From 31f08c1893a4a0182d572b48ab6789dc5794e541 Mon Sep 17 00:00:00 2001 From: jean-christophe81 <98889244+jean-christophe81@users.noreply.github.com> Date: Mon, 13 May 2024 11:05:11 +0200 Subject: [PATCH 01/60] workaround grpc crash (#1313) --- broker/doc/broker-doc.md | 3 ++- broker/grpc/src/stream.cc | 48 ++++++++++++++++++++++++++------------- 2 files changed, 34 insertions(+), 17 deletions(-) diff --git a/broker/doc/broker-doc.md b/broker/doc/broker-doc.md index 9c36df4fa02..82ecaaa30f4 100644 --- a/broker/doc/broker-doc.md +++ b/broker/doc/broker-doc.md @@ -206,7 +206,8 @@ When BAM is stopped (broker is stopped or reloaded), living data are saved into #### caution -grpc threads block at shutdown if grpc object aren't cleanly stopped. For example, we must call ClientBeReactor::Finish before delete. That's why grpc::stream::stop must be called before destruction (shared_ptr< stream >::reset()). So be careful to not forget a case (a catch handler) +grpc threads block at shutdown if grpc object aren't cleanly stopped. For example, we must call ClientBeReactor::Finish before delete. That's why grpc::stream::stop must be called before destruction (shared_ptr< stream >::reset()). So be careful to not forget a case (a catch handler). +Another issue: channel is owned both by connector and client stream context. At shutdown, if the last owner is client stream object, client destructor is called by OnDone method called by a grpc thread. Then channel destructor is called by grpc thread. The issue is that channel destructor tries to join current grpc thread. The solution is to leave stream destruction job to asio threads. #### Main classes diff --git a/broker/grpc/src/stream.cc b/broker/grpc/src/stream.cc index ef668fbb328..dc16361e3ee 100644 --- a/broker/grpc/src/stream.cc +++ b/broker/grpc/src/stream.cc @@ -24,6 +24,7 @@ #include "com/centreon/broker/exceptions/connection_closed.hh" #include "com/centreon/broker/grpc/grpc_bridge.hh" #include "com/centreon/broker/misc/string.hh" +#include "com/centreon/broker/pool.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon::broker::grpc; @@ -368,11 +369,18 @@ int32_t stream::write(std::shared_ptr const& d) { template void stream::OnDone() { stop(); - std::lock_guard l(_instances_m); - SPDLOG_LOGGER_DEBUG(log_v2::grpc(), "{:p} server::OnDone()", - static_cast(this)); - _instances.erase(std::enable_shared_from_this< - stream>::shared_from_this()); + /**grpc has a bug, sometimes if we delete this class in this handler as it is + * described in examples, it also deletes used channel and does a pthread_join + * of the current thread witch go to a EDEADLOCK error and call grpc::Crash. + * So we uses asio thread to do the job + */ + pool::io_context().post([me = std::enable_shared_from_this< + stream>::shared_from_this()]() { + std::lock_guard l(_instances_m); + SPDLOG_LOGGER_DEBUG(log_v2::grpc(), "{:p} server::OnDone()", + static_cast(me.get())); + _instances.erase(std::static_pointer_cast>(me)); + }); } /** @@ -385,12 +393,20 @@ void stream::OnDone() { template void stream::OnDone(const ::grpc::Status& status) { stop(); - std::lock_guard l(_instances_m); - SPDLOG_LOGGER_DEBUG(log_v2::grpc(), "{:p} client::OnDone({}) {}", - static_cast(this), status.error_message(), - status.error_details()); - _instances.erase(std::enable_shared_from_this< - stream>::shared_from_this()); + /**grpc has a bug, sometimes if we delete this class in this handler as it is + * described in examples, it also deletes used channel and does a + * pthread_join of the current thread witch go to a EDEADLOCK error and call + * grpc::Crash. So we uses asio thread to do the job + */ + pool::io_context().post([me = std::enable_shared_from_this< + stream>::shared_from_this(), + status]() { + std::lock_guard l(_instances_m); + SPDLOG_LOGGER_DEBUG(log_v2::grpc(), "{:p} client::OnDone({}) {}", + static_cast(me.get()), status.error_message(), + status.error_details()); + _instances.erase(std::static_pointer_cast>(me)); + }); } /** @@ -423,11 +439,11 @@ int32_t stream::flush() { */ template int32_t stream::stop() { - bool expected = true; - SPDLOG_LOGGER_DEBUG(log_v2::grpc(), "{:p} {}::stop", static_cast(this), - _class_name); - if (_alive.compare_exchange_strong(expected, false)) { - std::lock_guard l(_protect); + std::lock_guard l(_protect); + if (_alive) { + SPDLOG_LOGGER_DEBUG(log_v2::grpc(), "{:p} {}::stop", + static_cast(this), _class_name); + _alive = false; this->shutdown(); } return 0; From 15fc46fd6e12849293f829df6c62b60c2e29b8d8 Mon Sep 17 00:00:00 2001 From: jean-christophe81 <98889244+jean-christophe81@users.noreply.github.com> Date: Tue, 14 May 2024 09:48:40 +0200 Subject: [PATCH 02/60] enh(engine): Engine can be started with configuration files that complete the current ones When engine is started, there is now a '-c' option to specify a configuration file. REFS: MON-34326 --- broker/neb/CMakeLists.txt | 1 - broker/neb/precomp_inc/precomp.hpp | 2 + broker/neb/src/broker.cc | 11 + broker/test/CMakeLists.txt | 1 + common/CMakeLists.txt | 15 +- common/inc/com/centreon/common/hex_dump.hh | 1 - .../inc/com/centreon/common/node_allocator.hh | 2 - .../inc/com/centreon/common/process_stat.hh | 3 - .../com/centreon/common/rapidjson_helper.hh | 460 ++++++++++++++ common/precomp_inc/precomp.hh | 54 ++ common/src/hex_dump.cc | 5 +- common/src/process_stat.cc | 8 +- common/src/rapidjson_helper.cc | 449 +++++++++++++ common/test/CMakeLists.txt | 37 +- common/test/hex_dump_test.cc | 4 +- common/test/node_allocator_test.cc | 2 +- common/test/process_stat_test.cc | 2 +- common/test/rapidjson_helper_test.cc | 100 +++ engine/CMakeLists.txt | 4 +- engine/enginerpc/engine_impl.cc | 40 +- .../engine/configuration/extended_conf.hh | 71 +++ .../centreon/engine/configuration/state.hh | 66 +- engine/inc/com/centreon/engine/log_v2.hh | 7 +- .../external_commands/precomp_inc/precomp.hh | 2 + engine/precomp_inc/precomp.hh | 5 +- engine/src/checkable.cc | 35 +- engine/src/configuration/CMakeLists.txt | 27 +- engine/src/configuration/applier/state.cc | 34 +- engine/src/configuration/extended_conf.cc | 87 +++ engine/src/configuration/state.cc | 588 ++++++++++-------- engine/src/events/loop.cc | 42 +- engine/src/main.cc | 69 +- engine/tests/CMakeLists.txt | 1 + .../configuration/applier/applier-state.cc | 44 ++ tests/engine/extended_conf.robot | 59 ++ tests/resources/Engine.py | 27 + vcpkg.json | 9 +- 37 files changed, 1909 insertions(+), 465 deletions(-) create mode 100644 common/inc/com/centreon/common/rapidjson_helper.hh create mode 100644 common/precomp_inc/precomp.hh create mode 100644 common/src/rapidjson_helper.cc create mode 100644 common/test/rapidjson_helper_test.cc create mode 100644 engine/inc/com/centreon/engine/configuration/extended_conf.hh create mode 100644 engine/src/configuration/extended_conf.cc create mode 100644 tests/engine/extended_conf.robot diff --git a/broker/neb/CMakeLists.txt b/broker/neb/CMakeLists.txt index dfdf7b7521a..5c9476c114d 100644 --- a/broker/neb/CMakeLists.txt +++ b/broker/neb/CMakeLists.txt @@ -129,7 +129,6 @@ target_link_libraries(${NEB} spdlog::spdlog) set_target_properties("${NEB}" PROPERTIES PREFIX "") -target_precompile_headers(${NEB} REUSE_FROM nebbase) install(TARGETS "${NEB}" LIBRARY DESTINATION "${PREFIX_MODULES}") # Centreon Engine/Nagios module. diff --git a/broker/neb/precomp_inc/precomp.hpp b/broker/neb/precomp_inc/precomp.hpp index 41ab3419640..4885e5ba3e0 100644 --- a/broker/neb/precomp_inc/precomp.hpp +++ b/broker/neb/precomp_inc/precomp.hpp @@ -48,4 +48,6 @@ namespace asio = boost::asio; #include #include +#include + #endif diff --git a/broker/neb/src/broker.cc b/broker/neb/src/broker.cc index 7fab5c2fec5..0e1e1d218ba 100644 --- a/broker/neb/src/broker.cc +++ b/broker/neb/src/broker.cc @@ -16,6 +16,17 @@ * For more information : contact@centreon.com */ +#include + +#include + +#include +#include + +#include + +namespace asio = boost::asio; + #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/io/protocols.hh" #include "com/centreon/broker/log_v2.hh" diff --git a/broker/test/CMakeLists.txt b/broker/test/CMakeLists.txt index 7b677b49c1a..9469ce778a3 100644 --- a/broker/test/CMakeLists.txt +++ b/broker/test/CMakeLists.txt @@ -75,6 +75,7 @@ target_link_libraries( rpc_client berpc centreon_common + spdlog::spdlog -L${PROTOBUF_LIB_DIR} gRPC::gpr gRPC::grpc gRPC::grpc++ gRPC::grpc++_alts crypto ssl diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt index 391d1c5a9e6..faef6dc9663 100644 --- a/common/CMakeLists.txt +++ b/common/CMakeLists.txt @@ -20,7 +20,7 @@ project("Centreon common" C CXX) # Set directories. -set(INCLUDE_DIR "${PROJECT_SOURCE_DIR}/inc") +set(INCLUDE_DIR "${PROJECT_SOURCE_DIR}/inc/com/centreon/common") set(SRC_DIR "${PROJECT_SOURCE_DIR}/src") set(TEST_DIR "${PROJECT_SOURCE_DIR}/test") @@ -41,17 +41,26 @@ add_custom_command( WORKING_DIRECTORY ${CMAKE_BINARY_DIR}) # Set sources. -set(SOURCES ${SRC_DIR}/process_stat.cc ${SRC_DIR}/process_stat.pb.cc - ${SRC_DIR}/process_stat.grpc.pb.cc ${SRC_DIR}/hex_dump.cc) +set(SOURCES + ${SRC_DIR}/hex_dump.cc + ${SRC_DIR}/process_stat.cc + ${SRC_DIR}/process_stat.pb.cc + ${SRC_DIR}/process_stat.grpc.pb.cc + ${SRC_DIR}/rapidjson_helper.cc +) # Include directories. include_directories("${INCLUDE_DIR}" ${VCPKG_INCLUDE_DIR} ) +add_definitions(-DSPDLOG_ACTIVE_LEVEL=SPDLOG_LEVEL_TRACE) add_library(centreon_common STATIC ${SOURCES}) +target_include_directories(centreon_common PRIVATE ${INCLUDE_DIR}) set_property(TARGET centreon_common PROPERTY POSITION_INDEPENDENT_CODE ON) +target_precompile_headers(centreon_common PRIVATE precomp_inc/precomp.hh) + if(WITH_TESTING) add_subdirectory(test) endif() diff --git a/common/inc/com/centreon/common/hex_dump.hh b/common/inc/com/centreon/common/hex_dump.hh index 111bc16c694..1782c8f6ac8 100644 --- a/common/inc/com/centreon/common/hex_dump.hh +++ b/common/inc/com/centreon/common/hex_dump.hh @@ -19,7 +19,6 @@ #ifndef CCCM_HEX_DUMP_HH #define CCCM_HEX_DUMP_HH -#include namespace com::centreon::common { diff --git a/common/inc/com/centreon/common/node_allocator.hh b/common/inc/com/centreon/common/node_allocator.hh index 2e9b9a8db5e..d3913902c70 100644 --- a/common/inc/com/centreon/common/node_allocator.hh +++ b/common/inc/com/centreon/common/node_allocator.hh @@ -23,8 +23,6 @@ #include #include #include -#include -#include namespace boost::interprocess { diff --git a/common/inc/com/centreon/common/process_stat.hh b/common/inc/com/centreon/common/process_stat.hh index d57a7791997..0113d09afc6 100644 --- a/common/inc/com/centreon/common/process_stat.hh +++ b/common/inc/com/centreon/common/process_stat.hh @@ -19,12 +19,9 @@ #ifndef CCCM_PROCESS_STAT_HH #define CCCM_PROCESS_STAT_HH -#include #include #include -#include -#include namespace com::centreon::common { diff --git a/common/inc/com/centreon/common/rapidjson_helper.hh b/common/inc/com/centreon/common/rapidjson_helper.hh new file mode 100644 index 00000000000..a7039dfeea5 --- /dev/null +++ b/common/inc/com/centreon/common/rapidjson_helper.hh @@ -0,0 +1,460 @@ +/** + * Copyright 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#ifndef CCE_RAPIDJSON_HELPER_HH +#define CCE_RAPIDJSON_HELPER_HH + +#include +#include +#include + +#include "com/centreon/exceptions/msg_fmt.hh" + +namespace com::centreon::common { + +class json_validator; + +/** + * @brief this class is a helper to rapidjson to get a similar API to + * nlohmann_json library + * Another drawback, rapidjson doesn't throw but assert + * so we test and throw before calling accessors + * + * usage: + * @code {.c++} + * rapidjson::Document doc; + * rapidjson_helper json(doc); + * for (const auto doc_member: json) { + * rapidjson_helper json_member(doc_member.value); + * try { + * std::string_view toto = json_member.get_string("titi"); + * } + * catch (const std::exception &e) { + * SPDLOG_LOGGER_ERROR(spdlg, "titi not found in {} : {}", + * doc_member.value, e.what()); + * } + * } + * + * @endcode + * + * The constructor is not expensive, object only get a reference to constructor + * parameter So this object can be used on the fly: + * @code {.c++} + * rapidjson::Document doc; + * rapidjson_helper(doc).get_string("ererzr"); + * @endcode + * + * + * Beware, the life time of the json value passed to the constructor must exceed + * the lifetime of the rapidjson_helper + * + */ +class rapidjson_helper { + const rapidjson::Value& _val; + + public: + /** + * @brief Construct a new rapidjson helper object + * + * @param val + */ + rapidjson_helper(const rapidjson::Value& val) : _val(val) {} + + /** + * @brief deleted in order to forbid rvalue + * + * @param val + */ + rapidjson_helper(rapidjson::Value&& val) = delete; + + /** + * @brief allow to use for (const auto & member: val) + * + * @return rapidjson::Value::ConstValueIterator + */ + rapidjson::Value::ConstValueIterator begin() const; + + rapidjson::Value::ConstValueIterator end() const { return _val.End(); } + + /** + * @brief this method simplify access to rapid json value + * if field is not found or has not the correct type, it throws an exception + * this method is used by the following getters + * + * @tparam return_type const char *, double, uint64_t ..... + * @param field_name member field name + * @param type_name type that will be described in exception message + * @param original_type_tester Value method like IsString + * @param original_getter Value getter like GetString + * @return * template value returned by original + * getter + */ + template + return_type get(const char* field_name, + const char* type_name, + bool (rapidjson::Value::*original_type_tester)() const, + return_type (rapidjson::Value::*original_getter)() + const) const { + if (!_val.IsObject()) { + throw exceptions::msg_fmt("not an object parent of field {}", field_name); + } + auto member = _val.FindMember(field_name); + if (member == _val.MemberEnd()) { + throw exceptions::msg_fmt("no field {}", field_name); + } + if (!(member->value.*original_type_tester)()) { + throw exceptions::msg_fmt("field {} is not a {}", field_name, type_name); + } + + return (member->value.*original_getter)(); + } + + /** + * @brief this method simplify access to rapid json value + * if field is not found or has not the correct type, it throws an exception + * this method is used by the following getters + * It also allows number contained in string "456" + * The conversion param for string is passed in last param + * + * @tparam return_type double, uint64_t + * @param field_name member field name + * @param type_name type that will be described in exception message + * @param original_type_tester Value method like IsString + * @param original_getter Value getter like GetString + * @param simple_ato absl::SimpleAtoi Atod..... + * @return * template value returned by original + * getter + */ + template + return_type get(const char* field_name, + const char* type_name, + const type_tester& tester, + return_type (rapidjson::Value::*original_getter)() const, + bool (*simple_ato)(absl::string_view, return_type*)) const { + if (!_val.IsObject()) { + throw exceptions::msg_fmt("not an object parent of field {}", field_name); + } + auto member = _val.FindMember(field_name); + if (member == _val.MemberEnd()) { + throw exceptions::msg_fmt("no field {}", field_name); + } + if (tester(member->value)) { + return (member->value.*original_getter)(); + } + if (member->value.IsString()) { + return_type ret; + if (!simple_ato(member->value.GetString(), &ret)) { + throw exceptions::msg_fmt("field {} is not a {} string", field_name, + type_name); + } + return ret; + } else { + throw exceptions::msg_fmt("field {} is not a {}", field_name, type_name); + } + } + + /** + * @brief this method simplify access to rapid json value + * if field is not found it returns default + * if has not the correct type, it throws an exception + * this method is used by the following getters + * It also allows number contained in string "456" + * The conversion param for string is passed in last param + * + * @tparam return_type double, uint64_t + * @param field_name member field name + * @param type_name type that will be described in exception message + * @param original_type_tester Value method like IsString + * @param original_getter Value getter like GetString + * @param default_value value returned if field is missing + * @return * template value returned by original + * getter + */ + template + return_type get_or_default(const char* field_name, + const char* type_name, + const type_tester& original_type_tester, + return_type (rapidjson::Value::*original_getter)() + const, + const return_type& default_value) const { + if (!_val.IsObject()) { + throw exceptions::msg_fmt("not an object parent of field {}", field_name); + } + auto member = _val.FindMember(field_name); + if (member == _val.MemberEnd()) { + return default_value; + } + if (!(member->value.*original_type_tester)()) { + throw exceptions::msg_fmt("field {} is not a {}", field_name, type_name); + } + + return (member->value.*original_getter)(); + } + + /** + * @brief this method simplify access to rapid json value + * if field is not found it returns default + * if has not the correct type, it throws an exception + * this method is used by the following getters + * It also allows number contained in string "456" + * The conversion param for string is passed in last param + * + * @tparam return_type double, uint64_t + * @param field_name member field name + * @param type_name type that will be described in exception message + * @param original_type_tester Value method like IsString + * @param original_getter Value getter like GetString + * @param simple_ato absl::SimpleAtoi Atod..... + * @param default_value value returned if field is missing + * @return * template value returned by original + * getter + */ + template + return_type get_or_default(const char* field_name, + const char* type_name, + const type_tester& tester, + return_type (rapidjson::Value::*original_getter)() + const, + bool (*simple_ato)(absl::string_view, + return_type*), + const return_type& default_value) const { + if (!_val.IsObject()) { + throw exceptions::msg_fmt("not an object parent of field {}", field_name); + } + auto member = _val.FindMember(field_name); + if (member == _val.MemberEnd()) { + return default_value; + } + if (tester(member->value)) { + return (member->value.*original_getter)(); + } + if (member->value.IsString()) { + return_type ret; + if (!simple_ato(member->value.GetString(), &ret)) { + throw exceptions::msg_fmt("field {} is not a {} string", field_name, + type_name); + } + return ret; + } else { + throw exceptions::msg_fmt("field {} is not a {}", field_name, type_name); + } + } + + const char* get_string(const char* field_name) const; + const char* get_string(const char* field_name, + const char* default_value) const; + + double get_double(const char* field_name) const; + float get_float(const char* field_name) const; + + uint64_t get_uint64_t(const char* field_name) const; + int64_t get_int64_t(const char* field_name) const; + + uint32_t get_uint32_t(const char* field_name) const; + int32_t get_int32_t(const char* field_name) const; + + uint16_t get_uint16_t(const char* field_name) const; + int16_t get_int16_t(const char* field_name) const; + + unsigned get_unsigned(const char* field_name) const; + unsigned get_unsigned(const char* field_name, unsigned default_value) const; + + int get_int(const char* field_name) const; + + int get_int(const char* field_name, int default_value) const; + + bool get_bool(const char* field_name) const; + + bool get_bool(const char* field_name, bool default_value) const; + + // as overriding can't be done with returned type, we use a templated method + template + value_type get(const char* field_name); + + const rapidjson::Value& get_member(const char* field_name) const; + + /** + * @brief no assert if _val is not an object + * + * @param field_name + * @return true has the member + * @return false is not an object or has not this field + */ + bool has_member(const char* field_name) const { + return _val.IsObject() && _val.HasMember(field_name); + } + + void validate(json_validator& validator); + + static rapidjson::Document read_from_file(const std::string_view& path); + + static rapidjson::Document read_from_string( + const std::string_view& json_content); +}; + +/** + * @brief by default doesn't compile + * Only following specializations are valid + * + * @tparam value_type std::string, uint64_t, double.... + * @param field_name + * @return value_type + */ +template +inline value_type rapidjson_helper::get(const char* field_name) { + class not_convertible {}; + static_assert(std::is_convertible::value); +} + +template <> +inline std::string rapidjson_helper::get(const char* field_name) { + return get_string(field_name); +} + +template <> +inline double rapidjson_helper::get(const char* field_name) { + return get_double(field_name); +} + +template <> +inline float rapidjson_helper::get(const char* field_name) { + return get_float(field_name); +} + +template <> +inline uint64_t rapidjson_helper::get(const char* field_name) { + return get_uint64_t(field_name); +} + +template <> +inline int64_t rapidjson_helper::get(const char* field_name) { + return get_int64_t(field_name); +} + +template <> +inline uint32_t rapidjson_helper::get(const char* field_name) { + return get_uint32_t(field_name); +} + +template <> +inline int32_t rapidjson_helper::get(const char* field_name) { + return get_int32_t(field_name); +} + +template <> +inline uint16_t rapidjson_helper::get(const char* field_name) { + return get_uint16_t(field_name); +} + +template <> +inline int16_t rapidjson_helper::get(const char* field_name) { + return get_int16_t(field_name); +} + +template <> +inline bool rapidjson_helper::get(const char* field_name) { + return get_bool(field_name); +} + +/** + * @brief This class is helper to build json validator from a json string + * Example: + * @code {.c++} + * json_validator valid("R( + * { + * "$schema": "http://json-schema.org/draft-07/schema#", + * "type": "object" + * } + * )"); + * + * rapidjson::Document to_validate; + * rapidjson_helper doc(to_validate); + * std::lock_guard l(valid); + * try { + * doc.validate(valid); + * } catch (const std::exception &e) { + * SPDLOG_LOGGER_ERROR(logger, "bad document: {}", e.what()); + * } + * + * @endcode + * + * + */ +class json_validator { + rapidjson::SchemaDocument _schema; + std::string _json_schema; + friend class rapidjson_helper; + + public: + json_validator(const json_validator&) = delete; + json_validator& operator=(const json_validator&) = delete; + + json_validator(const std::string_view& json_schema); + + const std::string& get_json_schema() const { return _json_schema; } +}; + +namespace literals { + +/** + * @brief string literal to create rapidjson::Document + * @code {.c++} + * using com::centreon::common::literals; + * rapidjson::Document doc = "R( + * { + * "$schema": "http://json-schema.org/draft-07/schema#", + * "type": "object" + * } + * )_json" + * + * @endcode + * + * + */ +inline rapidjson::Document operator"" _json(const char* s, std::size_t n) { + return rapidjson_helper::read_from_string(std::string_view(s, n)); +} + +} // namespace literals +} // namespace com::centreon::common + +namespace fmt { + +template <> +struct formatter : formatter { + constexpr auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) { + return ctx.begin(); + } + + // Formats a rapidjson::Value + template + auto format(const rapidjson::Value& val, FormatContext& ctx) const + -> decltype(ctx.out()) { + using namespace rapidjson; + + StringBuffer buffer; + Writer writer(buffer); + val.Accept(writer); + + return formatter::format( + {buffer.GetString(), buffer.GetLength()}, ctx); + } +}; +} // namespace fmt + +#endif diff --git a/common/precomp_inc/precomp.hh b/common/precomp_inc/precomp.hh new file mode 100644 index 00000000000..6af5512cfee --- /dev/null +++ b/common/precomp_inc/precomp.hh @@ -0,0 +1,54 @@ +/* + * Copyright 2022 Centreon (https://www.centreon.com/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ + +#ifndef CCB_HTTP_CLIENT_PRECOMP_HH +#define CCB_HTTP_CLIENT_PRECOMP_HH + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include + +#include +#include + +#include +#include +#include +#include + +#include "com/centreon/exceptions/msg_fmt.hh" + + +namespace asio = boost::asio; + +#endif // CCB_HTTP_CLIENT_PRECOMP_HH diff --git a/common/src/hex_dump.cc b/common/src/hex_dump.cc index eabd5e70f0c..9a2c34caf51 100644 --- a/common/src/hex_dump.cc +++ b/common/src/hex_dump.cc @@ -16,9 +16,8 @@ * For more information : contact@centreon.com */ -#include -#include "com/centreon/common/hex_dump.hh" +#include "hex_dump.hh" inline void char_to_hex(unsigned char c, std::string& output) noexcept { unsigned char val = c >> 4; @@ -30,7 +29,7 @@ inline void char_to_hex(unsigned char c, std::string& output) noexcept { /** * @brief return a string in an hex format * format depends on nb_char_per_line - * if nb_char_per_line <= 0 dump is only an haxa string + * if nb_char_per_line <= 0 dump is only an hexa string * if nb_char_per_line > 0 dump is like 0000 xxxxxxxx abcd * * @param buffer diff --git a/common/src/process_stat.cc b/common/src/process_stat.cc index 2d165d2b923..7ae145d0d94 100644 --- a/common/src/process_stat.cc +++ b/common/src/process_stat.cc @@ -16,18 +16,12 @@ * For more information : contact@centreon.com */ -#include -#include - -#include -#include -#include #include #include #include -#include "com/centreon/common/process_stat.hh" +#include "process_stat.hh" using namespace com::centreon::common; diff --git a/common/src/rapidjson_helper.cc b/common/src/rapidjson_helper.cc new file mode 100644 index 00000000000..5663af59b64 --- /dev/null +++ b/common/src/rapidjson_helper.cc @@ -0,0 +1,449 @@ +/** + * Copyright 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#include +#include +#include +#include + +#include "rapidjson_helper.hh" + +using namespace com::centreon::common; + +namespace com::centreon::common::detail { + +class string_view_stream { + const std::string_view _src; + std::string_view::const_iterator _current; + + public: + using Ch = char; + + string_view_stream(const std::string_view src) : _src(src) { + _current = _src.begin(); + } + + inline Ch Peek() const { return _current >= _src.end() ? '\0' : *_current; } + inline Ch Take() { return _current >= _src.end() ? '\0' : *_current++; } + inline size_t Tell() const { + return static_cast(_current - _src.begin()); + } + + Ch* PutBegin() { + RAPIDJSON_ASSERT(false); + return 0; + } + void Put(Ch) { RAPIDJSON_ASSERT(false); } + void Flush() { RAPIDJSON_ASSERT(false); } + size_t PutEnd(Ch*) { + RAPIDJSON_ASSERT(false); + return 0; + } +}; + +}; // namespace com::centreon::common::detail + +/** + * @brief allow to use for (const auto & member: val) + * + * @return rapidjson::Value::ConstValueIterator + * @throw msg_fmt if oject is not an array + */ +rapidjson::Value::ConstValueIterator rapidjson_helper::begin() const { + if (!_val.IsArray()) { + throw exceptions::msg_fmt("object is not an array:{}", _val); + } + return _val.Begin(); +} + +/** + * @brief read a string field + * + * @param field_name + * @return const char* field value + * @throw msg_fmt if member does not exist or field value is not a string + */ +const char* rapidjson_helper::get_string(const char* field_name) const { + return get(field_name, "string", &rapidjson::Value::IsString, + &rapidjson::Value::GetString); +} + +const char* rapidjson_helper::get_string(const char* field_name, + const char* default_value) const { + return get_or_default( + field_name, "string", &rapidjson::Value::IsString, + &rapidjson::Value::GetString, default_value); +} + +/** + * @brief read a double field + * + * @param field_name + * @return const char* field value + * @throw msg_fmt if member does not exist or field value is nor a double nor a + * string containing a double + */ +double rapidjson_helper::get_double(const char* field_name) const { + return get( + field_name, "double", + [](const rapidjson::Value& val) { + return val.IsDouble() || val.IsInt() || val.IsUint() || val.IsInt64() || + val.IsUint64(); + }, + &rapidjson::Value::GetDouble, &absl::SimpleAtod); +} + +/** + * @brief read a float field + * + * @param field_name + * @return const char* field value + * @throw msg_fmt if member does not exist or field value is nor a float nor a + * string containing a float + */ +float rapidjson_helper::get_float(const char* field_name) const { + return get( + field_name, "float", + [](const rapidjson::Value& val) { + return val.IsFloat() || val.IsInt() || val.IsUint() || val.IsInt64() || + val.IsUint64(); + }, + &rapidjson::Value::GetFloat, &absl::SimpleAtof); +} + +/** + * @brief read a uint64_t field + * + * @param field_name + * @return const char* field value + * @throw msg_fmt if member does not exist or field value is nor a uint64_t nor + * a string containing a uint64_t + */ +uint64_t rapidjson_helper::get_uint64_t(const char* field_name) const { + return get( + field_name, "uint64", + [](const rapidjson::Value& val) { return val.IsUint64(); }, + &rapidjson::Value::GetUint64, &absl::SimpleAtoi); +} + +/** + * @brief read a int64_t field + * + * @param field_name + * @return const char* field value + * @throw msg_fmt if member does not exist or field value is nor a int64_t nor + * a string containing a int64_t + */ +int64_t rapidjson_helper::get_int64_t(const char* field_name) const { + return get( + field_name, "int64", + [](const rapidjson::Value& val) { return val.IsInt64(); }, + &rapidjson::Value::GetInt64, &absl::SimpleAtoi); +} + +/** + * @brief read a uint32_t field + * + * @param field_name + * @return const char* field value + * @throw msg_fmt if member does not exist or field value is nor a uint32_t nor + * a string containing a uint32_t + */ +uint32_t rapidjson_helper::get_uint32_t(const char* field_name) const { + uint64_t to_test = get_uint64_t(field_name); + if (to_test > std::numeric_limits::max()) { + throw exceptions::msg_fmt("field {}:uint32_t overflow {}", field_name, + to_test); + } + return to_test; +} + +/** + * @brief read a int32_t field + * + * @param field_name + * @return const char* field value + * @throw msg_fmt if member does not exist or field value is nor a int32_t nor + * a string containing a int32_t + */ +int32_t rapidjson_helper::get_int32_t(const char* field_name) const { + int64_t to_test = get_int64_t(field_name); + if (to_test > std::numeric_limits::max() || + to_test < std::numeric_limits::min()) { + throw exceptions::msg_fmt("field {}:int32_t overflow {}", field_name, + to_test); + } + return to_test; +} + +/** + * @brief read a uint16_t field + * + * @param field_name + * @return const char* field value + * @throw msg_fmt if member does not exist or field value is nor a uint16_t nor + * a string containing a uint16_t + */ +uint16_t rapidjson_helper::get_uint16_t(const char* field_name) const { + uint64_t to_test = get_uint64_t(field_name); + if (to_test > std::numeric_limits::max()) { + throw exceptions::msg_fmt("field {}:uint16_t overflow {}", field_name, + to_test); + } + return to_test; +} + +/** + * @brief read a int16_t field + * + * @param field_name + * @return const char* field value + * @throw msg_fmt if member does not exist or field value is nor a int16_t nor + * a string containing a int16_t + */ +int16_t rapidjson_helper::get_int16_t(const char* field_name) const { + int64_t to_test = get_int64_t(field_name); + if (to_test > std::numeric_limits::max() || + to_test < std::numeric_limits::min()) { + throw exceptions::msg_fmt("field {}:int16_t overflow {}", field_name, + to_test); + } + return to_test; +} + +/** + * @brief read an unsigned integer field + * + * @param field_name + * @param default_value value returned if member does not exist + * @return const char* field value + * @throw msg_fmt if field value is nor a integer nor a + * string containing a integer + */ +unsigned rapidjson_helper::get_unsigned(const char* field_name, + unsigned default_value) const { + return get_or_default( + field_name, "unsigned int", + [](const rapidjson::Value& val) { return val.IsUint(); }, + &rapidjson::Value::GetUint, &absl::SimpleAtoi, default_value); +} + +/** + * @brief read an unsigned int field + * + * @param field_name + * @return const char* field value + * @throw msg_fmt if member does not exist or field value is nor a uint nor a + * string containing a uint + */ +unsigned rapidjson_helper::get_unsigned(const char* field_name) const { + return get( + field_name, "unsigned int", + [](const rapidjson::Value& val) { return val.IsUint(); }, + &rapidjson::Value::GetUint, &absl::SimpleAtoi); +} + +/** + * @brief read a integer field + * + * @param field_name + * @param default_value value returned if member does not exist + * @return const char* field value + * @throw msg_fmt if field value is nor a integer nor a + * string containing a integer + */ +int rapidjson_helper::get_int(const char* field_name, int default_value) const { + return get_or_default( + field_name, "integer", + [](const rapidjson::Value& val) { return val.IsInt(); }, + &rapidjson::Value::GetInt, &absl::SimpleAtoi, default_value); +} + +/** + * @brief read a integer field + * + * @param field_name + * @return const char* field value + * @throw msg_fmt if member does not exist or field value is nor a integer nor a + * string containing a integer + */ +int rapidjson_helper::get_int(const char* field_name) const { + return get( + field_name, "integer", + [](const rapidjson::Value& val) { return val.IsInt(); }, + &rapidjson::Value::GetInt, &absl::SimpleAtoi); +} + +/** + * @brief read a boolean field + * + * @param field_name + * @return const char* field value + * @throw msg_fmt if member does not exist or field value is nor a boolean nor a + * string containing a boolean + */ +bool rapidjson_helper::get_bool(const char* field_name) const { + return get( + field_name, "boolean", + [](const rapidjson::Value& val) { return val.IsBool(); }, + &rapidjson::Value::GetBool, &absl::SimpleAtob); +} + +/** + * @brief read a boolean field + * + * @param field_name + * @param default_value value returned if member does not exist + * @return const char* field value + * @throw msg_fmt if field value is nor a boolean nor a + * string containing a boolean + */ +bool rapidjson_helper::get_bool(const char* field_name, + bool default_value) const { + return get_or_default( + field_name, "boolean", + [](const rapidjson::Value& val) { return val.IsBool(); }, + &rapidjson::Value::GetBool, &absl::SimpleAtob, default_value); +} + +/** + * @brief return a member + * + * @param field_name + * @return const rapidjson::Value& member + * @throw msg_fmt if member does not exist + */ +const rapidjson::Value& rapidjson_helper::get_member( + const char* field_name) const { + auto member = _val.FindMember(field_name); + if (member == _val.MemberEnd()) { + throw exceptions::msg_fmt("no field {}", field_name); + } + return member->value; +} + +/** + * @brief load and parse a json from a file + * + * @param path + * @return rapidjson::Document + */ +rapidjson::Document rapidjson_helper::read_from_file( + const std::string_view& path) { + FILE* to_close = fopen(path.data(), "r+b"); + if (!to_close) { + throw exceptions::msg_fmt("Fail to read file '{}' : {}", path, + strerror(errno)); + } + std::unique_ptr f(to_close, fclose); + + char read_buffer[0x10000]; + rapidjson::FileReadStream input_stream(f.get(), read_buffer, + sizeof(read_buffer)); + + rapidjson::Document json_doc; + json_doc.ParseStream(input_stream); + + if (json_doc.HasParseError()) { + throw exceptions::msg_fmt( + "Error: File '{}' should be a json " + "file: {} at offset {}", + path, rapidjson::GetParseError_En(json_doc.GetParseError()), + json_doc.GetErrorOffset()); + } + return json_doc; +} + +/** + * @brief parse json given in json_content + * + * @param json_content + * @return rapidjson::Document + */ +rapidjson::Document rapidjson_helper::read_from_string( + const std::string_view& json_content) { + detail::string_view_stream s(json_content); + + rapidjson::Document json_doc; + json_doc.ParseStream(s); + + if (json_doc.HasParseError()) { + throw exceptions::msg_fmt( + "Error: json is not correct: {} at offset {}", + rapidjson::GetParseError_En(json_doc.GetParseError()), + json_doc.GetErrorOffset()); + } + return json_doc; +} + +/** + * @brief check if document owned by this class is conform to validator + * Example: + * @code {.c++} + * json_validator valid("R( + * { + * "$schema": "http://json-schema.org/draft-07/schema#", + * "type": "object" + * } + * )"); + * + * rapidjson::Document to_validate; + * rapidjson_helper doc(to_validate); + * try { + * doc.validate(valid); + * } catch (const std::exception &e) { + * SPDLOG_LOGGER_ERROR(logger, "bad document: {}", e.what()); + * } + * + * @endcode + * + * @param validator validator that contains json schema + * @throw msg_fmt if document is not validated + */ +void rapidjson_helper::validate(json_validator& validator) { + rapidjson::SchemaValidator valid(validator._schema); + if (!_val.Accept(valid)) { + rapidjson::StringBuffer sb; + valid.GetInvalidSchemaPointer().StringifyUriFragment(sb); + std::string err; + err = fmt::format("document doesn't respect this schema: {}\n", + validator.get_json_schema()); + if (sb.GetLength() > 1) { + err += "Invalid value for "; + err += sb.GetString(); + } + err += "\nProblem for schema keyword:"; + err += valid.GetInvalidSchemaKeyword(); + + sb.Clear(); + valid.GetInvalidDocumentPointer().StringifyUriFragment(sb); + if (sb.GetLength() > 1) { + err += fmt::format("\nInvalid document: {}", sb.GetString()); + } + throw std::invalid_argument(err); + } +} + +/** + * @brief Construct a new json validator::json validator object + * + * @param json_schema + */ +json_validator::json_validator(const std::string_view& json_schema) + : _schema(rapidjson_helper::read_from_string(json_schema)), + _json_schema(json_schema) {} diff --git a/common/test/CMakeLists.txt b/common/test/CMakeLists.txt index e0785fff0a7..18fafc9fbb5 100644 --- a/common/test/CMakeLists.txt +++ b/common/test/CMakeLists.txt @@ -16,17 +16,15 @@ # For more information : contact@centreon.com # -add_executable(ut_common process_stat_test.cc hex_dump_test.cc - node_allocator_test.cc) +add_executable(ut_common + process_stat_test.cc + hex_dump_test.cc + node_allocator_test.cc + rapidjson_helper_test.cc +) -# target_include_directories(ut_common ${CONAN_INCLUDE_DIRS_GTEST}) +add_test(NAME tests COMMAND ut_common) -target_link_libraries(ut_common PRIVATE centreon_common - GTest::gtest GTest::gtest_main GTest::gmock GTest::gmock_main - absl::any absl::log absl::base absl::bits - fmt::fmt pthread) - -add_dependencies(ut_common centreon_common) set_target_properties( ut_common @@ -35,3 +33,24 @@ set_target_properties( RUNTIME_OUTPUT_DIRECTORY_RELEASE ${CMAKE_BINARY_DIR}/tests RUNTIME_OUTPUT_DIRECTORY_RELWITHDEBINFO ${CMAKE_BINARY_DIR}/tests RUNTIME_OUTPUT_DIRECTORY_MINSIZEREL ${CMAKE_BINARY_DIR}/tests) + +target_link_libraries(ut_common PRIVATE + centreon_common + crypto + ssl + GTest::gtest + GTest::gtest_main + GTest::gmock + GTest::gmock_main + absl::any + absl::log + absl::base + absl::bits + fmt::fmt pthread) + +add_dependencies(ut_common centreon_common) + +set_property(TARGET ut_common PROPERTY POSITION_INDEPENDENT_CODE ON) + +target_precompile_headers(ut_common PRIVATE ${PROJECT_SOURCE_DIR}/precomp_inc/precomp.hh) + diff --git a/common/test/hex_dump_test.cc b/common/test/hex_dump_test.cc index 9db1988697f..0b6be680b5a 100644 --- a/common/test/hex_dump_test.cc +++ b/common/test/hex_dump_test.cc @@ -18,7 +18,7 @@ #include -#include "com/centreon/common/hex_dump.hh" +#include "hex_dump.hh" using namespace com::centreon::common; @@ -42,4 +42,4 @@ TEST(hex_dump, long_string) { "00 30313233343536373839414243444546 0123456789ABCDEF\n\ 10 4748494A4B4C4D4E4F50515253545556 GHIJKLMNOPQRSTUV\n\ 20 5758595A WXYZ\n"); -} \ No newline at end of file +} diff --git a/common/test/node_allocator_test.cc b/common/test/node_allocator_test.cc index d663abe264b..ce182aef8f1 100644 --- a/common/test/node_allocator_test.cc +++ b/common/test/node_allocator_test.cc @@ -19,7 +19,7 @@ #include #include -#include "com/centreon/common/node_allocator.hh" +#include "node_allocator.hh" using namespace com::centreon::common; diff --git a/common/test/process_stat_test.cc b/common/test/process_stat_test.cc index 91b1a839c43..79cd1bc4a9f 100644 --- a/common/test/process_stat_test.cc +++ b/common/test/process_stat_test.cc @@ -18,7 +18,7 @@ #include -#include "com/centreon/common/process_stat.hh" +#include "process_stat.hh" using namespace com::centreon::common; diff --git a/common/test/rapidjson_helper_test.cc b/common/test/rapidjson_helper_test.cc new file mode 100644 index 00000000000..384db3424d1 --- /dev/null +++ b/common/test/rapidjson_helper_test.cc @@ -0,0 +1,100 @@ +/** + * Copyright 2024 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ + +#include + +#include + +#include + +#include "com/centreon/exceptions/msg_fmt.hh" + +#include "rapidjson_helper.hh" + +using namespace com::centreon; +using namespace com::centreon::common; + +TEST(rapidjson_helper_test, unknown_file) { + ::unlink("/tmp/toto.json"); + ASSERT_THROW(rapidjson_helper::read_from_file("/tmp/toto.json"), + exceptions::msg_fmt); +} + +TEST(rapidjson_helper_test, bad_file) { + ::unlink("/tmp/toto.json"); + + std::ofstream oss("/tmp/toto.json"); + oss << "fkjsdgheirgiergegeg"; + oss.close(); + ASSERT_THROW(rapidjson_helper::read_from_file("/tmp/toto.json"), + exceptions::msg_fmt); +} + +TEST(rapidjson_helper_test, good_file) { + ::unlink("/tmp/toto.json"); + + std::ofstream oss("/tmp/toto.json"); + oss << R"( +{ + "int_val":5, + "s_int_val": "5", + "double":3.14, + "s_double": "3.14", + "double_1": 121345678, + "double_2": -123 +} +)"; + oss.close(); + auto json_doc = rapidjson_helper::read_from_file("/tmp/toto.json"); + rapidjson_helper test(json_doc); + + ASSERT_EQ(5, test.get_int("int_val")); + ASSERT_EQ(5, test.get_int("s_int_val")); + ASSERT_EQ(3.14, test.get_double("double")); + ASSERT_EQ(3.14, test.get_double("s_double")); + ASSERT_EQ(121345678, test.get_double("double_1")); + ASSERT_EQ(-123, test.get_double("double_2")); +} + +TEST(rapidjson_helper_test, bad_array) { + ::unlink("/tmp/toto.json"); + + std::ofstream oss("/tmp/toto.json"); + oss << R"( +{ + "toto": 5 +} +)"; + oss.close(); + auto json_doc = rapidjson_helper::read_from_file("/tmp/toto.json"); + rapidjson_helper test(json_doc); + ASSERT_THROW(test.begin(), exceptions::msg_fmt); +} + +TEST(rapidjson_helper_test, good_array) { + auto json_doc = rapidjson_helper::read_from_string(R"( +[ + { + "toto":1 + } +] +)"); + rapidjson_helper test(json_doc); + ASSERT_NO_THROW(test.begin()); +} diff --git a/engine/CMakeLists.txt b/engine/CMakeLists.txt index fa3f9c42ee9..a4aa5ef8d30 100644 --- a/engine/CMakeLists.txt +++ b/engine/CMakeLists.txt @@ -493,7 +493,9 @@ add_subdirectory(src/macros) add_subdirectory(modules) add_subdirectory(src/retention) add_subdirectory(enginerpc) -include_directories(enginerpc ${CMAKE_SOURCE_DIR}/common/src) +include_directories(enginerpc + ${CMAKE_SOURCE_DIR}/common/src + ${CMAKE_SOURCE_DIR}/common/inc) # Library engine target. add_library(enginelog STATIC src/log_v2.cc) diff --git a/engine/enginerpc/engine_impl.cc b/engine/enginerpc/engine_impl.cc index 5221f790b49..b8d5f7b2144 100644 --- a/engine/enginerpc/engine_impl.cc +++ b/engine/enginerpc/engine_impl.cc @@ -1,22 +1,20 @@ - -/* -* Copyright 2022 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ +/** + * Copyright 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include #include @@ -33,6 +31,8 @@ namespace asio = boost::asio; #include #include +#include + #include "com/centreon/common/process_stat.hh" #include "com/centreon/common/time.hh" #include "com/centreon/engine/host.hh" @@ -99,7 +99,7 @@ std::ostream& operator<<(std::ostream& str, const ServiceIdentifier& serv_id) { return str; } -} +} // namespace com::centreon::engine namespace fmt { template <> diff --git a/engine/inc/com/centreon/engine/configuration/extended_conf.hh b/engine/inc/com/centreon/engine/configuration/extended_conf.hh new file mode 100644 index 00000000000..48baeff71f0 --- /dev/null +++ b/engine/inc/com/centreon/engine/configuration/extended_conf.hh @@ -0,0 +1,71 @@ +/** + * Copyright 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#ifndef CCE_CONFIGURATION_EXTENDED_STATE_HH +#define CCE_CONFIGURATION_EXTENDED_STATE_HH + +#include "com/centreon/common/rapidjson_helper.hh" + +namespace com::centreon::engine::configuration { + +class state; + +/** + * @brief contain json data of a config file passed in param to centengine + * command line + * + */ +class extended_conf { + std::string _path; + struct stat _file_info; + rapidjson::Document _content; + + static std::list> _confs; + + public: + extended_conf(const std::string& path); + ~extended_conf() = default; + extended_conf(const extended_conf&) = delete; + extended_conf& operator=(const extended_conf&) = delete; + void reload(); + + static void update_state(state& dest); + + template + static void load_all(file_path_iterator begin, file_path_iterator); +}; + +/** + * @brief try to load all extra configuration files + * if one or more fail, we continue + * + * @tparam file_path_iterator + * @param begin + * @param end + */ +template +void extended_conf::load_all(file_path_iterator begin, file_path_iterator end) { + _confs.clear(); + for (; begin != end; ++begin) { + _confs.emplace_back(std::make_unique(*begin)); + } +} + +} // namespace com::centreon::engine::configuration + +#endif diff --git a/engine/inc/com/centreon/engine/configuration/state.hh b/engine/inc/com/centreon/engine/configuration/state.hh index 6f692a8a203..53f8b28997e 100644 --- a/engine/inc/com/centreon/engine/configuration/state.hh +++ b/engine/inc/com/centreon/engine/configuration/state.hh @@ -36,11 +36,22 @@ #include "com/centreon/engine/configuration/severity.hh" #include "com/centreon/engine/configuration/tag.hh" #include "com/centreon/engine/configuration/timeperiod.hh" +#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" -namespace com::centreon::engine { +namespace com::centreon::engine::configuration { -namespace configuration { +class setter_base { + protected: + const std::string_view _field_name; + + public: + setter_base(const std::string_view& field_name) : _field_name(field_name) {} + + virtual ~setter_base() = default; + virtual bool apply_from_cfg(state& obj, const char* value) = 0; + virtual bool apply_from_json(state& obj, const rapidjson::Document& doc) = 0; +}; /** * @class state state.hh @@ -169,8 +180,8 @@ class state { void date_format(date_type value); std::string const& debug_file() const noexcept; void debug_file(std::string const& value); - unsigned long long debug_level() const noexcept; - void debug_level(unsigned long long value); + uint64_t debug_level() const noexcept; + void debug_level(uint64_t value); unsigned int debug_verbosity() const noexcept; void debug_verbosity(unsigned int value); bool enable_environment_macros() const noexcept; @@ -437,9 +448,15 @@ class state { bool use_true_regexp_matching() const noexcept; void use_true_regexp_matching(bool value); - private: - typedef bool (*setter_func)(state&, char const*); + using setter_map = + absl::flat_hash_map>; + static const setter_map& get_setters() { return _setters; } + + void apply_extended_conf(const std::string& file_path, + const rapidjson::Document& json_doc); + private: + static void _init_setter(); void _set_aggregate_status_updates(std::string const& value); void _set_auth_file(std::string const& value); void _set_bare_update_check(std::string const& value); @@ -478,35 +495,6 @@ class state { void _set_temp_path(std::string const& value); void _set_use_embedded_perl_implicitly(std::string const& value); - template - struct setter { - static bool generic(state& obj, char const* value) { - try { - U val(0); - if (!string::to(value, val)) - return (false); - (obj.*ptr)(val); - } catch (std::exception const& e) { - engine_logger(logging::log_config_error, logging::basic) << e.what(); - return (false); - } - return (true); - } - }; - - template - struct setter { - static bool generic(state& obj, char const* value) { - try { - (obj.*ptr)(value); - } catch (std::exception const& e) { - engine_logger(logging::log_config_error, logging::basic) << e.what(); - return (false); - } - return (true); - } - }; - bool _accept_passive_host_checks; bool _accept_passive_service_checks; int _additional_freshness_latency; @@ -540,7 +528,7 @@ class state { set_contact _contacts; date_type _date_format; std::string _debug_file; - unsigned long long _debug_level; + uint64_t _debug_level; unsigned int _debug_verbosity; bool _enable_environment_macros; bool _enable_event_handlers; @@ -628,7 +616,7 @@ class state { std::string _service_perfdata_file_processing_command; unsigned int _service_perfdata_file_processing_interval; std::string _service_perfdata_file_template; - static std::unordered_map const _setters; + static setter_map _setters; float _sleep_time; bool _soft_state_dependencies; std::string _state_retention_file; @@ -662,10 +650,8 @@ class state { std::string _log_level_runtime; std::string _use_timezone; bool _use_true_regexp_matching; - }; -} // namespace configuration -} +} // namespace com::centreon::engine::configuration #endif // !CCE_CONFIGURATION_STATE_HH diff --git a/engine/inc/com/centreon/engine/log_v2.hh b/engine/inc/com/centreon/engine/log_v2.hh index 8460ff3375a..8423065635c 100644 --- a/engine/inc/com/centreon/engine/log_v2.hh +++ b/engine/inc/com/centreon/engine/log_v2.hh @@ -18,10 +18,13 @@ #ifndef CCE_LOG_V2_HH #define CCE_LOG_V2_HH -#include "com/centreon/engine/configuration/state.hh" #include "log_v2_base.hh" namespace com::centreon::engine { +namespace configuration { +class state; +} + class log_v2 : public log_v2_base { std::array, 13> _log; std::atomic_bool _running; @@ -117,6 +120,6 @@ class log_v2 : public log_v2_base { return _instance->get_logger(log_v2::log_runtime, "runtime"); } }; -} +} // namespace com::centreon::engine #endif /* !CCE_LOG_V2_HH */ diff --git a/engine/modules/external_commands/precomp_inc/precomp.hh b/engine/modules/external_commands/precomp_inc/precomp.hh index 39ad9d44723..3d9508bb7aa 100644 --- a/engine/modules/external_commands/precomp_inc/precomp.hh +++ b/engine/modules/external_commands/precomp_inc/precomp.hh @@ -44,4 +44,6 @@ namespace asio = boost::asio; #include #include +#include + #endif // CCE_EXTERNAL_COMMANDS_PRECOMP_HH diff --git a/engine/precomp_inc/precomp.hh b/engine/precomp_inc/precomp.hh index d8788fd3782..70fe1cd993f 100644 --- a/engine/precomp_inc/precomp.hh +++ b/engine/precomp_inc/precomp.hh @@ -52,6 +52,7 @@ #include #include #include +#include #include #include #include @@ -60,11 +61,13 @@ #include #include +#include #include #include -#include #include +#include + #include #include #include diff --git a/engine/src/checkable.cc b/engine/src/checkable.cc index f204b6261cd..3d502a31ad1 100644 --- a/engine/src/checkable.cc +++ b/engine/src/checkable.cc @@ -1,25 +1,26 @@ /** -* Copyright 2011-2019,2022 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2019,2022 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/checkable.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/log_v2.hh" +#include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/configuration/whitelist.hh" diff --git a/engine/src/configuration/CMakeLists.txt b/engine/src/configuration/CMakeLists.txt index 0ebfa72fa52..8121674ec0b 100644 --- a/engine/src/configuration/CMakeLists.txt +++ b/engine/src/configuration/CMakeLists.txt @@ -31,6 +31,7 @@ set(FILES "${SRC_DIR}/connector.cc" "${SRC_DIR}/contact.cc" "${SRC_DIR}/contactgroup.cc" + "${SRC_DIR}/extended_conf.cc" "${SRC_DIR}/group.cc" "${SRC_DIR}/host.cc" "${SRC_DIR}/hostdependency.cc" @@ -51,30 +52,4 @@ set(FILES "${SRC_DIR}/tag.cc" "${SRC_DIR}/timeperiod.cc" "${SRC_DIR}/whitelist.cc" - # Headers. - "${INC_DIR}/anomalydetection.hh" - "${INC_DIR}/command.hh" - "${INC_DIR}/connector.hh" - "${INC_DIR}/contactgroup.hh" - "${INC_DIR}/contact.hh" - "${INC_DIR}/file_info.hh" - "${INC_DIR}/group.hh" - "${INC_DIR}/host.hh" - "${INC_DIR}/hostdependency.hh" - "${INC_DIR}/hostescalation.hh" - "${INC_DIR}/hostextinfo.hh" - "${INC_DIR}/hostgroup.hh" - "${INC_DIR}/object.hh" - "${INC_DIR}/parser.hh" - "${INC_DIR}/point_2d.hh" - "${INC_DIR}/point_3d.hh" - "${INC_DIR}/servicedependency.hh" - "${INC_DIR}/serviceescalation.hh" - "${INC_DIR}/serviceextinfo.hh" - "${INC_DIR}/servicegroup.hh" - "${INC_DIR}/service.hh" - "${INC_DIR}/severity.hh" - "${INC_DIR}/state.hh" - "${INC_DIR}/tag.hh" - "${INC_DIR}/timeperiod.hh" PARENT_SCOPE) diff --git a/engine/src/configuration/applier/state.cc b/engine/src/configuration/applier/state.cc index 05bdc40e0b2..d65e5c5aa9c 100644 --- a/engine/src/configuration/applier/state.cc +++ b/engine/src/configuration/applier/state.cc @@ -1,21 +1,21 @@ /** -* Copyright 2011-2020 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2020 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/configuration/applier/state.hh" diff --git a/engine/src/configuration/extended_conf.cc b/engine/src/configuration/extended_conf.cc new file mode 100644 index 00000000000..24738e1c11e --- /dev/null +++ b/engine/src/configuration/extended_conf.cc @@ -0,0 +1,87 @@ +/** + * Copyright 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#include "com/centreon/engine/configuration/extended_conf.hh" +#include "com/centreon/engine/configuration/state.hh" +#include "com/centreon/exceptions/msg_fmt.hh" + +using namespace com::centreon::engine::configuration; + +std::list> extended_conf::_confs; + +/** + * @brief Construct a new extended state::extended state object + * + * @param path of the configuration file + * @throw exception if json malformed + */ +extended_conf::extended_conf(const std::string& path) : _path(path) { + if (::stat(_path.c_str(), &_file_info)) { + SPDLOG_LOGGER_ERROR(log_v2::config(), "can't access to {}", _path); + } + try { + _content = common::rapidjson_helper::read_from_file(_path); + SPDLOG_LOGGER_INFO(log_v2::config(), "extended conf file {} loaded", _path); + } catch (const std::exception& e) { + SPDLOG_LOGGER_ERROR( + log_v2::config(), + "extended_conf::extended_conf : fail to read json content from {}: {}", + _path, e.what()); + } +} + +/** + * @brief checks if the file has been updated. + * In that case, file is parsed. In case of failure, we continue to use old + * version + * + */ +void extended_conf::reload() { + struct stat file_info; + if (::stat(_path.c_str(), &file_info)) { + SPDLOG_LOGGER_ERROR(log_v2::config(), + "can't access to {} anymore => we keep old content", + _path); + return; + } + if (!memcmp(&file_info, &_file_info, sizeof(struct stat))) { + return; + } + try { + _content = common::rapidjson_helper::read_from_file(_path); + _file_info = file_info; + } catch (const std::exception& e) { + SPDLOG_LOGGER_ERROR(log_v2::config(), + "extended_conf::extended_conf : fail to read json " + "content from {} => we keep old content, cause: {}", + _path, e.what()); + } +} + +/** + * @brief reload all optional configuration files if needed + * Then these configuration content are applied to dest + * + * @param dest + */ +void extended_conf::update_state(state& dest) { + for (auto& conf_file : _confs) { + conf_file->reload(); + dest.apply_extended_conf(conf_file->_path, conf_file->_content); + } +} diff --git a/engine/src/configuration/state.cc b/engine/src/configuration/state.cc index 9f11cb28187..12fbdcdae75 100644 --- a/engine/src/configuration/state.cc +++ b/engine/src/configuration/state.cc @@ -1,21 +1,23 @@ /** -* Copyright 2011-2013,2015-2017, 2021-2022 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2013,2015-2017, 2021-2022 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ + +#include "com/centreon/common/rapidjson_helper.hh" #include "com/centreon/engine/configuration/state.hh" @@ -32,233 +34,280 @@ using namespace com::centreon::engine; using namespace com::centreon::engine::configuration; using namespace com::centreon::engine::logging; -#define SETTER(type, method) &state::setter::generic - -std::unordered_map const state::_setters{ - {"accept_passive_host_checks", SETTER(bool, accept_passive_host_checks)}, - {"accept_passive_service_checks", - SETTER(bool, accept_passive_service_checks)}, - {"additional_freshness_latency", SETTER(int, additional_freshness_latency)}, - {"admin_email", SETTER(std::string const&, admin_email)}, - {"admin_pager", SETTER(std::string const&, admin_pager)}, - {"aggregate_status_updates", - SETTER(std::string const&, _set_aggregate_status_updates)}, - {"allow_empty_hostgroup_assignment", - SETTER(bool, allow_empty_hostgroup_assignment)}, - {"auth_file", SETTER(std::string const&, _set_auth_file)}, - {"auto_reschedule_checks", SETTER(bool, auto_reschedule_checks)}, - {"auto_rescheduling_interval", - SETTER(unsigned int, auto_rescheduling_interval)}, - {"auto_rescheduling_window", - SETTER(unsigned int, auto_rescheduling_window)}, - {"bare_update_check", SETTER(std::string const&, _set_bare_update_check)}, - {"broker_module_directory", - SETTER(std::string const&, broker_module_directory)}, - {"broker_module", SETTER(std::string const&, _set_broker_module)}, - {"cached_host_check_horizon", - SETTER(unsigned long, cached_host_check_horizon)}, - {"cached_service_check_horizon", - SETTER(unsigned long, cached_service_check_horizon)}, - {"cfg_dir", SETTER(std::string const&, _set_cfg_dir)}, - {"cfg_file", SETTER(std::string const&, _set_cfg_file)}, - {"check_external_commands", SETTER(bool, check_external_commands)}, - {"check_for_orphaned_hosts", SETTER(bool, check_orphaned_hosts)}, - {"check_for_orphaned_services", SETTER(bool, check_orphaned_services)}, - {"check_for_updates", SETTER(std::string const&, _set_check_for_updates)}, - {"check_host_freshness", SETTER(bool, check_host_freshness)}, - {"check_result_reaper_frequency", - SETTER(unsigned int, check_reaper_interval)}, - {"check_service_freshness", SETTER(bool, check_service_freshness)}, - {"child_processes_fork_twice", - SETTER(std::string const&, _set_child_processes_fork_twice)}, - {"command_check_interval", - SETTER(std::string const&, _set_command_check_interval)}, - {"command_file", SETTER(std::string const&, command_file)}, - {"comment_file", SETTER(std::string const&, _set_comment_file)}, - {"daemon_dumps_core", SETTER(std::string const&, _set_daemon_dumps_core)}, - {"date_format", SETTER(std::string const&, _set_date_format)}, - {"debug_file", SETTER(std::string const&, debug_file)}, - {"debug_level", SETTER(unsigned long long, debug_level)}, - {"debug_verbosity", SETTER(unsigned int, debug_verbosity)}, - {"downtime_file", SETTER(std::string const&, _set_downtime_file)}, - {"enable_embedded_perl", - SETTER(std::string const&, _set_enable_embedded_perl)}, - {"enable_environment_macros", SETTER(bool, enable_environment_macros)}, - {"enable_event_handlers", SETTER(bool, enable_event_handlers)}, - {"enable_failure_prediction", - SETTER(std::string const&, _set_enable_failure_prediction)}, - {"enable_flap_detection", SETTER(bool, enable_flap_detection)}, - {"enable_macros_filter", SETTER(bool, enable_macros_filter)}, - {"enable_notifications", SETTER(bool, enable_notifications)}, - {"enable_predictive_host_dependency_checks", - SETTER(bool, enable_predictive_host_dependency_checks)}, - {"enable_predictive_service_dependency_checks", - SETTER(bool, enable_predictive_service_dependency_checks)}, - {"event_broker_options", - SETTER(std::string const&, _set_event_broker_options)}, - {"event_handler_timeout", SETTER(unsigned int, event_handler_timeout)}, - {"execute_host_checks", SETTER(bool, execute_host_checks)}, - {"execute_service_checks", SETTER(bool, execute_service_checks)}, - {"external_command_buffer_slots", - SETTER(int, external_command_buffer_slots)}, - {"free_child_process_memory", - SETTER(std::string const&, _set_free_child_process_memory)}, - {"global_host_event_handler", - SETTER(std::string const&, global_host_event_handler)}, - {"global_service_event_handler", - SETTER(std::string const&, global_service_event_handler)}, - {"high_host_flap_threshold", SETTER(float, high_host_flap_threshold)}, - {"high_service_flap_threshold", SETTER(float, high_service_flap_threshold)}, - {"host_check_timeout", SETTER(unsigned int, host_check_timeout)}, - {"host_freshness_check_interval", - SETTER(unsigned int, host_freshness_check_interval)}, - {"host_inter_check_delay_method", - SETTER(std::string const&, _set_host_inter_check_delay_method)}, - {"host_perfdata_command", - SETTER(std::string const&, host_perfdata_command)}, - {"host_perfdata_file", SETTER(std::string const&, host_perfdata_file)}, - {"host_perfdata_file_mode", - SETTER(std::string const&, _set_host_perfdata_file_mode)}, - {"host_perfdata_file_processing_command", - SETTER(std::string const&, host_perfdata_file_processing_command)}, - {"host_perfdata_file_processing_interval", - SETTER(unsigned int, host_perfdata_file_processing_interval)}, - {"host_perfdata_file_template", - SETTER(std::string const&, host_perfdata_file_template)}, - {"illegal_macro_output_chars", - SETTER(std::string const&, illegal_output_chars)}, - {"illegal_object_name_chars", - SETTER(std::string const&, illegal_object_chars)}, - {"interval_length", SETTER(unsigned int, interval_length)}, - {"lock_file", SETTER(std::string const&, _set_lock_file)}, - {"log_archive_path", SETTER(std::string const&, _set_log_archive_path)}, - {"log_event_handlers", SETTER(bool, log_event_handlers)}, - {"log_external_commands", SETTER(bool, log_external_commands)}, - {"log_file", SETTER(std::string const&, log_file)}, - {"log_host_retries", SETTER(bool, log_host_retries)}, - {"log_initial_states", SETTER(std::string const&, _set_log_initial_states)}, - {"log_notifications", SETTER(bool, log_notifications)}, - {"log_passive_checks", SETTER(bool, log_passive_checks)}, - {"log_pid", SETTER(bool, log_pid)}, - {"log_file_line", SETTER(bool, log_file_line)}, - {"log_rotation_method", - SETTER(std::string const&, _set_log_rotation_method)}, - {"log_service_retries", SETTER(bool, log_service_retries)}, - {"low_host_flap_threshold", SETTER(float, low_host_flap_threshold)}, - {"low_service_flap_threshold", SETTER(float, low_service_flap_threshold)}, - {"macros_filter", SETTER(std::string const&, macros_filter)}, - {"max_concurrent_checks", - SETTER(unsigned int, max_parallel_service_checks)}, - {"max_debug_file_size", SETTER(unsigned long, max_debug_file_size)}, - {"max_host_check_spread", SETTER(unsigned int, max_host_check_spread)}, - {"max_log_file_size", SETTER(unsigned long, max_log_file_size)}, - {"log_flush_period", SETTER(uint32_t, log_flush_period)}, - {"max_service_check_spread", - SETTER(unsigned int, max_service_check_spread)}, - {"nagios_group", SETTER(std::string const&, _set_nagios_group)}, - {"nagios_user", SETTER(std::string const&, _set_nagios_user)}, - {"notification_timeout", SETTER(unsigned int, notification_timeout)}, - {"object_cache_file", SETTER(std::string const&, _set_object_cache_file)}, - {"obsess_over_hosts", SETTER(bool, obsess_over_hosts)}, - {"obsess_over_services", SETTER(bool, obsess_over_services)}, - {"ochp_command", SETTER(std::string const&, ochp_command)}, - {"ochp_timeout", SETTER(unsigned int, ochp_timeout)}, - {"ocsp_command", SETTER(std::string const&, ocsp_command)}, - {"ocsp_timeout", SETTER(unsigned int, ocsp_timeout)}, - {"p1_file", SETTER(std::string const&, _set_p1_file)}, - {"perfdata_timeout", SETTER(int, perfdata_timeout)}, - {"poller_name", SETTER(std::string const&, poller_name)}, - {"poller_id", SETTER(uint32_t, poller_id)}, - {"rpc_port", SETTER(uint16_t, rpc_port)}, - {"rpc_listen_address", SETTER(const std::string&, rpc_listen_address)}, - {"precached_object_file", - SETTER(std::string const&, _set_precached_object_file)}, - {"process_performance_data", SETTER(bool, process_performance_data)}, - {"resource_file", SETTER(std::string const&, _set_resource_file)}, - {"retained_contact_host_attribute_mask", - SETTER(unsigned long, retained_contact_host_attribute_mask)}, - {"retained_contact_service_attribute_mask", - SETTER(unsigned long, retained_contact_service_attribute_mask)}, - {"retained_host_attribute_mask", - SETTER(unsigned long, retained_host_attribute_mask)}, - {"retained_process_host_attribute_mask", - SETTER(unsigned long, retained_process_host_attribute_mask)}, - {"retained_process_service_attribute_mask", - SETTER(std::string const&, _set_retained_process_service_attribute_mask)}, - {"retained_service_attribute_mask", - SETTER(std::string const&, _set_retained_service_attribute_mask)}, - {"retain_state_information", SETTER(bool, retain_state_information)}, - {"retention_scheduling_horizon", - SETTER(unsigned int, retention_scheduling_horizon)}, - {"retention_update_interval", - SETTER(unsigned int, retention_update_interval)}, - {"service_check_timeout", SETTER(unsigned int, service_check_timeout)}, - {"service_freshness_check_interval", - SETTER(unsigned int, service_freshness_check_interval)}, - {"service_inter_check_delay_method", - SETTER(std::string const&, _set_service_inter_check_delay_method)}, - {"service_interleave_factor", - SETTER(std::string const&, _set_service_interleave_factor_method)}, - {"service_perfdata_command", - SETTER(std::string const&, service_perfdata_command)}, - {"service_perfdata_file", - SETTER(std::string const&, service_perfdata_file)}, - {"service_perfdata_file_mode", - SETTER(std::string const&, _set_service_perfdata_file_mode)}, - {"service_perfdata_file_processing_command", - SETTER(std::string const&, service_perfdata_file_processing_command)}, - {"service_perfdata_file_processing_interval", - SETTER(unsigned int, service_perfdata_file_processing_interval)}, - {"service_perfdata_file_template", - SETTER(std::string const&, service_perfdata_file_template)}, - {"service_reaper_frequency", SETTER(unsigned int, check_reaper_interval)}, - {"sleep_time", SETTER(float, sleep_time)}, - {"soft_state_dependencies", SETTER(bool, soft_state_dependencies)}, - {"state_retention_file", SETTER(std::string const&, state_retention_file)}, - {"status_file", SETTER(std::string const&, status_file)}, - {"status_update_interval", SETTER(unsigned int, status_update_interval)}, - {"temp_file", SETTER(std::string const&, _set_temp_file)}, - {"temp_path", SETTER(std::string const&, _set_temp_path)}, - {"time_change_threshold", SETTER(unsigned int, time_change_threshold)}, - {"use_aggressive_host_checking", - SETTER(bool, use_aggressive_host_checking)}, - {"use_agressive_host_checking", SETTER(bool, use_aggressive_host_checking)}, - {"use_embedded_perl_implicitly", - SETTER(std::string const&, _set_use_embedded_perl_implicitly)}, - {"use_large_installation_tweaks", - SETTER(bool, use_large_installation_tweaks)}, - {"instance_heartbeat_interval", - SETTER(uint32_t, instance_heartbeat_interval)}, - {"use_regexp_matching", SETTER(bool, use_regexp_matches)}, - {"use_retained_program_state", SETTER(bool, use_retained_program_state)}, - {"use_retained_scheduling_info", - SETTER(bool, use_retained_scheduling_info)}, - {"use_setpgid", SETTER(bool, use_setpgid)}, - {"use_syslog", SETTER(bool, use_syslog)}, - {"log_v2_enabled", SETTER(bool, log_v2_enabled)}, - {"log_legacy_enabled", SETTER(bool, log_legacy_enabled)}, - {"log_v2_logger", SETTER(std::string const&, log_v2_logger)}, - {"log_level_functions", SETTER(std::string const&, log_level_functions)}, - {"log_level_config", SETTER(std::string const&, log_level_config)}, - {"log_level_events", SETTER(std::string const&, log_level_events)}, - {"log_level_checks", SETTER(std::string const&, log_level_checks)}, - {"log_level_notifications", - SETTER(std::string const&, log_level_notifications)}, - {"log_level_eventbroker", - SETTER(std::string const&, log_level_eventbroker)}, - {"log_level_external_command", - SETTER(std::string const&, log_level_external_command)}, - {"log_level_commands", SETTER(std::string const&, log_level_commands)}, - {"log_level_downtimes", SETTER(std::string const&, log_level_downtimes)}, - {"log_level_comments", SETTER(std::string const&, log_level_comments)}, - {"log_level_macros", SETTER(std::string const&, log_level_macros)}, - {"log_level_process", SETTER(std::string const&, log_level_process)}, - {"log_level_runtime", SETTER(std::string const&, log_level_runtime)}, - {"use_timezone", SETTER(std::string const&, use_timezone)}, - {"use_true_regexp_matching", SETTER(bool, use_true_regexp_matching)}, - {"xcddefault_comment_file", SETTER(std::string const&, _set_comment_file)}, - {"xdddefault_downtime_file", - SETTER(std::string const&, _set_downtime_file)}}; +namespace com::centreon::engine::configuration::detail { +template +struct setter : public setter_base { + setter(const std::string_view& field_name) : setter_base(field_name) {} + bool apply_from_cfg(state& obj, char const* value) override { + try { + U val(0); + if (!string::to(value, val)) + return false; + (obj.*ptr)(val); + } catch (std::exception const& e) { + SPDLOG_LOGGER_ERROR(log_v2::config(), + "fail to update {} with value {}: {}", + setter_base::_field_name, value, e.what()); + return false; + } + return true; + } + + bool apply_from_json(state& obj, const rapidjson::Document& doc) override { + try { + U val = + common::rapidjson_helper(doc).get(setter_base::_field_name.data()); + (obj.*ptr)(val); + } catch (std::exception const& e) { + SPDLOG_LOGGER_ERROR(log_v2::config(), "fail to update {} : {}", + setter_base::_field_name, e.what()); + return false; + } + return true; + } +}; + +template +struct setter : public setter_base { + setter(const std::string_view& field_name) : setter_base(field_name) {} + bool apply_from_cfg(state& obj, char const* value) override { + try { + (obj.*ptr)(value); + } catch (std::exception const& e) { + SPDLOG_LOGGER_ERROR(log_v2::config(), + "fail to update {} with value {}: {}", _field_name, + value, e.what()); + return false; + } + return true; + } + bool apply_from_json(state& obj, const rapidjson::Document& doc) override { + try { + std::string val = + common::rapidjson_helper(doc).get_string(_field_name.data()); + (obj.*ptr)(val); + } catch (std::exception const& e) { + SPDLOG_LOGGER_ERROR(log_v2::config(), "fail to update {} : {}", + _field_name, e.what()); + return false; + } + return true; + } +}; +}; // namespace com::centreon::engine::configuration::detail + +#define SETTER(type, method, field) \ + _setters.emplace(std::make_pair( \ + field, std::make_unique>(field))) + +state::setter_map state::_setters; + +void state::_init_setter() { + SETTER(bool, accept_passive_host_checks, "accept_passive_host_checks"); + SETTER(bool, accept_passive_service_checks, "accept_passive_service_checks"); + SETTER(int, additional_freshness_latency, "additional_freshness_latency"); + SETTER(std::string const&, admin_email, "admin_email"); + SETTER(std::string const&, admin_pager, "admin_pager"); + SETTER(std::string const&, _set_aggregate_status_updates, + "aggregate_status_updates"); + SETTER(bool, allow_empty_hostgroup_assignment, + "allow_empty_hostgroup_assignment"); + SETTER(std::string const&, _set_auth_file, "auth_file"); + SETTER(bool, auto_reschedule_checks, "auto_reschedule_checks"); + SETTER(unsigned int, auto_rescheduling_interval, + "auto_rescheduling_interval"); + SETTER(unsigned int, auto_rescheduling_window, "auto_rescheduling_window"); + SETTER(std::string const&, _set_bare_update_check, "bare_update_check"); + SETTER(std::string const&, broker_module_directory, + "broker_module_directory"); + SETTER(std::string const&, _set_broker_module, "broker_module"); + SETTER(unsigned long, cached_host_check_horizon, "cached_host_check_horizon"); + SETTER(unsigned long, cached_service_check_horizon, + "cached_service_check_horizon"); + SETTER(std::string const&, _set_cfg_dir, "cfg_dir"); + SETTER(std::string const&, _set_cfg_file, "cfg_file"); + SETTER(bool, check_external_commands, "check_external_commands"); + SETTER(bool, check_orphaned_hosts, "check_for_orphaned_hosts"); + SETTER(bool, check_orphaned_services, "check_for_orphaned_services"); + SETTER(std::string const&, _set_check_for_updates, "check_for_updates"); + SETTER(bool, check_host_freshness, "check_host_freshness"); + SETTER(unsigned int, check_reaper_interval, "check_result_reaper_frequency"); + SETTER(bool, check_service_freshness, "check_service_freshness"); + SETTER(std::string const&, _set_child_processes_fork_twice, + "child_processes_fork_twice"); + SETTER(std::string const&, _set_command_check_interval, + "command_check_interval"); + SETTER(std::string const&, command_file, "command_file"); + SETTER(std::string const&, _set_comment_file, "comment_file"); + SETTER(std::string const&, _set_daemon_dumps_core, "daemon_dumps_core"); + SETTER(std::string const&, _set_date_format, "date_format"); + SETTER(std::string const&, debug_file, "debug_file"); + SETTER(uint64_t, debug_level, "debug_level"); + SETTER(unsigned int, debug_verbosity, "debug_verbosity"); + SETTER(std::string const&, _set_downtime_file, "downtime_file"); + SETTER(std::string const&, _set_enable_embedded_perl, "enable_embedded_perl"); + SETTER(bool, enable_environment_macros, "enable_environment_macros"); + SETTER(bool, enable_event_handlers, "enable_event_handlers"); + SETTER(std::string const&, _set_enable_failure_prediction, + "enable_failure_prediction"); + SETTER(bool, enable_flap_detection, "enable_flap_detection"); + SETTER(bool, enable_macros_filter, "enable_macros_filter"); + SETTER(bool, enable_notifications, "enable_notifications"); + SETTER(bool, enable_predictive_host_dependency_checks, + "enable_predictive_host_dependency_checks"); + SETTER(bool, enable_predictive_service_dependency_checks, + "enable_predictive_service_dependency_checks"); + SETTER(std::string const&, _set_event_broker_options, "event_broker_options"); + SETTER(unsigned int, event_handler_timeout, "event_handler_timeout"); + SETTER(bool, execute_host_checks, "execute_host_checks"); + SETTER(bool, execute_service_checks, "execute_service_checks"); + SETTER(int, external_command_buffer_slots, "external_command_buffer_slots"); + SETTER(std::string const&, _set_free_child_process_memory, + "free_child_process_memory"); + SETTER(std::string const&, global_host_event_handler, + "global_host_event_handler"); + SETTER(std::string const&, global_service_event_handler, + "global_service_event_handler"); + SETTER(float, high_host_flap_threshold, "high_host_flap_threshold"); + SETTER(float, high_service_flap_threshold, "high_service_flap_threshold"); + SETTER(unsigned int, host_check_timeout, "host_check_timeout"); + SETTER(unsigned int, host_freshness_check_interval, + "host_freshness_check_interval"); + SETTER(std::string const&, _set_host_inter_check_delay_method, + "host_inter_check_delay_method"); + SETTER(std::string const&, host_perfdata_command, "host_perfdata_command"); + SETTER(std::string const&, host_perfdata_file, "host_perfdata_file"); + SETTER(std::string const&, _set_host_perfdata_file_mode, + "host_perfdata_file_mode"); + SETTER(std::string const&, host_perfdata_file_processing_command, + "host_perfdata_file_processing_command"); + SETTER(unsigned int, host_perfdata_file_processing_interval, + "host_perfdata_file_processing_interval"); + SETTER(std::string const&, host_perfdata_file_template, + "host_perfdata_file_template"); + SETTER(std::string const&, illegal_output_chars, + "illegal_macro_output_chars"); + SETTER(std::string const&, illegal_object_chars, "illegal_object_name_chars"); + SETTER(unsigned int, interval_length, "interval_length"); + SETTER(std::string const&, _set_lock_file, "lock_file"); + SETTER(std::string const&, _set_log_archive_path, "log_archive_path"); + SETTER(bool, log_event_handlers, "log_event_handlers"); + SETTER(bool, log_external_commands, "log_external_commands"); + SETTER(std::string const&, log_file, "log_file"); + SETTER(bool, log_host_retries, "log_host_retries"); + SETTER(std::string const&, _set_log_initial_states, "log_initial_states"); + SETTER(bool, log_notifications, "log_notifications"); + SETTER(bool, log_passive_checks, "log_passive_checks"); + SETTER(bool, log_pid, "log_pid"); + SETTER(bool, log_file_line, "log_file_line"); + SETTER(std::string const&, _set_log_rotation_method, "log_rotation_method"); + SETTER(bool, log_service_retries, "log_service_retries"); + SETTER(float, low_host_flap_threshold, "low_host_flap_threshold"); + SETTER(float, low_service_flap_threshold, "low_service_flap_threshold"); + SETTER(std::string const&, macros_filter, "macros_filter"); + SETTER(unsigned int, max_parallel_service_checks, "max_concurrent_checks"); + SETTER(unsigned long, max_debug_file_size, "max_debug_file_size"); + SETTER(unsigned int, max_host_check_spread, "max_host_check_spread"); + SETTER(unsigned long, max_log_file_size, "max_log_file_size"); + SETTER(uint32_t, log_flush_period, "log_flush_period"); + SETTER(unsigned int, max_service_check_spread, "max_service_check_spread"); + SETTER(std::string const&, _set_nagios_group, "nagios_group"); + SETTER(std::string const&, _set_nagios_user, "nagios_user"); + SETTER(unsigned int, notification_timeout, "notification_timeout"); + SETTER(std::string const&, _set_object_cache_file, "object_cache_file"); + SETTER(bool, obsess_over_hosts, "obsess_over_hosts"); + SETTER(bool, obsess_over_services, "obsess_over_services"); + SETTER(std::string const&, ochp_command, "ochp_command"); + SETTER(unsigned int, ochp_timeout, "ochp_timeout"); + SETTER(std::string const&, ocsp_command, "ocsp_command"); + SETTER(unsigned int, ocsp_timeout, "ocsp_timeout"); + SETTER(std::string const&, _set_p1_file, "p1_file"); + SETTER(int, perfdata_timeout, "perfdata_timeout"); + SETTER(std::string const&, poller_name, "poller_name"); + SETTER(uint32_t, poller_id, "poller_id"); + SETTER(uint16_t, rpc_port, "rpc_port"); + SETTER(const std::string&, rpc_listen_address, "rpc_listen_address"); + SETTER(std::string const&, _set_precached_object_file, + "precached_object_file"); + SETTER(bool, process_performance_data, "process_performance_data"); + SETTER(std::string const&, _set_resource_file, "resource_file"); + SETTER(unsigned long, retained_contact_host_attribute_mask, + "retained_contact_host_attribute_mask"); + SETTER(unsigned long, retained_contact_service_attribute_mask, + "retained_contact_service_attribute_mask"); + SETTER(unsigned long, retained_host_attribute_mask, + "retained_host_attribute_mask"); + SETTER(unsigned long, retained_process_host_attribute_mask, + "retained_process_host_attribute_mask"); + SETTER(std::string const&, _set_retained_process_service_attribute_mask, + "retained_process_service_attribute_mask"); + SETTER(std::string const&, _set_retained_service_attribute_mask, + "retained_service_attribute_mask"); + SETTER(bool, retain_state_information, "retain_state_information"); + SETTER(unsigned int, retention_scheduling_horizon, + "retention_scheduling_horizon"); + SETTER(unsigned int, retention_update_interval, "retention_update_interval"); + SETTER(unsigned int, service_check_timeout, "service_check_timeout"); + SETTER(unsigned int, service_freshness_check_interval, + "service_freshness_check_interval"); + SETTER(std::string const&, _set_service_inter_check_delay_method, + "service_inter_check_delay_method"); + SETTER(std::string const&, _set_service_interleave_factor_method, + "service_interleave_factor"); + SETTER(std::string const&, service_perfdata_command, + "service_perfdata_command"); + SETTER(std::string const&, service_perfdata_file, "service_perfdata_file"); + SETTER(std::string const&, _set_service_perfdata_file_mode, + "service_perfdata_file_mode"); + SETTER(std::string const&, service_perfdata_file_processing_command, + "service_perfdata_file_processing_command"); + SETTER(unsigned int, service_perfdata_file_processing_interval, + "service_perfdata_file_processing_interval"); + SETTER(std::string const&, service_perfdata_file_template, + "service_perfdata_file_template"); + SETTER(unsigned int, check_reaper_interval, "service_reaper_frequency"); + SETTER(float, sleep_time, "sleep_time"); + SETTER(bool, soft_state_dependencies, "soft_state_dependencies"); + SETTER(std::string const&, state_retention_file, "state_retention_file"); + SETTER(std::string const&, status_file, "status_file"); + SETTER(unsigned int, status_update_interval, "status_update_interval"); + SETTER(std::string const&, _set_temp_file, "temp_file"); + SETTER(std::string const&, _set_temp_path, "temp_path"); + SETTER(unsigned int, time_change_threshold, "time_change_threshold"); + SETTER(bool, use_aggressive_host_checking, "use_aggressive_host_checking"); + SETTER(bool, use_aggressive_host_checking, "use_agressive_host_checking"); + SETTER(std::string const&, _set_use_embedded_perl_implicitly, + "use_embedded_perl_implicitly"); + SETTER(bool, use_large_installation_tweaks, "use_large_installation_tweaks"); + SETTER(uint32_t, instance_heartbeat_interval, "instance_heartbeat_interval"); + SETTER(bool, use_regexp_matches, "use_regexp_matching"); + SETTER(bool, use_retained_program_state, "use_retained_program_state"); + SETTER(bool, use_retained_scheduling_info, "use_retained_scheduling_info"); + SETTER(bool, use_setpgid, "use_setpgid"); + SETTER(bool, use_syslog, "use_syslog"); + SETTER(bool, log_v2_enabled, "log_v2_enabled"); + SETTER(bool, log_legacy_enabled, "log_legacy_enabled"); + SETTER(std::string const&, log_v2_logger, "log_v2_logger"); + SETTER(std::string const&, log_level_functions, "log_level_functions"); + SETTER(std::string const&, log_level_config, "log_level_config"); + SETTER(std::string const&, log_level_events, "log_level_events"); + SETTER(std::string const&, log_level_checks, "log_level_checks"); + SETTER(std::string const&, log_level_notifications, + "log_level_notifications"); + SETTER(std::string const&, log_level_eventbroker, "log_level_eventbroker"); + SETTER(std::string const&, log_level_external_command, + "log_level_external_command"); + SETTER(std::string const&, log_level_commands, "log_level_commands"); + SETTER(std::string const&, log_level_downtimes, "log_level_downtimes"); + SETTER(std::string const&, log_level_comments, "log_level_comments"); + SETTER(std::string const&, log_level_macros, "log_level_macros"); + SETTER(std::string const&, log_level_process, "log_level_process"); + SETTER(std::string const&, log_level_runtime, "log_level_runtime"); + SETTER(std::string const&, use_timezone, "use_timezone"); + SETTER(bool, use_true_regexp_matching, "use_true_regexp_matching"); + SETTER(std::string const&, _set_comment_file, "xcddefault_comment_file"); + SETTER(std::string const&, _set_downtime_file, "xdddefault_downtime_file"); +} // Default values. static bool const default_accept_passive_host_checks(true); @@ -283,7 +332,7 @@ static int const default_command_check_interval(-1); static std::string const default_command_file(DEFAULT_COMMAND_FILE); static state::date_type const default_date_format(state::us); static std::string const default_debug_file(DEFAULT_DEBUG_FILE); -static unsigned long long const default_debug_level(0); +static uint64_t const default_debug_level(0); static unsigned int const default_debug_verbosity(1); static bool const default_enable_environment_macros(false); static bool const default_enable_event_handlers(true); @@ -394,7 +443,6 @@ static std::string const default_use_timezone(""); static bool const default_use_true_regexp_matching(false); static const std::string default_rpc_listen_address("localhost"); - /** * Default constructor. */ @@ -533,7 +581,10 @@ state::state() _log_level_process(default_log_level_process), _log_level_runtime(default_log_level_runtime), _use_timezone(default_use_timezone), - _use_true_regexp_matching(default_use_true_regexp_matching) {} + _use_true_regexp_matching(default_use_true_regexp_matching) { + static absl::once_flag _init_call_once; + absl::call_once(_init_call_once, _init_setter); +} /** * Copy constructor. @@ -1645,7 +1696,7 @@ void state::debug_file(std::string const& value) { * * @return The debug_level value. */ -unsigned long long state::debug_level() const noexcept { +uint64_t state::debug_level() const noexcept { return _debug_level; } @@ -1654,9 +1705,9 @@ unsigned long long state::debug_level() const noexcept { * * @param[in] value The new debug_level value. */ -void state::debug_level(unsigned long long value) { +void state::debug_level(uint64_t value) { if (value == std::numeric_limits::max()) - _debug_level = static_cast(all); + _debug_level = static_cast(all); else _debug_level = value; } @@ -3556,10 +3607,9 @@ void state::status_update_interval(unsigned int value) { */ bool state::set(char const* key, char const* value) { try { - std::unordered_map::const_iterator it{ - _setters.find(key)}; + auto it = _setters.find(std::string_view(key)); if (it != _setters.end()) - return (it->second)(*this, value); + return (it->second)->apply_from_cfg(*this, value); } catch (std::exception const& e) { engine_logger(log_config_error, basic) << e.what(); log_v2::config()->error(e.what()); @@ -4320,7 +4370,8 @@ void state::_set_command_check_interval(std::string const& value) { _command_check_interval_is_seconds = true; val.erase(val.begin() + pos); } - setter::generic(*this, val.c_str()); + detail::setter("").apply_from_cfg( + *this, val.c_str()); } /** @@ -4412,8 +4463,8 @@ void state::_set_enable_failure_prediction(std::string const& value) { */ void state::_set_event_broker_options(std::string const& value) { if (value != "-1") - setter::generic(*this, - value.c_str()); + detail::setter("") + .apply_from_cfg(*this, value.c_str()); else { _event_broker_options = BROKER_EVERYTHING; } @@ -4763,3 +4814,28 @@ bool state::enable_macros_filter() const noexcept { void state::enable_macros_filter(bool value) { _enable_macros_filter = value; } + +/** + * @brief modify state according json passed in parameter + * + * @param file_path + * @param json_doc + */ +void state::apply_extended_conf(const std::string& file_path, + const rapidjson::Document& json_doc) { + SPDLOG_LOGGER_INFO(log_v2::config(), "apply conf from file {}", file_path); + for (rapidjson::Value::ConstMemberIterator member_iter = + json_doc.MemberBegin(); + member_iter != json_doc.MemberEnd(); ++member_iter) { + const std::string_view field_name = member_iter->name.GetString(); + auto setter = _setters.find(field_name); + if (setter == _setters.end()) { + SPDLOG_LOGGER_ERROR(log_v2::config(), "unknown field: {} in file {}", + field_name, file_path); + } else if (!setter->second->apply_from_json(*this, json_doc)) { + SPDLOG_LOGGER_ERROR(log_v2::config(), + "fail to update field: {} from file {}", field_name, + file_path); + } + } +} diff --git a/engine/src/events/loop.cc b/engine/src/events/loop.cc index cc4dba748b9..cc12e203054 100644 --- a/engine/src/events/loop.cc +++ b/engine/src/events/loop.cc @@ -1,24 +1,24 @@ /** -* Copyright 1999-2009 Ethan Galstad -* Copyright 2009-2010 Nagios Core Development Team and Community Contributors -* Copyright 2011-2013 Merethis -* Copyright 2013-2022 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 1999-2009 Ethan Galstad + * Copyright 2009-2010 Nagios Core Development Team and Community Contributors + * Copyright 2011-2013 Merethis + * Copyright 2013-2022 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/events/loop.hh" #include @@ -27,6 +27,7 @@ #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/command_manager.hh" #include "com/centreon/engine/configuration/applier/state.hh" +#include "com/centreon/engine/configuration/extended_conf.hh" #include "com/centreon/engine/configuration/parser.hh" #include "com/centreon/engine/globals.hh" #include "com/centreon/engine/log_v2.hh" @@ -101,6 +102,7 @@ static void apply_conf(std::atomic* reloading) { std::string path(::config->cfg_main()); p.parse(path, config); } + configuration::extended_conf::update_state(config); configuration::applier::state::instance().apply(config); engine_logger(log_info_message, basic) << "Configuration reloaded, main loop continuing."; diff --git a/engine/src/main.cc b/engine/src/main.cc index e7b61776b7b..8953c0ccc67 100644 --- a/engine/src/main.cc +++ b/engine/src/main.cc @@ -1,23 +1,23 @@ /** -* Copyright 1999-2009 Ethan Galstad -* Copyright 2009-2010 Nagios Core Development Team and Community Contributors -* Copyright 2011-2021 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 1999-2009 Ethan Galstad + * Copyright 2009-2010 Nagios Core Development Team and Community Contributors + * Copyright 2011-2021 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #ifdef HAVE_GETOPT_H #include @@ -37,12 +37,15 @@ namespace asio = boost::asio; #include #include +#include + #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/broker/loader.hh" #include "com/centreon/engine/checks/checker.hh" #include "com/centreon/engine/config.hh" #include "com/centreon/engine/configuration/applier/logging.hh" #include "com/centreon/engine/configuration/applier/state.hh" +#include "com/centreon/engine/configuration/extended_conf.hh" #include "com/centreon/engine/configuration/parser.hh" #include "com/centreon/engine/configuration/state.hh" #include "com/centreon/engine/diagnostic.hh" @@ -97,14 +100,15 @@ int main(int argc, char* argv[]) { #ifdef HAVE_GETOPT_H int option_index = 0; static struct option const long_options[] = { - {"diagnose", no_argument, NULL, 'D'}, - {"dont-verify-paths", no_argument, NULL, 'x'}, - {"help", no_argument, NULL, 'h'}, - {"license", no_argument, NULL, 'V'}, - {"test-scheduling", no_argument, NULL, 's'}, - {"verify-config", no_argument, NULL, 'v'}, - {"version", no_argument, NULL, 'V'}, - {NULL, no_argument, NULL, '\0'}}; + {"diagnose", no_argument, nullptr, 'D'}, + {"dont-verify-paths", no_argument, nullptr, 'x'}, + {"help", no_argument, nullptr, 'h'}, + {"license", no_argument, nullptr, 'V'}, + {"test-scheduling", no_argument, nullptr, 's'}, + {"verify-config", no_argument, nullptr, 'v'}, + {"version", no_argument, nullptr, 'V'}, + {"config-file", optional_argument, nullptr, 'c'}, + {NULL, no_argument, nullptr, '\0'}}; #endif // HAVE_GETOPT_H // Load singletons and global variable. @@ -123,11 +127,12 @@ int main(int argc, char* argv[]) { bool display_license(false); bool error(false); bool diagnose(false); + std::set extended_conf_file; // Process all command line arguments. int c; #ifdef HAVE_GETOPT_H - while ((c = getopt_long(argc, argv, "+hVvsxD", long_options, + while ((c = getopt_long(argc, argv, "+hVvsxDc", long_options, &option_index)) != -1) { #else while ((c = getopt(argc, argv, "+hVvsxD")) != -1) { @@ -154,6 +159,10 @@ int main(int argc, char* argv[]) { case 'D': // Diagnostic. diagnose = true; break; + case 'c': + if (optarg) + extended_conf_file.insert(optarg); + break; default: error = true; } @@ -351,6 +360,10 @@ int main(int argc, char* argv[]) { p.parse(config_file, config); } + configuration::extended_conf::load_all(extended_conf_file.begin(), + extended_conf_file.end()); + + configuration::extended_conf::update_state(config); uint16_t port = config.rpc_port(); if (!port) { diff --git a/engine/tests/CMakeLists.txt b/engine/tests/CMakeLists.txt index 135efd33331..7d11b056cd8 100755 --- a/engine/tests/CMakeLists.txt +++ b/engine/tests/CMakeLists.txt @@ -35,6 +35,7 @@ if(WITH_TESTING) -L${PROTOBUF_LIB_DIR} cerpc centreon_common + spdlog::spdlog gRPC::gpr gRPC::grpc gRPC::grpc++ gRPC::grpc++_alts crypto ssl z diff --git a/engine/tests/configuration/applier/applier-state.cc b/engine/tests/configuration/applier/applier-state.cc index fa8163002c5..cd6feb66e0a 100644 --- a/engine/tests/configuration/applier/applier-state.cc +++ b/engine/tests/configuration/applier/applier-state.cc @@ -20,6 +20,7 @@ #include #include #include "com/centreon/engine/configuration/applier/state.hh" +#include "com/centreon/engine/configuration/extended_conf.hh" #include "com/centreon/engine/configuration/parser.hh" #include "com/centreon/engine/globals.hh" @@ -1017,3 +1018,46 @@ TEST_F(ApplierState, StateLegacyParsingHostdependencyWithoutHost) { CreateBadConf(ConfigurationObject::HOSTDEPENDENCY); ASSERT_THROW(p.parse("/tmp/centengine.cfg", config), std::exception); } + +TEST_F(ApplierState, extended_override_conf) { + configuration::state config; + configuration::parser p; + CreateConf(); + p.parse("/tmp/centengine.cfg", config); + + const char* file_paths[] = {"/tmp/extended_conf.json"}; + CreateFile(file_paths[0], + R"({"instance_heartbeat_interval":120, + "log_level_functions":"debug", + "log_level_checks":"trace", + "enable_flap_detection": true, + "rpc_port": 12345 +})"); + + configuration::extended_conf::load_all(file_paths, file_paths + 1); + configuration::extended_conf::update_state(config); + ASSERT_EQ(config.log_level_functions(), std::string("debug")); + ASSERT_EQ(config.log_level_checks(), std::string("trace")); + ASSERT_EQ(config.instance_heartbeat_interval(), 120); + ASSERT_EQ(config.enable_flap_detection(), true); + ASSERT_EQ(config.rpc_port(), 12345); +} + +TEST_F(ApplierState, extended_override_conf_overflow) { + configuration::state config; + configuration::parser p; + CreateConf(); + p.parse("/tmp/centengine.cfg", config); + + const char* file_paths[] = {"/tmp/extended_conf.json"}; + CreateFile(file_paths[0], + R"({ + "enable_flap_detection": "etetge", + "rpc_port": 12345456 +})"); + + configuration::extended_conf::load_all(file_paths, file_paths + 1); + configuration::extended_conf::update_state(config); + ASSERT_EQ(config.enable_flap_detection(), false); + ASSERT_EQ(config.rpc_port(), 0); +} diff --git a/tests/engine/extended_conf.robot b/tests/engine/extended_conf.robot new file mode 100644 index 00000000000..16673eff249 --- /dev/null +++ b/tests/engine/extended_conf.robot @@ -0,0 +1,59 @@ +*** Settings *** +Documentation Centreon Engine forced checks tests + +Resource ../resources/import.resource + +Suite Setup Ctn Clean Before Suite +Suite Teardown Ctn Clean After Suite +Test Setup Ctn Stop Processes +Test Teardown Run Keywords Ctn Stop engine AND Ctn Save Logs If Failed + + +*** Test Cases *** +EXT_CONF1 + [Documentation] Engine configuration is overided by json conf + [Tags] engine mon-34326 + Ctn Config Engine ${1} + Ctn Config Broker module ${1} + Create File /tmp/centengine_extend.json {"log_level_checks": "trace", "log_level_comments": "debug"} + ${start} Get Current Date + Start Process + ... /usr/sbin/centengine + ... --config-file\=/tmp/centengine_extend.json + ... ${EtcRoot}/centreon-engine/config0/centengine.cfg + ... alias=e0 + Ctn Wait For Engine To Be Ready ${start} ${1} + ${level} Ctn Get Engine Log Level 50001 checks + Should Be Equal ${level} trace log_level_checks must be the extended conf value + ${level} Ctn Get Engine Log Level 50001 comments + Should Be Equal ${level} debug log_level_comments must be the extended conf value + +EXT_CONF2 + [Documentation] Engine configuration is overided by json conf after reload + [Tags] engine mon-34326 + Ctn Config Engine ${1} + Ctn Config Broker module ${1} + Create File /tmp/centengine_extend.json {} + ${start} Get Current Date + Start Process + ... /usr/sbin/centengine + ... --config-file\=/tmp/centengine_extend.json + ... ${EtcRoot}/centreon-engine/config0/centengine.cfg + ... alias=e0 + Ctn Wait For Engine To Be Ready ${start} ${1} + Create File /tmp/centengine_extend.json {"log_level_checks": "trace", "log_level_comments": "debug"} + + ${start} Get Current Date + Send Signal To Process SIGHUP e0 + ${content} Create List Need reload. + ${result} Ctn Find In Log With Timeout + ... ${ENGINE_LOG}/config0/centengine.log + ... ${start} ${content} 60 + Should Be True + ... ${result} + ... A message telling Need reload. should be available in config0/centengine.log. + + ${level} Ctn Get Engine Log Level 50001 checks + Should Be Equal ${level} trace log_level_checks must be the extended conf value + ${level} Ctn Get Engine Log Level 50001 comments + Should Be Equal ${level} debug log_level_comments must be the extended conf value diff --git a/tests/resources/Engine.py b/tests/resources/Engine.py index 6706c12d1ed..0a5c70a31bb 100755 --- a/tests/resources/Engine.py +++ b/tests/resources/Engine.py @@ -3289,3 +3289,30 @@ def ctn_get_service_command(host_id: int, service_id: int): logger.console( f"Unable to find the command id of service ({host_id};{service_id})") return None + + +def ctn_get_engine_log_level(port, log, timeout=TIMEOUT): + """ + Get the log level of a given logger. The timeout is due to the way we ask + for this information ; we use gRPC and the server may not be correctly + started. + + Args: + port: The gRPC port to use. + log: The logger name. + + Returns: + A string with the log level. + """ + limit = time.time() + timeout + while time.time() < limit: + logger.console("Try to call GetLogInfo") + time.sleep(1) + with grpc.insecure_channel("127.0.0.1:{}".format(port)) as channel: + stub = engine_pb2_grpc.EngineStub(channel) + try: + logs = stub.GetLogInfo(empty_pb2.Empty()) + return logs.loggers[0].level[log] + + except: + logger.console("gRPC server not ready") diff --git a/vcpkg.json b/vcpkg.json index 0d551ea03dc..5a23bcb978f 100644 --- a/vcpkg.json +++ b/vcpkg.json @@ -3,7 +3,7 @@ { "name": "abseil", "features": [ - "cxx17" + "cxx17" ] }, "libmariadb", @@ -24,11 +24,12 @@ { "name": "opentelemetry-cpp", "features": [ - "otlp-grpc", - "otlp-http" + "otlp-grpc", + "otlp-http" ] }, "nlohmann-json", + "rapidjson", "gtest" ] -} +} \ No newline at end of file From 2dd942059542693c1b7a1f53163824b33a657d8a Mon Sep 17 00:00:00 2001 From: jean-christophe81 <98889244+jean-christophe81@users.noreply.github.com> Date: Tue, 14 May 2024 10:50:50 +0200 Subject: [PATCH 03/60] exception is cached in _check_queues (#1330) --- broker/unified_sql/src/stream_storage.cc | 348 +++++++++++---------- tests/broker-database/networkFailure.robot | 37 +++ 2 files changed, 216 insertions(+), 169 deletions(-) diff --git a/broker/unified_sql/src/stream_storage.cc b/broker/unified_sql/src/stream_storage.cc index 219c7680529..7a56a921cdd 100644 --- a/broker/unified_sql/src/stream_storage.cc +++ b/broker/unified_sql/src/stream_storage.cc @@ -801,198 +801,208 @@ void stream::_check_queues(boost::system::error_code ec) { bool resources_done = false; - if (_bulk_prepared_statement) { - _finish_action(-1, actions::host_parents | actions::comments | - actions::downtimes | actions::host_dependencies | - actions::service_dependencies); - if (_store_in_hosts_services) { - if (_hscr_bind) { - SPDLOG_LOGGER_TRACE( - log_v2::sql(), - "Check if some statements are ready, hscr_bind connections " - "count " - "= {}", - _hscr_bind->connections_count()); - for (uint32_t conn = 0; conn < _hscr_bind->connections_count(); - conn++) { - if (_hscr_bind->ready(conn)) { - SPDLOG_LOGGER_DEBUG( - log_v2::sql(), - "Sending {} hosts rows of host status on connection {}", - _hscr_bind->size(conn), conn); - // Setting the good bind to the stmt - _hscr_bind->apply_to_stmt(conn); - // Executing the stmt - _mysql.run_statement(*_hscr_update, - database::mysql_error::store_host_status, - conn); - _add_action(conn, actions::hosts); + try { + if (_bulk_prepared_statement) { + _finish_action(-1, actions::host_parents | actions::comments | + actions::downtimes | actions::host_dependencies | + actions::service_dependencies); + if (_store_in_hosts_services) { + if (_hscr_bind) { + SPDLOG_LOGGER_TRACE( + log_v2::sql(), + "Check if some statements are ready, hscr_bind connections " + "count " + "= {}", + _hscr_bind->connections_count()); + for (uint32_t conn = 0; conn < _hscr_bind->connections_count(); + conn++) { + if (_hscr_bind->ready(conn)) { + SPDLOG_LOGGER_DEBUG( + log_v2::sql(), + "Sending {} hosts rows of host status on connection {}", + _hscr_bind->size(conn), conn); + // Setting the good bind to the stmt + _hscr_bind->apply_to_stmt(conn); + // Executing the stmt + _mysql.run_statement(*_hscr_update, + database::mysql_error::store_host_status, + conn); + _add_action(conn, actions::hosts); + } } } - } - if (_sscr_bind) { - SPDLOG_LOGGER_TRACE( - log_v2::sql(), - "Check if some statements are ready, sscr_bind connections " - "count " - "= {}", - _sscr_bind->connections_count()); - for (uint32_t conn = 0; conn < _sscr_bind->connections_count(); - conn++) { - if (_sscr_bind->ready(conn)) { - SPDLOG_LOGGER_DEBUG( - log_v2::sql(), - "Sending {} services rows of service status on connection {}", - _sscr_bind->size(conn), conn); - // Setting the good bind to the stmt - _sscr_bind->apply_to_stmt(conn); - // Executing the stmt - _mysql.run_statement(*_sscr_update, - database::mysql_error::store_service_status, - conn); - _add_action(conn, actions::services); + if (_sscr_bind) { + SPDLOG_LOGGER_TRACE( + log_v2::sql(), + "Check if some statements are ready, sscr_bind connections " + "count " + "= {}", + _sscr_bind->connections_count()); + for (uint32_t conn = 0; conn < _sscr_bind->connections_count(); + conn++) { + if (_sscr_bind->ready(conn)) { + SPDLOG_LOGGER_DEBUG(log_v2::sql(), + "Sending {} services rows of service " + "status on connection {}", + _sscr_bind->size(conn), conn); + // Setting the good bind to the stmt + _sscr_bind->apply_to_stmt(conn); + // Executing the stmt + _mysql.run_statement( + *_sscr_update, database::mysql_error::store_service_status, + conn); + _add_action(conn, actions::services); + } } } } - } - if (_store_in_resources) { - if (_hscr_resources_bind) { - for (uint32_t conn = 0; - conn < _hscr_resources_bind->connections_count(); conn++) { - if (_hscr_resources_bind->ready(conn)) { - SPDLOG_LOGGER_DEBUG( - log_v2::sql(), - "Sending {} host rows of resource status on connection {}", - _hscr_resources_bind->size(conn), conn); - // Setting the good bind to the stmt - _hscr_resources_bind->apply_to_stmt(conn); - // Executing the stmt - _mysql.run_statement(*_hscr_resources_update, - database::mysql_error::store_host_status, - conn); - _add_action(conn, actions::resources); + if (_store_in_resources) { + if (_hscr_resources_bind) { + for (uint32_t conn = 0; + conn < _hscr_resources_bind->connections_count(); conn++) { + if (_hscr_resources_bind->ready(conn)) { + SPDLOG_LOGGER_DEBUG( + log_v2::sql(), + "Sending {} host rows of resource status on connection {}", + _hscr_resources_bind->size(conn), conn); + // Setting the good bind to the stmt + _hscr_resources_bind->apply_to_stmt(conn); + // Executing the stmt + _mysql.run_statement(*_hscr_resources_update, + database::mysql_error::store_host_status, + conn); + _add_action(conn, actions::resources); + } } } - } - if (_sscr_resources_bind) { - for (uint32_t conn = 0; - conn < _sscr_resources_bind->connections_count(); conn++) { - if (_sscr_resources_bind->ready(conn)) { - SPDLOG_LOGGER_DEBUG( - log_v2::sql(), - "Sending {} service rows of resource status on connection {}", - _sscr_resources_bind->size(conn), conn); - // Setting the good bind to the stmt - _sscr_resources_bind->apply_to_stmt(conn); - // Executing the stmt - _mysql.run_statement(*_sscr_resources_update, - database::mysql_error::store_service_status, - conn); - _add_action(conn, actions::resources); + if (_sscr_resources_bind) { + for (uint32_t conn = 0; + conn < _sscr_resources_bind->connections_count(); conn++) { + if (_sscr_resources_bind->ready(conn)) { + SPDLOG_LOGGER_DEBUG(log_v2::sql(), + "Sending {} service rows of resource " + "status on connection {}", + _sscr_resources_bind->size(conn), conn); + // Setting the good bind to the stmt + _sscr_resources_bind->apply_to_stmt(conn); + // Executing the stmt + _mysql.run_statement( + *_sscr_resources_update, + database::mysql_error::store_service_status, conn); + _add_action(conn, actions::resources); + } } } } + resources_done = true; } - resources_done = true; - } - bool perfdata_done = false; - { - std::lock_guard lck(*_perfdata_query); - if (_perfdata_query->ready()) { - SPDLOG_LOGGER_DEBUG(log_v2::sql(), "{} new perfdata inserted", - _perfdata_query->row_count()); - _perfdata_query->execute( - _dedicated_connections ? *_dedicated_connections : _mysql); - perfdata_done = true; + bool perfdata_done = false; + { + std::lock_guard lck(*_perfdata_query); + if (_perfdata_query->ready()) { + SPDLOG_LOGGER_DEBUG(log_v2::sql(), "{} new perfdata inserted", + _perfdata_query->row_count()); + _perfdata_query->execute( + _dedicated_connections ? *_dedicated_connections : _mysql); + perfdata_done = true; + } } - } - bool metrics_done = false; - if (now >= _next_update_metrics || sz_metrics >= _max_metrics_queries) { - _next_update_metrics = now + queue_timer_duration; - _update_metrics(); - metrics_done = true; - } + bool metrics_done = false; + if (now >= _next_update_metrics || sz_metrics >= _max_metrics_queries) { + _next_update_metrics = now + queue_timer_duration; + _update_metrics(); + metrics_done = true; + } - bool customvar_done = false; - if (_cv.ready()) { - SPDLOG_LOGGER_DEBUG(log_v2::sql(), "{} new custom variables inserted", - _cv.size()); - std::string query = _cv.get_query(); - int32_t conn = special_conn::custom_variable % _mysql.connections_count(); - _mysql.run_query(query, database::mysql_error::update_customvariables, - conn); - _add_action(conn, actions::custom_variables); - customvar_done = true; - } + bool customvar_done = false; + if (_cv.ready()) { + SPDLOG_LOGGER_DEBUG(log_v2::sql(), "{} new custom variables inserted", + _cv.size()); + std::string query = _cv.get_query(); + int32_t conn = + special_conn::custom_variable % _mysql.connections_count(); + _mysql.run_query(query, database::mysql_error::update_customvariables, + conn); + _add_action(conn, actions::custom_variables); + customvar_done = true; + } - if (_cvs.ready()) { - SPDLOG_LOGGER_DEBUG( - log_v2::sql(), "{} new custom variable status inserted", _cvs.size()); - std::string query = _cvs.get_query(); - int32_t conn = special_conn::custom_variable % _mysql.connections_count(); - _mysql.run_query(query, database::mysql_error::update_customvariables, - conn); - _add_action(conn, actions::custom_variables); - customvar_done = true; - } + if (_cvs.ready()) { + SPDLOG_LOGGER_DEBUG(log_v2::sql(), + "{} new custom variable status inserted", + _cvs.size()); + std::string query = _cvs.get_query(); + int32_t conn = + special_conn::custom_variable % _mysql.connections_count(); + _mysql.run_query(query, database::mysql_error::update_customvariables, + conn); + _add_action(conn, actions::custom_variables); + customvar_done = true; + } - bool downtimes_done = false; - { - std::lock_guard lck(*_downtimes); - if (_downtimes->ready()) { - SPDLOG_LOGGER_DEBUG(log_v2::sql(), "{} new downtimes inserted", - _downtimes->row_count()); - _finish_action(-1, actions::hosts | actions::instances | - actions::downtimes | actions::host_parents | - actions::host_dependencies | - actions::service_dependencies); - int32_t conn = special_conn::downtime % _mysql.connections_count(); - _downtimes->execute(_mysql, database::mysql_error::store_downtime, - conn); - _add_action(conn, actions::downtimes); - downtimes_done = true; + bool downtimes_done = false; + { + std::lock_guard lck(*_downtimes); + if (_downtimes->ready()) { + SPDLOG_LOGGER_DEBUG(log_v2::sql(), "{} new downtimes inserted", + _downtimes->row_count()); + _finish_action(-1, actions::hosts | actions::instances | + actions::downtimes | actions::host_parents | + actions::host_dependencies | + actions::service_dependencies); + int32_t conn = special_conn::downtime % _mysql.connections_count(); + _downtimes->execute(_mysql, database::mysql_error::store_downtime, + conn); + _add_action(conn, actions::downtimes); + downtimes_done = true; + } } - } - bool comments_done = false; - { - std::lock_guard lck(*_comments); - if (_comments->ready()) { - SPDLOG_LOGGER_DEBUG(log_v2::sql(), "{} new comments inserted", - _comments->row_count()); - int32_t conn = special_conn::comment % _mysql.connections_count(); - _comments->execute(_mysql, database::mysql_error::store_downtime, conn); - comments_done = true; - _add_action(conn, actions::comments); + bool comments_done = false; + { + std::lock_guard lck(*_comments); + if (_comments->ready()) { + SPDLOG_LOGGER_DEBUG(log_v2::sql(), "{} new comments inserted", + _comments->row_count()); + int32_t conn = special_conn::comment % _mysql.connections_count(); + _comments->execute(_mysql, database::mysql_error::store_downtime, + conn); + comments_done = true; + _add_action(conn, actions::comments); + } } - } - bool logs_done = false; - { - std::lock_guard lck(*_logs); - if (_logs->ready()) { - SPDLOG_LOGGER_DEBUG(log_v2::sql(), "{} new logs inserted", - _logs->row_count()); - if (_dedicated_connections) - _logs->execute(*_dedicated_connections, - database::mysql_error::update_logs); - else - _logs->execute(_mysql, database::mysql_error::update_logs, - special_conn::log % _mysql.connections_count()); - logs_done = true; + bool logs_done = false; + { + std::lock_guard lck(*_logs); + if (_logs->ready()) { + SPDLOG_LOGGER_DEBUG(log_v2::sql(), "{} new logs inserted", + _logs->row_count()); + if (_dedicated_connections) + _logs->execute(*_dedicated_connections, + database::mysql_error::update_logs); + else + _logs->execute(_mysql, database::mysql_error::update_logs, + special_conn::log % _mysql.connections_count()); + logs_done = true; + } } - } - // End. - SPDLOG_LOGGER_DEBUG(log_v2::sql(), - "unified_sql:_check_queues - resources: {}, " - "perfdata: {}, metrics: {}, customvar: " - "{}, logs: {}, downtimes: {} comments: {}", - resources_done, perfdata_done, metrics_done, - customvar_done, logs_done, downtimes_done, - comments_done); + // End. + SPDLOG_LOGGER_DEBUG(log_v2::sql(), + "unified_sql:_check_queues - resources: {}, " + "perfdata: {}, metrics: {}, customvar: " + "{}, logs: {}, downtimes: {} comments: {}", + resources_done, perfdata_done, metrics_done, + customvar_done, logs_done, downtimes_done, + comments_done); + + } catch (const std::exception& e) { + SPDLOG_LOGGER_ERROR( + log_v2::sql(), "fail to store queued data in database: {}", e.what()); + } if (!_stop_check_queues) { std::lock_guard l(_timer_m); diff --git a/tests/broker-database/networkFailure.robot b/tests/broker-database/networkFailure.robot index 24109de8668..12711b77a45 100644 --- a/tests/broker-database/networkFailure.robot +++ b/tests/broker-database/networkFailure.robot @@ -157,6 +157,43 @@ NetworkDBFailU7 Ctn Stop engine Ctn Kindly Stop Broker +NetworkDBFailU8 + [Documentation] network failure test between broker and database: we wait for the connection to be established and then we shutdown the connection until _check_queues failure + [Tags] MON-71277 broker database network unified_sql unstable + Ctn Reset Eth Connection + Ctn Config Engine ${1} + Ctn Config Broker central + Ctn Config Broker Sql Output central unified_sql + Ctn Broker Config Output Set central central-broker-unified-sql db_host 127.0.0.1 + Ctn Broker Config Output Set central central-broker-unified-sql connections_count 3 + Ctn Broker Config Log central sql trace + Ctn Config Broker rrd + Ctn Config Broker module + ${start} Get Current Date + Ctn Start Broker + Ctn Start engine + ${result} Ctn Check Connections + Should Be True ${result} Broker and Engine are not connected + ${content} Create List run query: SELECT + ${result} Ctn Find In Log With Timeout ${centralLog} ${start} ${content} 40 + Should Be True ${result} No SELECT done by broker in the DB + + Log To Console Connection failure. + ${start} Get Current Date + Ctn Disable Eth Connection On Port port=3306 + ${content} Create List fail to store queued data in database + ${result} Ctn Find In Log With Timeout ${centralLog} ${start} ${content} 40 + Should Be True ${result} No failure found in log + + ${start} Get Current Date + Log To Console Reestablishing the connection and test last steps. + Ctn Reset Eth Connection + ${content} Create List unified_sql:_check_queues + ${result} Ctn Find In Log With Timeout ${centralLog} ${start} ${content} 40 + Ctn Stop engine + Ctn Kindly Stop Broker + + *** Keywords *** Ctn Disable Sleep Enable From 54ef060256d7291cf145904128480bff9f2c287b Mon Sep 17 00:00:00 2001 From: jean-christophe81 <98889244+jean-christophe81@users.noreply.github.com> Date: Wed, 15 May 2024 10:36:58 +0200 Subject: [PATCH 04/60] enh(engine): Allow bypass the notification inhibitions for recovery notifications (#1260) REFS: MON-33121 --- engine/doc/engine-doc.md | 27 ++++++ .../engine/configuration/extended_conf.hh | 5 +- .../centreon/engine/configuration/state.hh | 3 + engine/src/configuration/applier/state.cc | 2 + engine/src/configuration/extended_conf.cc | 2 + engine/src/configuration/state.cc | 42 ++++++++- engine/src/main.cc | 4 +- engine/src/notifier.cc | 27 ++++-- tests/broker-engine/notifications.robot | 93 +++++++++++++++++++ tests/engine/extended_conf.robot | 12 +-- tests/resources/Engine.py | 32 +++++++ tests/resources/resources.resource | 23 ++++- 12 files changed, 248 insertions(+), 24 deletions(-) diff --git a/engine/doc/engine-doc.md b/engine/doc/engine-doc.md index d3aa94b0ede..aa1fa21912f 100644 --- a/engine/doc/engine-doc.md +++ b/engine/doc/engine-doc.md @@ -30,3 +30,30 @@ The main main job is done by whitelist class, it parses file and compares final This class is a singleton witch is replace by another instance each time conf is reloaded. Checkable class inherited by service and host classes keeps the last result of whitelist's check in cache in order to reduce CPU whitelist usage. + +## Extended configuration +Users can pass an additional configuration file to engine. Gorgone is not aware of this file, so users can override centengine.cfg configuration. +Each entry found in additional json configuration file overrides its twin in `centengine.cfg`. + +### examples of command line +```sh +/usr/sbin/centengine --config-file=/tmp/centengine_extend.json /etc/centreon-engine/centengine.cfg + +/usr/sbin/centengine --c /tmp/file1.json --c /tmp/file2.json /etc/centreon-engine/centengine.cfg +``` + +In the second case, values of file1.json will override values of centengine.cfg and values of file2.json will override values of file1.json + +### file format +```json +{ + "send_recovery_notifications_anyways": true +} +``` + +### implementation detail +In `state.cc` all setters have two methods: +* `apply_from_cfg` +* `apply_from_json`. + +On configuration update, we first parse the `centengine.cfg` and all the `*.cfg` files, and then we parse additional configuration files. diff --git a/engine/inc/com/centreon/engine/configuration/extended_conf.hh b/engine/inc/com/centreon/engine/configuration/extended_conf.hh index 48baeff71f0..fbd65a3c6c3 100644 --- a/engine/inc/com/centreon/engine/configuration/extended_conf.hh +++ b/engine/inc/com/centreon/engine/configuration/extended_conf.hh @@ -62,7 +62,10 @@ template void extended_conf::load_all(file_path_iterator begin, file_path_iterator end) { _confs.clear(); for (; begin != end; ++begin) { - _confs.emplace_back(std::make_unique(*begin)); + try { + _confs.emplace_back(std::make_unique(*begin)); + } catch (const std::exception&) { + } } } diff --git a/engine/inc/com/centreon/engine/configuration/state.hh b/engine/inc/com/centreon/engine/configuration/state.hh index 53f8b28997e..09b37a4512d 100644 --- a/engine/inc/com/centreon/engine/configuration/state.hh +++ b/engine/inc/com/centreon/engine/configuration/state.hh @@ -447,6 +447,8 @@ class state { void use_timezone(std::string const& value); bool use_true_regexp_matching() const noexcept; void use_true_regexp_matching(bool value); + bool use_send_recovery_notifications_anyways() const; + void use_send_recovery_notifications_anyways(bool value); using setter_map = absl::flat_hash_map>; @@ -650,6 +652,7 @@ class state { std::string _log_level_runtime; std::string _use_timezone; bool _use_true_regexp_matching; + bool _send_recovery_notifications_anyways; }; } // namespace com::centreon::engine::configuration diff --git a/engine/src/configuration/applier/state.cc b/engine/src/configuration/applier/state.cc index d65e5c5aa9c..ff8ae42e7cd 100644 --- a/engine/src/configuration/applier/state.cc +++ b/engine/src/configuration/applier/state.cc @@ -459,6 +459,8 @@ void applier::state::_apply(configuration::state const& new_cfg) { config->log_level_comments(new_cfg.log_level_comments()); config->log_level_macros(new_cfg.log_level_macros()); config->use_true_regexp_matching(new_cfg.use_true_regexp_matching()); + config->use_send_recovery_notifications_anyways( + new_cfg.use_send_recovery_notifications_anyways()); config->user(new_cfg.user()); // Set this variable just the first time. diff --git a/engine/src/configuration/extended_conf.cc b/engine/src/configuration/extended_conf.cc index 24738e1c11e..bb0cbd846eb 100644 --- a/engine/src/configuration/extended_conf.cc +++ b/engine/src/configuration/extended_conf.cc @@ -33,6 +33,7 @@ std::list> extended_conf::_confs; extended_conf::extended_conf(const std::string& path) : _path(path) { if (::stat(_path.c_str(), &_file_info)) { SPDLOG_LOGGER_ERROR(log_v2::config(), "can't access to {}", _path); + throw exceptions::msg_fmt("can't access to {}", _path); } try { _content = common::rapidjson_helper::read_from_file(_path); @@ -42,6 +43,7 @@ extended_conf::extended_conf(const std::string& path) : _path(path) { log_v2::config(), "extended_conf::extended_conf : fail to read json content from {}: {}", _path, e.what()); + throw; } } diff --git a/engine/src/configuration/state.cc b/engine/src/configuration/state.cc index 12fbdcdae75..dd549b763cf 100644 --- a/engine/src/configuration/state.cc +++ b/engine/src/configuration/state.cc @@ -307,6 +307,8 @@ void state::_init_setter() { SETTER(bool, use_true_regexp_matching, "use_true_regexp_matching"); SETTER(std::string const&, _set_comment_file, "xcddefault_comment_file"); SETTER(std::string const&, _set_downtime_file, "xdddefault_downtime_file"); + SETTER(bool, use_send_recovery_notifications_anyways, + "send_recovery_notifications_anyways"); } // Default values. @@ -581,7 +583,8 @@ state::state() _log_level_process(default_log_level_process), _log_level_runtime(default_log_level_runtime), _use_timezone(default_use_timezone), - _use_true_regexp_matching(default_use_true_regexp_matching) { + _use_true_regexp_matching(default_use_true_regexp_matching), + _send_recovery_notifications_anyways(false) { static absl::once_flag _init_call_once; absl::call_once(_init_call_once, _init_setter); } @@ -764,6 +767,8 @@ state& state::operator=(state const& right) { _log_level_runtime = right._log_level_runtime; _use_timezone = right._use_timezone; _use_true_regexp_matching = right._use_true_regexp_matching; + _send_recovery_notifications_anyways = + right._send_recovery_notifications_anyways; } return *this; } @@ -928,7 +933,9 @@ bool state::operator==(state const& right) const noexcept { _log_level_process == right._log_level_process && _log_level_runtime == right._log_level_runtime && _use_timezone == right._use_timezone && - _use_true_regexp_matching == right._use_true_regexp_matching); + _use_true_regexp_matching == right._use_true_regexp_matching && + _send_recovery_notifications_anyways == + right._send_recovery_notifications_anyways); } /** @@ -4815,6 +4822,37 @@ void state::enable_macros_filter(bool value) { _enable_macros_filter = value; } +/** + * @brief Get _send_recovery_notifications_anyways + * + * Having a resource that has entered a non-OK state during a notification + * period and goes back to an OK state out of a notification period, then only + * if send_recovery_notifications_anyways is set to 1, the recovery notification + * must be sent to all users that have previously received the alert + * notification. + * + * @return true + * @return false + */ +bool state::use_send_recovery_notifications_anyways() const { + return _send_recovery_notifications_anyways; +} + +/** + * @brief + * + * Having a resource that has entered a non-OK state during a notification + * period and goes back to an OK state out of a notification period, then only + * if send_recovery_notifications_anyways is set to 1, the recovery notification + * must be sent to all users that have previously received the alert + * notification. + * + * @param value true if have to nitify anyway + */ +void state::use_send_recovery_notifications_anyways(bool value) { + _send_recovery_notifications_anyways = value; +} + /** * @brief modify state according json passed in parameter * diff --git a/engine/src/main.cc b/engine/src/main.cc index 8953c0ccc67..2581b42c043 100644 --- a/engine/src/main.cc +++ b/engine/src/main.cc @@ -127,7 +127,7 @@ int main(int argc, char* argv[]) { bool display_license(false); bool error(false); bool diagnose(false); - std::set extended_conf_file; + std::vector extended_conf_file; // Process all command line arguments. int c; @@ -161,7 +161,7 @@ int main(int argc, char* argv[]) { break; case 'c': if (optarg) - extended_conf_file.insert(optarg); + extended_conf_file.emplace_back(optarg); break; default: error = true; diff --git a/engine/src/notifier.cc b/engine/src/notifier.cc index 6529945c96a..cc854ce3aec 100644 --- a/engine/src/notifier.cc +++ b/engine/src/notifier.cc @@ -458,16 +458,27 @@ bool notifier::_is_notification_viable_recovery(reason_type type std::time_t now; std::time(&now); + // if use_send_recovery_notifications_anyways flag is set, we don't take + // timeperiod into account for recovery if (!check_time_against_period_for_notif(now, tp)) { - engine_logger(dbg_notifications, more) - << "This notifier shouldn't have notifications sent out " - "at this time."; - SPDLOG_LOGGER_DEBUG(log_v2::notifications(), - "This notifier shouldn't have notifications sent out " - "at this time."); - retval = false; - send_later = true; + if (config->use_send_recovery_notifications_anyways()) { + SPDLOG_LOGGER_DEBUG(log_v2::notifications(), + "send_recovery_notifications_anyways flag enabled, " + "recovery notification is viable even if we are " + "out of timeperiod at this time."); + } else { + engine_logger(dbg_notifications, more) + << "This notifier shouldn't have notifications sent out " + "at this time."; + SPDLOG_LOGGER_DEBUG( + log_v2::notifications(), + "This notifier shouldn't have notifications sent out " + "at this time."); + retval = false; + send_later = true; + } } + /* if this notifier is currently in a scheduled downtime period, don't send * the notification */ else if (is_in_downtime()) { diff --git a/tests/broker-engine/notifications.robot b/tests/broker-engine/notifications.robot index 95b62d01c7d..bf67ece87ed 100644 --- a/tests/broker-engine/notifications.robot +++ b/tests/broker-engine/notifications.robot @@ -1311,6 +1311,99 @@ not20 Ctn Stop Engine Ctn Kindly Stop Broker +not_in_timeperiod_without_send_recovery_notifications_anyways + [Documentation] This test case configures a single service and verifies that a notification is sent when the service is in a non-OK state and OK is not sent outside timeperiod when _send_recovery_notifications_anyways is not set + [Tags] MON-33121 broker engine services hosts notification + Ctn Config Engine ${1} ${1} ${1} + Ctn Config Notifications + Ctn Engine Config Set Value In Hosts 0 host_1 notifications_enabled 1 + Ctn Engine Config Set Value In Hosts 0 host_1 notification_options d,r + Ctn Engine Config Set Value In Hosts 0 host_1 contacts John_Doe + Ctn Engine Config Set Value In Services 0 service_1 contacts John_Doe + Ctn Engine Config Set Value In Services 0 service_1 notification_options w,c,r + Ctn Engine Config Set Value In Services 0 service_1 notifications_enabled 1 + Ctn Engine Config Set Value In Services 0 service_1 notification_period short_time_period + Ctn Engine Config Set Value In Contacts 0 John_Doe host_notification_commands command_notif + Ctn Engine Config Set Value In Contacts 0 John_Doe service_notification_commands command_notif + ${cmd_1} Ctn Get Service Command Id 1 + Log To Console service_1 has command id ${cmd_1} + Ctn Set Command Status ${cmd_1} 2 + + ${start} Get Current Date + Ctn Create Single Day Time Period 0 short_time_period ${start} 2 + + Ctn Start Broker + Ctn Start engine + + # Let's wait for the external command check start + Ctn Wait For Engine To Be Ready ${start} + + ## Time to set the service to CRITICAL HARD. + Ctn Process Service Result Hard host_1 service_1 2 critical + + ${result} Ctn Check Service Status With Timeout host_1 service_1 ${2} 60 HARD + Should Be True ${result} Service (host_1,service_1) should be CRITICAL HARD + + ${content} Create List SERVICE NOTIFICATION: John_Doe;host_1;service_1;CRITICAL;command_notif;critical + ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 60 + Should Be True ${result} The notification is not sent + + Sleep 3m + Ctn Set Command Status ${cmd_1} 0 + Ctn Process Service Check Result host_1 service_1 0 ok + + ${content} Create List SERVICE NOTIFICATION: John_Doe;host_1;service_1;RECOVERY (OK);command_notif;ok + ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 60 + Should Not Be True ${result} The notification is sent out of time period + +not_in_timeperiod_with_send_recovery_notifications_anyways + [Documentation] This test case configures a single service and verifies that a notification is sent when the service is in a non-OK state and OK is sent outside timeperiod when _send_recovery_notifications_anyways is set + [Tags] MON-33121 broker engine services hosts notification mon-33121 + Ctn Config Engine ${1} ${1} ${1} + Ctn Config Notifications + Ctn Engine Config Set Value In Hosts 0 host_1 notifications_enabled 1 + Ctn Engine Config Set Value In Hosts 0 host_1 notification_options d,r + Ctn Engine Config Set Value In Hosts 0 host_1 contacts John_Doe + Ctn Engine Config Set Value In Services 0 service_1 contacts John_Doe + Ctn Engine Config Set Value In Services 0 service_1 notification_options w,c,r + Ctn Engine Config Set Value In Services 0 service_1 notifications_enabled 1 + Ctn Engine Config Set Value In Services 0 service_1 notification_period short_time_period + Ctn Engine Config Set Value In Contacts 0 John_Doe host_notification_commands command_notif + Ctn Engine Config Set Value In Contacts 0 John_Doe service_notification_commands command_notif + Create File /tmp/centengine_extend.json {"send_recovery_notifications_anyways": true} + + ${cmd_1} Ctn Get Service Command Id 1 + Log To Console service_1 has command id ${cmd_1} + Ctn Set Command Status ${cmd_1} 2 + + ${start} Get Current Date + Ctn Create Single Day Time Period 0 short_time_period ${start} 2 + + Ctn Start Broker + Ctn Start Engine With Extend Conf + + # Let's wait for the external command check start + Ctn Wait For Engine To Be Ready ${start} + + ## Time to set the service to CRITICAL HARD. + Ctn Process Service Result Hard host_1 service_1 2 critical + + ${result} Ctn Check Service Status With Timeout host_1 service_1 ${2} 60 HARD + Should Be True ${result} Service (host_1,service_1) should be CRITICAL HARD + + ${content} Create List SERVICE NOTIFICATION: John_Doe;host_1;service_1;CRITICAL;command_notif;critical + ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 60 + Should Be True ${result} The notification is not sent + + Sleep 3m + Ctn Set Command Status ${cmd_1} 0 + Ctn Process Service Check Result host_1 service_1 0 ok + + ${content} Create List SERVICE NOTIFICATION: John_Doe;host_1;service_1;RECOVERY (OK);command_notif;ok + ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 60 + Should Be True ${result} The notification is not sent outside time period + + *** Keywords *** Ctn Config Notifications [Documentation] Configuring engine notification settings. diff --git a/tests/engine/extended_conf.robot b/tests/engine/extended_conf.robot index 16673eff249..89c5e9e1692 100644 --- a/tests/engine/extended_conf.robot +++ b/tests/engine/extended_conf.robot @@ -17,11 +17,7 @@ EXT_CONF1 Ctn Config Broker module ${1} Create File /tmp/centengine_extend.json {"log_level_checks": "trace", "log_level_comments": "debug"} ${start} Get Current Date - Start Process - ... /usr/sbin/centengine - ... --config-file\=/tmp/centengine_extend.json - ... ${EtcRoot}/centreon-engine/config0/centengine.cfg - ... alias=e0 + Ctn Start Engine With Extend Conf Ctn Wait For Engine To Be Ready ${start} ${1} ${level} Ctn Get Engine Log Level 50001 checks Should Be Equal ${level} trace log_level_checks must be the extended conf value @@ -35,11 +31,7 @@ EXT_CONF2 Ctn Config Broker module ${1} Create File /tmp/centengine_extend.json {} ${start} Get Current Date - Start Process - ... /usr/sbin/centengine - ... --config-file\=/tmp/centengine_extend.json - ... ${EtcRoot}/centreon-engine/config0/centengine.cfg - ... alias=e0 + Ctn Start Engine With Extend Conf Ctn Wait For Engine To Be Ready ${start} ${1} Create File /tmp/centengine_extend.json {"log_level_checks": "trace", "log_level_comments": "debug"} diff --git a/tests/resources/Engine.py b/tests/resources/Engine.py index 0a5c70a31bb..cd45400e11c 100755 --- a/tests/resources/Engine.py +++ b/tests/resources/Engine.py @@ -6,6 +6,8 @@ import engine_pb2 import engine_pb2_grpc from array import array +from dateutil import parser +import datetime from os import makedirs, chmod from os.path import exists, dirname from robot.api import logger @@ -3316,3 +3318,33 @@ def ctn_get_engine_log_level(port, log, timeout=TIMEOUT): except: logger.console("gRPC server not ready") + + + +def ctn_create_single_day_time_period(idx: int, time_period_name: str, date, minute_duration: int): + """ + Create a single day time period with a single time range from date to date + minute_duration + Args + idx: poller index + time_period_name: must be unique + date: time range start + minute_duration: time range length in minutes + """ + try: + my_date = parser.parse(date) + except: + my_date = datetime.fromtimestamp(date) + + filename = f"{ETC_ROOT}/centreon-engine/config{idx}/timeperiods.cfg" + + begin = my_date.time() + end = my_date + datetime.timedelta(minutes=minute_duration) + + with open(filename, "a+") as f: + f.write(f""" +define timeperiod {{ + timeperiod_name {time_period_name} + alias {time_period_name} + {my_date.date().isoformat()} {begin.strftime("%H:%M")}-{end.time().strftime("%H:%M")} +}} +""") diff --git a/tests/resources/resources.resource b/tests/resources/resources.resource index 1195e482ca2..9b7368b20c9 100644 --- a/tests/resources/resources.resource +++ b/tests/resources/resources.resource @@ -142,7 +142,7 @@ Ctn Stop Processes Ctn Kill Broker Ctn Kill Engine -Ctn Start engine +Ctn Start Engine ${count} Ctn Get Engines Count FOR ${idx} IN RANGE 0 ${count} ${alias} Catenate SEPARATOR= e ${idx} @@ -159,6 +159,27 @@ Ctn Start engine Start Process /usr/sbin/centengine ${conf} alias=${alias} END +Ctn Start Engine With Extend Conf + ${count} Ctn Get Engines Count + FOR ${idx} IN RANGE 0 ${count} + ${alias} Catenate SEPARATOR= e ${idx} + ${conf} Catenate SEPARATOR= ${EtcRoot} /centreon-engine/config ${idx} /centengine.cfg + ${log} Catenate SEPARATOR= ${VarRoot} /log/centreon-engine/config ${idx} + ${lib} Catenate SEPARATOR= ${VarRoot} /lib/centreon-engine/config ${idx} + Create Directory ${log} + Create Directory ${lib} + TRY + Remove File ${lib}/rw/centengine.cmd + EXCEPT + Log can't remove ${lib}/rw/centengine.cmd don't worry + END + Start Process + ... /usr/sbin/centengine + ... --config-file\=/tmp/centengine_extend.json + ... ${conf} + ... alias=${alias} + END + Ctn Restart Engine Ctn Stop engine Ctn Start engine From 39916b6d050ca23433dae323e4ca6bee7f5a0c1e Mon Sep 17 00:00:00 2001 From: jean-christophe81 <98889244+jean-christophe81@users.noreply.github.com> Date: Wed, 15 May 2024 14:38:12 +0200 Subject: [PATCH 05/60] enh(broker/common) Pool moved to common (#1302) REFS: MON-34074 Co-authored-by: David Boucher --- broker/CMakeLists.txt | 2 - broker/bam/src/monitoring_stream.cc | 4 +- broker/bam/test/ba/kpi_ba.cc | 3 - broker/bam/test/ba/kpi_service.cc | 2 - .../bam/test/configuration/applier-boolexp.cc | 3 - broker/bam/test/exp_builder/exp_builder.cc | 2 - broker/bam/test/monitoring_stream.cc | 3 - broker/bam/test/time/check_timeperiod.cc | 3 - broker/core/inc/com/centreon/broker/pool.hh | 111 -------- .../inc/com/centreon/broker/stats/center.hh | 1 - broker/core/multiplexing/src/engine.cc | 28 +- .../multiplexing/test/engine/start_stop.cc | 2 - broker/core/multiplexing/test/muxer/read.cc | 3 - .../core/multiplexing/test/publisher/read.cc | 3 - .../core/multiplexing/test/publisher/write.cc | 3 - broker/core/src/config/applier/init.cc | 41 ++- broker/core/src/main.cc | 40 +-- broker/core/src/pool.cc | 201 -------------- broker/core/src/processing/feeder.cc | 8 +- broker/core/src/stats/center.cc | 44 ++- broker/core/src/stats/helper.cc | 37 +-- broker/core/test/bbdo/output.cc | 2 - broker/core/test/compression/stream/read.cc | 3 - broker/core/test/compression/stream/write.cc | 3 - broker/core/test/config/init.cc | 3 - broker/core/test/main.cc | 8 +- broker/core/test/misc/perfdata.cc | 3 - broker/core/test/modules/module.cc | 3 - broker/core/test/mysql/mysql.cc | 3 - broker/core/test/processing/acceptor.cc | 3 - broker/core/test/processing/feeder.cc | 6 - broker/core/test/rpc/brokerrpc.cc | 6 - broker/grpc/src/stream.cc | 36 +-- broker/grpc/test/acceptor.cc | 13 +- broker/grpc/test/grpc_test_include.hh | 2 +- broker/grpc/test/stream_test.cc | 6 - broker/http_client/test/http_client_test.cc | 6 +- broker/http_tsdb/test/stream_test.cc | 4 +- broker/lua/test/lua.cc | 3 - broker/rrd/test/rrd.cc | 3 - broker/simu/test/simu.cc | 3 - broker/stats/test/stats.cc | 6 +- broker/stats_exporter/src/exporter.cc | 37 +-- .../com/centreon/broker/storage/rebuilder.hh | 4 +- broker/storage/src/conflict_manager.cc | 5 +- broker/storage/src/rebuilder.cc | 34 +-- broker/storage/test/conflict_manager.cc | 3 - broker/storage/test/perfdata.cc | 3 - broker/storage/test/status-entry.cc | 3 - .../inc/com/centreon/broker/tcp/tcp_async.hh | 4 +- broker/tcp/src/stream.cc | 10 +- broker/tcp/src/tcp_async.cc | 53 ++-- broker/tcp/test/acceptor.cc | 8 +- broker/tcp/test/connector.cc | 7 +- broker/tls/test/acceptor.cc | 7 +- broker/tls/test/nominal.cc | 10 +- broker/tls/test/read.cc | 3 - broker/tls2/test/acceptor.cc | 7 +- broker/tls2/test/nominal.cc | 8 - broker/tls2/test/read.cc | 3 - .../centreon/broker/unified_sql/rebuilder.hh | 4 +- broker/unified_sql/src/rebuilder.cc | 34 +-- broker/unified_sql/src/stream.cc | 9 +- broker/unified_sql/test/conflict_manager.cc | 35 ++- broker/unified_sql/test/perfdata.cc | 3 - broker/unified_sql/test/rebuild_message.cc | 3 - broker/unified_sql/test/status-entry.cc | 3 - broker/victoria_metrics/src/connector.cc | 42 +-- broker/victoria_metrics/src/factory.cc | 37 +-- broker/victoria_metrics/src/main.cc | 33 ++- broker/victoria_metrics/src/stream.cc | 35 ++- broker/victoria_metrics/test/factory_test.cc | 10 +- common/CMakeLists.txt | 1 + common/doc/common-doc.md | 10 + common/doc/pictures/logo.jpg | Bin 0 -> 49244 bytes common/inc/com/centreon/common/pool.hh | 87 ++++++ common/src/pool.cc | 173 ++++++++++++ engine/precomp_inc/precomp.hh | 1 + engine/src/main.cc | 21 +- engine/tests/main.cc | 41 +-- tests/bench.py | 259 ++++++++++++++++++ tests/broker/command-line.robot | 2 +- 82 files changed, 884 insertions(+), 837 deletions(-) delete mode 100644 broker/core/inc/com/centreon/broker/pool.hh delete mode 100644 broker/core/src/pool.cc create mode 100644 common/doc/common-doc.md create mode 100644 common/doc/pictures/logo.jpg create mode 100644 common/inc/com/centreon/common/pool.hh create mode 100644 common/src/pool.cc create mode 100644 tests/bench.py diff --git a/broker/CMakeLists.txt b/broker/CMakeLists.txt index 4b476d2ab58..f1d1e076fc6 100644 --- a/broker/CMakeLists.txt +++ b/broker/CMakeLists.txt @@ -349,7 +349,6 @@ set(LIBROKER_SOURCES ${SRC_DIR}/misc/uuid.cc ${SRC_DIR}/misc/variant.cc ${SRC_DIR}/modules/handle.cc - ${SRC_DIR}/pool.cc ${SRC_DIR}/persistent_cache.cc ${SRC_DIR}/persistent_file.cc ${SRC_DIR}/processing/acceptor.cc @@ -418,7 +417,6 @@ set(LIBROKER_SOURCES ${INC_DIR}/misc/time.hh ${INC_DIR}/misc/variant.hh ${INC_DIR}/modules/handle.hh - ${INC_DIR}/pool.hh ${INC_DIR}/persistent_cache.hh ${INC_DIR}/persistent_file.hh ${INC_DIR}/processing/acceptor.hh diff --git a/broker/bam/src/monitoring_stream.cc b/broker/bam/src/monitoring_stream.cc index 92d21342ce1..6ba0b889ea4 100644 --- a/broker/bam/src/monitoring_stream.cc +++ b/broker/bam/src/monitoring_stream.cc @@ -38,8 +38,8 @@ #include "com/centreon/broker/neb/internal.hh" #include "com/centreon/broker/neb/service.hh" #include "com/centreon/broker/neb/service_status.hh" -#include "com/centreon/broker/pool.hh" #include "com/centreon/broker/timestamp.hh" +#include "com/centreon/common/pool.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon::exceptions; @@ -68,7 +68,7 @@ monitoring_stream::monitoring_stream(const std::string& ext_cmd_file, _pending_request(0), _storage_db_cfg(storage_db_cfg), _cache(std::move(cache)), - _forced_svc_checks_timer{pool::io_context()} { + _forced_svc_checks_timer{com::centreon::common::pool::io_context()} { SPDLOG_LOGGER_TRACE(log_v2::bam(), "BAM: monitoring_stream constructor"); if (!_conf_queries_per_transaction) { _conf_queries_per_transaction = 1; diff --git a/broker/bam/test/ba/kpi_ba.cc b/broker/bam/test/ba/kpi_ba.cc index fe1e517d1f2..73b02558c5c 100644 --- a/broker/bam/test/ba/kpi_ba.cc +++ b/broker/bam/test/ba/kpi_ba.cc @@ -33,8 +33,6 @@ using namespace com::centreon::broker; -extern std::shared_ptr g_io_context; - class KpiBA : public ::testing::Test { protected: std::unique_ptr _aply_state; @@ -44,7 +42,6 @@ class KpiBA : public ::testing::Test { public: void SetUp() override { // Initialization. - g_io_context->restart(); config::applier::init(0, "test_broker", 0); _aply_state = std::make_unique(); diff --git a/broker/bam/test/ba/kpi_service.cc b/broker/bam/test/ba/kpi_service.cc index a0a017bea86..c4a0ce24cd2 100644 --- a/broker/bam/test/ba/kpi_service.cc +++ b/broker/bam/test/ba/kpi_service.cc @@ -36,7 +36,6 @@ using namespace com::centreon::broker; -extern std::shared_ptr g_io_context; class BamBA : public ::testing::Test { protected: @@ -47,7 +46,6 @@ class BamBA : public ::testing::Test { public: void SetUp() override { // Initialization. - g_io_context->restart(); config::applier::init(0, "test_broker", 0); _aply_state = std::make_unique(); diff --git a/broker/bam/test/configuration/applier-boolexp.cc b/broker/bam/test/configuration/applier-boolexp.cc index 620cd81174c..3211ae726ac 100644 --- a/broker/bam/test/configuration/applier-boolexp.cc +++ b/broker/bam/test/configuration/applier-boolexp.cc @@ -24,12 +24,9 @@ using namespace com::centreon::broker; -extern std::shared_ptr g_io_context; - class ApplierBoolexp : public ::testing::Test { public: void SetUp() override { - g_io_context->restart(); // Initialization. config::applier::init(0, "test_broker", 0); diff --git a/broker/bam/test/exp_builder/exp_builder.cc b/broker/bam/test/exp_builder/exp_builder.cc index 03b374ab938..153c0d3bede 100644 --- a/broker/bam/test/exp_builder/exp_builder.cc +++ b/broker/bam/test/exp_builder/exp_builder.cc @@ -34,7 +34,6 @@ using namespace com::centreon::broker; -extern std::shared_ptr g_io_context; class BamExpBuilder : public ::testing::Test { protected: @@ -42,7 +41,6 @@ class BamExpBuilder : public ::testing::Test { public: void SetUp() override { - g_io_context->restart(); try { config::applier::init(0, "test_broker", 0); log_v2::bam()->set_level(spdlog::level::debug); diff --git a/broker/bam/test/monitoring_stream.cc b/broker/bam/test/monitoring_stream.cc index b40d0ef5fd9..7877e2d4957 100644 --- a/broker/bam/test/monitoring_stream.cc +++ b/broker/bam/test/monitoring_stream.cc @@ -28,11 +28,8 @@ using namespace com::centreon::broker; using namespace com::centreon::broker::bam; -extern std::shared_ptr g_io_context; - class BamMonitoringStream : public testing::Test { void SetUp() override { - g_io_context->restart(); config::applier::init(0, "test_broker", 0); } void TearDown() override { config::applier::deinit(); } diff --git a/broker/bam/test/time/check_timeperiod.cc b/broker/bam/test/time/check_timeperiod.cc index 634c7c87eee..ba58e3382fd 100644 --- a/broker/bam/test/time/check_timeperiod.cc +++ b/broker/bam/test/time/check_timeperiod.cc @@ -40,8 +40,6 @@ using namespace com::centreon::exceptions; using namespace com::centreon::broker; -extern std::shared_ptr g_io_context; - struct options { options() : preferred_time(0), ref_time(0) {} std::vector > period; @@ -143,7 +141,6 @@ static void parse_file(char const* filename, options& opt) { class BamTime : public ::testing::Test { public: void SetUp() override { - g_io_context->restart(); config::applier::init(0, "test_broker", 0); } diff --git a/broker/core/inc/com/centreon/broker/pool.hh b/broker/core/inc/com/centreon/broker/pool.hh deleted file mode 100644 index 8d4f45f1794..00000000000 --- a/broker/core/inc/com/centreon/broker/pool.hh +++ /dev/null @@ -1,111 +0,0 @@ -/* -** Copyright 2020-2021 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ -#ifndef CENTREON_BROKER_CORE_INC_COM_CENTREON_BROKER_POOL_HH_ -#define CENTREON_BROKER_CORE_INC_COM_CENTREON_BROKER_POOL_HH_ - -#include "broker.pb.h" - -namespace com::centreon::broker { - -/** - * @brief The Broker's thread pool. - * - * At the origin, this thread pool is configured to be used by ASIO. Each thread - * in this pool runs an io_context that allows any part in Broker to post - * a work to be done. - * - * This pool may look a little complicated. We can see inside it several - * attributes, let's make a quick tour of them. A thread pool is an array of - * threads. This array, here, is a std::vector named _pool. - * - * This pool is instanciated through a unique instance. So its constructor is - * private and we have a static method named instance() to get it. - * - * Initially, the pool is not started. To start it, there is a static method - * named start() that takes one argument: the number of threads. - * - * If the start() method is not called before using the pool, broker does not - * work, at least not as expected. If the given size is 0, its size will be - * initialized with the number of cpus on the host computer. - * - * To post tasks to the pool, we use the ASIO api, for that we need an - * asio::io_context witch is g_io_context instanciated in both main of engine - * and cbd and an asio::io_service::work which are defined when then pool is - * constructed. - * - * There is a _closed boolean variable used internally to know if the pool is - * running (and not closed) or stopped (and closed). To work with it, we also - * use a mutex _closed_m. - * - * And to have statistics on that pool, every 10s, we execute a task - * _check_latency() whose goal is to measure the duration between the time point - * when we ask to execute a task and the time point when we get its execution. - * This duration is stored in _latency. - * - * We can see a steady_timer in the class, its goal is to cadence this check. - */ -class pool { - static pool* _instance; - static std::mutex _init_m; - - double _last_check_latency; - ThreadPool* _stats; - const size_t _pool_size; - - std::shared_ptr _io_context; - asio::executor_work_guard _worker; - std::vector _pool; - bool _closed; - mutable std::mutex _closed_m; - - asio::steady_timer _timer; - std::atomic_bool _stats_running; - - pool(const std::shared_ptr& io_context, size_t size); - ~pool() noexcept; - void _stop(); - void _check_latency(const boost::system::error_code& ec); - - public: - pool(const pool&) = delete; - pool& operator=(const pool&) = delete; - - static void load(const std::shared_ptr& io_context, - size_t size); - static void unload(); - static pool& instance(); - static asio::io_context& io_context(); - static std::shared_ptr io_context_ptr(); - - void start_stats(ThreadPool* stats); - void stop_stats(); - - /** - * @brief Returns the number of threads used in the pool. - * - * @return a size. - */ - size_t get_pool_size() const { return _pool_size; } - - // used for tests - double get_last_check_latency(); -}; - -} - -#endif // CENTREON_BROKER_CORE_INC_COM_CENTREON_BROKER_POOL_HH_ diff --git a/broker/core/inc/com/centreon/broker/stats/center.hh b/broker/core/inc/com/centreon/broker/stats/center.hh index a61f9721d19..eb5e732fe4a 100644 --- a/broker/core/inc/com/centreon/broker/stats/center.hh +++ b/broker/core/inc/com/centreon/broker/stats/center.hh @@ -53,7 +53,6 @@ class center { int _json_stats_file_creation; center(); - ~center(); public: static center& instance(); diff --git a/broker/core/multiplexing/src/engine.cc b/broker/core/multiplexing/src/engine.cc index 7a195ad3b5b..9a0cd2309ef 100644 --- a/broker/core/multiplexing/src/engine.cc +++ b/broker/core/multiplexing/src/engine.cc @@ -27,7 +27,7 @@ #include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/misc.hh" #include "com/centreon/broker/multiplexing/muxer.hh" -#include "com/centreon/broker/pool.hh" +#include "com/centreon/common/pool.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::multiplexing; @@ -402,18 +402,20 @@ bool engine::_send_to_subscribers(send_to_mux_callback_type&& callback) { } else { std::shared_ptr mux_to_publish_in_asio = mux.lock(); if (mux_to_publish_in_asio) { - pool::io_context().post([kiew, mux_to_publish_in_asio, cb]() { - try { - mux_to_publish_in_asio->publish(*kiew); - } // pool threads protection - catch (const std::exception& ex) { - SPDLOG_LOGGER_ERROR(log_v2::core(), - "publish caught exception: {}", ex.what()); - } catch (...) { - SPDLOG_LOGGER_ERROR(log_v2::core(), - "publish caught unknown exception"); - } - }); + com::centreon::common::pool::io_context().post( + [kiew, mux_to_publish_in_asio, cb]() { + try { + mux_to_publish_in_asio->publish(*kiew); + } // pool threads protection + catch (const std::exception& ex) { + SPDLOG_LOGGER_ERROR(log_v2::core(), + "publish caught exception: {}", + ex.what()); + } catch (...) { + SPDLOG_LOGGER_ERROR(log_v2::core(), + "publish caught unknown exception"); + } + }); } } } diff --git a/broker/core/multiplexing/test/engine/start_stop.cc b/broker/core/multiplexing/test/engine/start_stop.cc index 41776f99be2..7d5bc2969c7 100644 --- a/broker/core/multiplexing/test/engine/start_stop.cc +++ b/broker/core/multiplexing/test/engine/start_stop.cc @@ -33,12 +33,10 @@ const std::string MSG2("foo bar baz"); const std::string MSG3("last message with qux"); const std::string MSG4("no this is the last message"); -extern std::shared_ptr g_io_context; class StartStop : public testing::Test { public: void SetUp() override { - g_io_context->restart(); config::applier::init(0, "test_broker", 0); } diff --git a/broker/core/multiplexing/test/muxer/read.cc b/broker/core/multiplexing/test/muxer/read.cc index 140b801d75c..3c54b2e4756 100644 --- a/broker/core/multiplexing/test/muxer/read.cc +++ b/broker/core/multiplexing/test/muxer/read.cc @@ -25,8 +25,6 @@ using namespace com::centreon::broker; -extern std::shared_ptr g_io_context; - class MultiplexingMuxerRead : public ::testing::Test { protected: std::shared_ptr _m; @@ -34,7 +32,6 @@ class MultiplexingMuxerRead : public ::testing::Test { public: void SetUp() override { try { - g_io_context->restart(); config::applier::init(0, "test_broker", 0); stats::center::load(); } catch (std::exception const& e) { diff --git a/broker/core/multiplexing/test/publisher/read.cc b/broker/core/multiplexing/test/publisher/read.cc index b9b4da85ab4..88c92e89615 100644 --- a/broker/core/multiplexing/test/publisher/read.cc +++ b/broker/core/multiplexing/test/publisher/read.cc @@ -23,12 +23,9 @@ using namespace com::centreon::broker; -extern std::shared_ptr g_io_context; - class PublisherRead : public testing::Test { public: void SetUp() override { - g_io_context->restart(); config::applier::init(0, "test_broker", 0); } diff --git a/broker/core/multiplexing/test/publisher/write.cc b/broker/core/multiplexing/test/publisher/write.cc index f6ca3ee52e1..26e68f90233 100644 --- a/broker/core/multiplexing/test/publisher/write.cc +++ b/broker/core/multiplexing/test/publisher/write.cc @@ -31,12 +31,9 @@ using namespace com::centreon::broker; const std::string MSG1("0123456789abcdef"); const std::string MSG2("foo bar baz qux"); -extern std::shared_ptr g_io_context; - class PublisherWrite : public testing::Test { public: void SetUp() override { - g_io_context->restart(); config::applier::init(0, "test_broker", 0); } diff --git a/broker/core/src/config/applier/init.cc b/broker/core/src/config/applier/init.cc index 2e99435cca1..ff6bdcaa6c9 100644 --- a/broker/core/src/config/applier/init.cc +++ b/broker/core/src/config/applier/init.cc @@ -1,20 +1,20 @@ /** -* Copyright 2011-2013, 2021-2022 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2013, 2021-2022 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include #include @@ -42,17 +42,14 @@ namespace asio = boost::asio; #include "com/centreon/broker/io/protocols.hh" #include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/multiplexing/engine.hh" -#include "com/centreon/broker/pool.hh" #include "com/centreon/broker/sql/mysql_manager.hh" #include "com/centreon/broker/time/timezone_manager.hh" +#include "com/centreon/common/pool.hh" using namespace com::centreon::broker; std::atomic config::applier::mode{not_started}; -extern std::shared_ptr g_io_context; -extern bool g_io_context_started; - /** * @brief Load necessary structures. It initializes exactly the same structures * as init(const config::state& conf) just with detailed parameters. @@ -64,8 +61,7 @@ void config::applier::init(size_t n_thread, const std::string&, size_t event_queues_total_size) { // Load singletons. - pool::load(g_io_context, n_thread); - g_io_context_started = true; + com::centreon::common::pool::set_pool_size(n_thread); stats::center::load(); mysql_manager::load(); config::applier::state::load(); @@ -96,7 +92,6 @@ void config::applier::deinit() { stats::center::unload(); file::disk_accessor::unload(); - pool::unload(); } /** diff --git a/broker/core/src/main.cc b/broker/core/src/main.cc index f2ac1ace17f..563d473ee9c 100644 --- a/broker/core/src/main.cc +++ b/broker/core/src/main.cc @@ -1,20 +1,20 @@ /** -* Copyright 2009-2013,2015,2018 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2009-2013,2015,2018 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include @@ -27,6 +27,7 @@ #include #include #include +#include #include #include @@ -53,7 +54,7 @@ namespace asio = boost::asio; #include "com/centreon/broker/config/state.hh" #include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/diagnostic.hh" -#include "com/centreon/broker/pool.hh" +#include "com/centreon/common/pool.hh" #include "com/centreon/exceptions/msg_fmt.hh" @@ -62,7 +63,6 @@ using namespace com::centreon::exceptions; std::shared_ptr g_io_context = std::make_shared(); -bool g_io_context_started = false; // Main config file. static std::vector gl_mainconfigfiles; @@ -159,6 +159,7 @@ int main(int argc, char* argv[]) { std::string default_listen_address{"localhost"}; log_v2::load(g_io_context); + com::centreon::common::pool::load(g_io_context, log_v2::core()); // Set configuration update handler. if (signal(SIGHUP, hup_handler) == SIG_ERR) { @@ -323,6 +324,7 @@ int main(int argc, char* argv[]) { log_v2::core()->info("main: process {} pid:{} end exit_code:{}", argv[0], getpid(), retval); - + g_io_context->stop(); + com::centreon::common::pool::unload(); return retval; } diff --git a/broker/core/src/pool.cc b/broker/core/src/pool.cc deleted file mode 100644 index 9b8bcf6e5ff..00000000000 --- a/broker/core/src/pool.cc +++ /dev/null @@ -1,201 +0,0 @@ -/** - * Copyright 2020-2022 Centreon - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * For more information : contact@centreon.com - */ -#include "com/centreon/broker/pool.hh" - -#include "com/centreon/broker/log_v2.hh" -#include "com/centreon/broker/stats/center.hh" - -using namespace com::centreon::broker; - -pool* pool::_instance{nullptr}; - -std::mutex pool::_init_m; - -/** - * @brief The way to access to the pool. - * - * @return a reference to the pool. - */ -pool& pool::instance() { - assert(pool::_instance); - return *_instance; -} - -void pool::load(const std::shared_ptr& io_context, - size_t size) { - std::lock_guard lck(_init_m); - if (_instance == nullptr) - _instance = new pool(io_context, size); - else - SPDLOG_LOGGER_ERROR(log_v2::core(), "pool already started."); -} - -void pool::unload() { - std::lock_guard lck(_init_m); - if (_instance) { - SPDLOG_LOGGER_INFO(log_v2::core(), "unload pool of {} threads", - _instance->_pool_size); - delete _instance; - _instance = nullptr; - } -} - -/** - * @brief A static method to access the IO context. - * - * @return the IO context. - */ -asio::io_context& pool::io_context() { - return *instance()._io_context; -} - -/** - * @brief A static method to access the IO context. - * - * @return the IO context. - */ -std::shared_ptr pool::io_context_ptr() { - return instance()._io_context; -} - -/** - * @brief Constructor. Private, it is called through the static - * instance() method. While this object gathers statistics for the statistics - * engine, it is not initialized as others. This is because, the stats engine - * is heavily dependent on the pool. So the stats engine needs the pool and the - * pool needs the stats engine. - * - * The idea here, is that when the pool is started, no stats are done. And when - * the stats::center is well started, it asks the pool to start its stats. - */ -pool::pool(const std::shared_ptr& io_context, size_t size) - : _stats(nullptr), - _pool_size{size == 0 ? std::max(std::thread::hardware_concurrency(), 3u) - : size}, - _io_context(io_context), - _worker{asio::make_work_guard(*_io_context)}, - _closed(true), - _timer(*_io_context), - _stats_running{false} { - std::lock_guard lock(_closed_m); - if (_closed) { - SPDLOG_LOGGER_INFO(log_v2::core(), - "Starting the TCP thread pool of {} threads", - _pool_size); - for (uint32_t i = 0; i < _pool_size; ++i) { - _pool.emplace_back([ctx = _io_context, i] { - try { - SPDLOG_LOGGER_INFO(log_v2::core(), "start of asio thread {:x}", - pthread_self()); - ctx->run(); - SPDLOG_LOGGER_INFO(log_v2::core(), "End of pool thread {}", i); - } catch (const std::exception& e) { - SPDLOG_LOGGER_CRITICAL(log_v2::core(), - "catch in io_context run: {} {} thread {:x}", - e.what(), typeid(e).name(), pthread_self()); - } - }); - char str[16]; - sprintf(str, "pool_thread%u", i); - pthread_setname_np(_pool[i].native_handle(), str); - } - _closed = false; - } -} - -/** - * @brief Start the stats of the pool. This method is called by the stats - * engine when it is ready. - * - * @param stats The pointer used by the pool to set its data in the stats - * engine. - */ -void pool::start_stats(ThreadPool* stats) { - _stats = stats; - /* The only time, we set a data directly to stats, this is because this - * method is called by the stats engine and the _check_latency has not - * started yet */ - _stats->set_size(_pool_size); - _stats_running = true; - _timer.expires_after(std::chrono::seconds(10)); - _timer.async_wait( - std::bind(&pool::_check_latency, this, std::placeholders::_1)); -} - -void pool::stop_stats() { - if (_stats_running) { - std::promise p; - std::future f(p.get_future()); - asio::post(_timer.get_executor(), [this, &p] { - _stats_running = false; - _timer.cancel(); - p.set_value(true); - }); - f.get(); - } -} - -/** - * @brief Destructor - */ -pool::~pool() noexcept { - _stop(); -} - -/** - * @brief Stop the thread pool. - */ -void pool::_stop() { - SPDLOG_LOGGER_DEBUG(log_v2::core(), "Stopping the thread pool"); - std::lock_guard lock(_closed_m); - if (!_closed) { - _closed = true; - _worker.reset(); - for (auto& t : _pool) - if (t.joinable()) - t.join(); - } - SPDLOG_LOGGER_DEBUG(log_v2::core(), "No remaining thread in the pool"); -} - -/** - * @brief The function whose role is to compute the latency. It makes the - * computation every 10s. - * - */ -void pool::_check_latency(const boost::system::error_code& ec) { - if (ec) - SPDLOG_LOGGER_INFO(log_v2::core(), - "pool: the latency check encountered an error: {}", - ec.message()); - else { - auto start = std::chrono::system_clock::now(); - asio::post(*_io_context, [start, this] { - auto end = std::chrono::system_clock::now(); - auto duration = std::chrono::duration(end - start); - float d = duration.count() / 1000.0f; - stats::center::instance().update(&ThreadPool::set_latency, _stats, d); - SPDLOG_LOGGER_TRACE(log_v2::core(), "Thread pool latency {:.5f}s", d); - }); - if (_stats_running) { - _timer.expires_after(std::chrono::seconds(10)); - _timer.async_wait( - [this](const boost::system::error_code& ec) { _check_latency(ec); }); - } - } -} diff --git a/broker/core/src/processing/feeder.cc b/broker/core/src/processing/feeder.cc index 6488ea7e8da..0f338199d30 100644 --- a/broker/core/src/processing/feeder.cc +++ b/broker/core/src/processing/feeder.cc @@ -27,7 +27,7 @@ #include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/misc.hh" #include "com/centreon/broker/multiplexing/muxer.hh" -#include "com/centreon/broker/pool.hh" +#include "com/centreon/common/pool.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon::exceptions; @@ -83,9 +83,9 @@ feeder::feeder(const std::string& name, std::move(read_filters), std::move(write_filters), false)), - _stat_timer(pool::io_context()), - _read_from_stream_timer(pool::io_context()), - _io_context(pool::io_context_ptr()) { + _stat_timer(com::centreon::common::pool::io_context()), + _read_from_stream_timer(com::centreon::common::pool::io_context()), + _io_context(com::centreon::common::pool::io_context_ptr()) { DEBUG(fmt::format("CONSTRUCTOR feeder {:p} {} - muxer: {:p}", static_cast(this), name, static_cast(_muxer.get()))); diff --git a/broker/core/src/stats/center.cc b/broker/core/src/stats/center.cc index d16167d59be..4723a6081ea 100644 --- a/broker/core/src/stats/center.cc +++ b/broker/core/src/stats/center.cc @@ -1,20 +1,20 @@ /** -* Copyright 2020-2022 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2020-2022 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/stats/center.hh" @@ -25,8 +25,8 @@ #include "com/centreon/broker/config/applier/state.hh" #include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/filesystem.hh" -#include "com/centreon/broker/pool.hh" #include "com/centreon/broker/version.hh" +#include "com/centreon/common/pool.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::stats; @@ -71,16 +71,6 @@ center::center() { *m->mutable_state() = "loaded"; } } - - /*Start the thread pool */ - pool::instance().start_stats(_stats.mutable_pool_stats()); -} - -/** - * @brief The destructor. - */ -center::~center() { - pool::instance().stop_stats(); } /** diff --git a/broker/core/src/stats/helper.cc b/broker/core/src/stats/helper.cc index 5dbf5014e82..2730adf4647 100644 --- a/broker/core/src/stats/helper.cc +++ b/broker/core/src/stats/helper.cc @@ -1,20 +1,20 @@ /** -* Copyright 2020-2021 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2020-2021 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/stats/helper.hh" @@ -23,9 +23,9 @@ #include "com/centreon/broker/config/endpoint.hh" #include "com/centreon/broker/misc/filesystem.hh" #include "com/centreon/broker/multiplexing/muxer.hh" -#include "com/centreon/broker/pool.hh" #include "com/centreon/broker/processing/endpoint.hh" #include "com/centreon/broker/sql/mysql_manager.hh" +#include "com/centreon/common/pool.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::stats; @@ -46,7 +46,8 @@ void com::centreon::broker::stats::get_generic_stats( BOOST_ASIO_VERSION / 100 % 1000, BOOST_ASIO_VERSION % 100); nlohmann::json pool; - pool["size"] = static_cast(pool::instance().get_pool_size()); + pool["size"] = static_cast( + com::centreon::common::pool::instance().get_pool_size()); pool["latency"] = ""; object["thread_pool"] = pool; } diff --git a/broker/core/test/bbdo/output.cc b/broker/core/test/bbdo/output.cc index 3238f1c9afc..c05251f6062 100644 --- a/broker/core/test/bbdo/output.cc +++ b/broker/core/test/bbdo/output.cc @@ -34,7 +34,6 @@ using namespace com::centreon::broker; using namespace com::centreon::broker::misc; -extern std::shared_ptr g_io_context; class into_memory : public io::stream { public: @@ -71,7 +70,6 @@ class OutputTest : public ::testing::Test { public: void SetUp() override { io::data::broker_id = 0; - g_io_context->restart(); try { config::applier::init(0, "broker_test", 0); } catch (std::exception const& e) { diff --git a/broker/core/test/compression/stream/read.cc b/broker/core/test/compression/stream/read.cc index 10cd25b4fef..4481aa6f53a 100644 --- a/broker/core/test/compression/stream/read.cc +++ b/broker/core/test/compression/stream/read.cc @@ -26,12 +26,9 @@ using namespace com::centreon::broker; -extern std::shared_ptr g_io_context; - class CompressionStreamRead : public ::testing::Test { public: void SetUp() override { - g_io_context->restart(); try { config::applier::init(0, "test_broker", 0); } catch (const std::exception& e) { diff --git a/broker/core/test/compression/stream/write.cc b/broker/core/test/compression/stream/write.cc index 40f4a9bbc64..ffa2624c1e8 100644 --- a/broker/core/test/compression/stream/write.cc +++ b/broker/core/test/compression/stream/write.cc @@ -27,12 +27,9 @@ using namespace com::centreon::broker; using namespace com::centreon::exceptions; -extern std::shared_ptr g_io_context; - class CompressionStreamWrite : public ::testing::Test { public: void SetUp() override { - g_io_context->restart(); try { config::applier::init(0, "test_broker", 0); } catch (const std::exception& e) { diff --git a/broker/core/test/config/init.cc b/broker/core/test/config/init.cc index a8dab72b0df..f6cac87c8d2 100644 --- a/broker/core/test/config/init.cc +++ b/broker/core/test/config/init.cc @@ -21,8 +21,6 @@ using namespace com::centreon::broker; -extern std::shared_ptr g_io_context; - /** * Check that the logger configuration class can be copied properly. * @@ -30,7 +28,6 @@ extern std::shared_ptr g_io_context; */ TEST(init, init) { // First object. - g_io_context->restart(); config::applier::init(0, "test", 0); ASSERT_NO_THROW(config::applier::deinit()); } diff --git a/broker/core/test/main.cc b/broker/core/test/main.cc index 9f1b996d37a..4b016a4ab81 100644 --- a/broker/core/test/main.cc +++ b/broker/core/test/main.cc @@ -21,10 +21,10 @@ #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/io/protocols.hh" #include "com/centreon/broker/log_v2.hh" +#include "com/centreon/common/pool.hh" std::shared_ptr g_io_context = std::make_shared(); -bool g_io_context_started = false; class CentreonBrokerEnvironment : public testing::Environment { public: @@ -55,8 +55,14 @@ int main(int argc, char* argv[]) { testing::AddGlobalTestEnvironment(new CentreonBrokerEnvironment()); com::centreon::broker::log_v2::load(g_io_context); + com::centreon::common::pool::load(g_io_context, + com::centreon::broker::log_v2::core()); + com::centreon::common::pool::set_pool_size(0); + // Run all tests. int ret = RUN_ALL_TESTS(); spdlog::shutdown(); + g_io_context->stop(); + com::centreon::common::pool::unload(); return ret; } diff --git a/broker/core/test/misc/perfdata.cc b/broker/core/test/misc/perfdata.cc index 2ec05aca785..da54dd001ea 100644 --- a/broker/core/test/misc/perfdata.cc +++ b/broker/core/test/misc/perfdata.cc @@ -27,8 +27,6 @@ using namespace com::centreon::broker; -extern std::shared_ptr g_io_context; - /** * Check that the perfdata assignment operator works properly. */ @@ -197,7 +195,6 @@ TEST(MiscPerfdata, DefaultCtor) { class MiscParserParsePerfdata : public testing::Test { public: void SetUp() override { - g_io_context->restart(); config::applier::init(0, "test_broker", 0); } void TearDown() override { config::applier::deinit(); }; diff --git a/broker/core/test/modules/module.cc b/broker/core/test/modules/module.cc index 3fcd61ec720..c095b06524a 100644 --- a/broker/core/test/modules/module.cc +++ b/broker/core/test/modules/module.cc @@ -24,12 +24,9 @@ using namespace com::centreon::broker; -extern std::shared_ptr g_io_context; - class Modules : public testing::Test { public: void SetUp() override { - g_io_context->restart(); config::applier::init(0, "test_broker", 0); } diff --git a/broker/core/test/mysql/mysql.cc b/broker/core/test/mysql/mysql.cc index e5341da53b5..879d06f71ed 100644 --- a/broker/core/test/mysql/mysql.cc +++ b/broker/core/test/mysql/mysql.cc @@ -49,12 +49,9 @@ using msg_fmt = com::centreon::exceptions::msg_fmt; using namespace com::centreon::broker; using namespace com::centreon::broker::database; -extern std::shared_ptr g_io_context; - class DatabaseStorageTest : public ::testing::Test { public: void SetUp() override { - g_io_context->restart(); try { config::applier::init(0, "test_broker", 0); } catch (std::exception const& e) { diff --git a/broker/core/test/processing/acceptor.cc b/broker/core/test/processing/acceptor.cc index 1cf43b216df..7b54a84f8aa 100644 --- a/broker/core/test/processing/acceptor.cc +++ b/broker/core/test/processing/acceptor.cc @@ -28,12 +28,9 @@ using namespace com::centreon::broker; using namespace com::centreon::broker::processing; -extern std::shared_ptr g_io_context; - class ProcessingTest : public ::testing::Test { public: void SetUp() override { - g_io_context->restart(); try { config::applier::init(0, "test_broker", 0); } catch (std::exception const& e) { diff --git a/broker/core/test/processing/feeder.cc b/broker/core/test/processing/feeder.cc index acddf538967..73c3562b43f 100644 --- a/broker/core/test/processing/feeder.cc +++ b/broker/core/test/processing/feeder.cc @@ -25,14 +25,11 @@ #include "com/centreon/broker/io/protocols.hh" #include "com/centreon/broker/multiplexing/engine.hh" #include "com/centreon/broker/multiplexing/muxer_filter.hh" -#include "com/centreon/broker/pool.hh" #include "com/centreon/broker/stats/center.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::processing; -extern std::shared_ptr g_io_context; - class TestStream : public io::stream { public: TestStream() : io::stream("TestStream") {} @@ -48,8 +45,6 @@ class TestFeeder : public ::testing::Test { public: void SetUp() override { - g_io_context->restart(); - pool::load(g_io_context, 0); stats::center::load(); config::applier::state::load(); file::disk_accessor::load(10000); @@ -74,7 +69,6 @@ class TestFeeder : public ::testing::Test { io::protocols::unload(); stats::center::unload(); file::disk_accessor::unload(); - pool::unload(); } }; diff --git a/broker/core/test/rpc/brokerrpc.cc b/broker/core/test/rpc/brokerrpc.cc index 4ad26b197e4..f7af312c30e 100644 --- a/broker/core/test/rpc/brokerrpc.cc +++ b/broker/core/test/rpc/brokerrpc.cc @@ -18,7 +18,6 @@ */ #include "com/centreon/broker/brokerrpc.hh" -#include "com/centreon/broker/pool.hh" #include "com/centreon/broker/stats/center.hh" #include @@ -33,13 +32,9 @@ using namespace com::centreon; using namespace com::centreon::broker; -extern std::shared_ptr g_io_context; - class BrokerRpc : public ::testing::Test { public: void SetUp() override { - g_io_context->restart(); - pool::load(g_io_context, 0); stats::center::load(); io::protocols::load(); io::events::load(); @@ -49,7 +44,6 @@ class BrokerRpc : public ::testing::Test { io::events::unload(); io::protocols::unload(); stats::center::unload(); - pool::pool::unload(); } std::list execute(const std::string& command) { diff --git a/broker/grpc/src/stream.cc b/broker/grpc/src/stream.cc index dc16361e3ee..582cafb2778 100644 --- a/broker/grpc/src/stream.cc +++ b/broker/grpc/src/stream.cc @@ -24,7 +24,7 @@ #include "com/centreon/broker/exceptions/connection_closed.hh" #include "com/centreon/broker/grpc/grpc_bridge.hh" #include "com/centreon/broker/misc/string.hh" -#include "com/centreon/broker/pool.hh" +#include "com/centreon/common/pool.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon::broker::grpc; @@ -374,13 +374,14 @@ void stream::OnDone() { * of the current thread witch go to a EDEADLOCK error and call grpc::Crash. * So we uses asio thread to do the job */ - pool::io_context().post([me = std::enable_shared_from_this< - stream>::shared_from_this()]() { - std::lock_guard l(_instances_m); - SPDLOG_LOGGER_DEBUG(log_v2::grpc(), "{:p} server::OnDone()", - static_cast(me.get())); - _instances.erase(std::static_pointer_cast>(me)); - }); + common::pool::io_context().post( + [me = std::enable_shared_from_this< + stream>::shared_from_this()]() { + std::lock_guard l(_instances_m); + SPDLOG_LOGGER_DEBUG(log_v2::grpc(), "{:p} server::OnDone()", + static_cast(me.get())); + _instances.erase(std::static_pointer_cast>(me)); + }); } /** @@ -398,15 +399,16 @@ void stream::OnDone(const ::grpc::Status& status) { * pthread_join of the current thread witch go to a EDEADLOCK error and call * grpc::Crash. So we uses asio thread to do the job */ - pool::io_context().post([me = std::enable_shared_from_this< - stream>::shared_from_this(), - status]() { - std::lock_guard l(_instances_m); - SPDLOG_LOGGER_DEBUG(log_v2::grpc(), "{:p} client::OnDone({}) {}", - static_cast(me.get()), status.error_message(), - status.error_details()); - _instances.erase(std::static_pointer_cast>(me)); - }); + common::pool::io_context().post( + [me = std::enable_shared_from_this< + stream>::shared_from_this(), + status]() { + std::lock_guard l(_instances_m); + SPDLOG_LOGGER_DEBUG(log_v2::grpc(), "{:p} client::OnDone({}) {}", + static_cast(me.get()), + status.error_message(), status.error_details()); + _instances.erase(std::static_pointer_cast>(me)); + }); } /** diff --git a/broker/grpc/test/acceptor.cc b/broker/grpc/test/acceptor.cc index ccc1199edce..15c71d92ae9 100644 --- a/broker/grpc/test/acceptor.cc +++ b/broker/grpc/test/acceptor.cc @@ -38,18 +38,7 @@ using namespace com::centreon::broker; using namespace com::centreon::broker::grpc; using namespace com::centreon::exceptions; -extern std::shared_ptr g_io_context; - -class GrpcTlsTest : public ::testing::Test { - public: - void SetUp() override { - pool::load(g_io_context, 1); - log_v2::grpc()->set_level(spdlog::level::trace); - io::protocols::load(); - io::events::load(); - } - void TearDown() override { pool::unload(); } -}; +class GrpcTlsTest : public ::testing::Test {}; static auto read_file = [](const std::string& path) { std::ifstream file(path); diff --git a/broker/grpc/test/grpc_test_include.hh b/broker/grpc/test/grpc_test_include.hh index 843a0166a49..1f22ba3f1d3 100644 --- a/broker/grpc/test/grpc_test_include.hh +++ b/broker/grpc/test/grpc_test_include.hh @@ -49,7 +49,7 @@ using unique_lock = std::unique_lock; #include "com/centreon/broker/grpc/connector.hh" #include "com/centreon/broker/grpc/stream.hh" #include "com/centreon/broker/io/raw.hh" -#include "com/centreon/broker/pool.hh" +#include "com/centreon/common/pool.hh" #include "com/centreon/exceptions/msg_fmt.hh" #endif // CCB_GRPC_TEST__INCLUDE_HH diff --git a/broker/grpc/test/stream_test.cc b/broker/grpc/test/stream_test.cc index 7568acf9183..476d1884c00 100644 --- a/broker/grpc/test/stream_test.cc +++ b/broker/grpc/test/stream_test.cc @@ -28,8 +28,6 @@ using namespace com::centreon::broker; using namespace com::centreon::exceptions; -extern std::shared_ptr g_io_context; - com::centreon::broker::grpc::grpc_config::pointer conf( std::make_shared( "127.0.0.1:4444", @@ -80,8 +78,6 @@ class grpc_test_server : public ::testing::TestWithParam { log_v2::grpc()->set_level(spdlog::level::trace); s = std::make_unique(conf); std::this_thread::sleep_for(std::chrono::milliseconds(50)); - g_io_context->restart(); - com::centreon::broker::pool::load(g_io_context, 1); io::protocols::load(); io::events::load(); } @@ -181,7 +177,6 @@ class grpc_comm_failure : public ::testing::TestWithParam { s = std::make_unique(conf_relay_out); relay = std::make_unique( "127.0.0.1", relay_listen_port, "127.0.0.1", server_listen_port); - com::centreon::broker::pool::load(std::make_shared(), 1); } static void TearDownTestSuite() { s.reset(); @@ -399,7 +394,6 @@ class grpc_test_server_crypted : public ::testing::TestWithParam { // log_v2::grpc()->set_level(spdlog::level::trace); s = std::make_unique( conf_crypted_server1234); - com::centreon::broker::pool::load(std::make_shared(), 1); } static void TearDownTestSuite() { s.reset(); }; diff --git a/broker/http_client/test/http_client_test.cc b/broker/http_client/test/http_client_test.cc index 1d4ead50c9f..4c04506558d 100644 --- a/broker/http_client/test/http_client_test.cc +++ b/broker/http_client/test/http_client_test.cc @@ -26,8 +26,8 @@ #include #include "com/centreon/broker/log_v2.hh" -#include "com/centreon/broker/pool.hh" #include "com/centreon/common/defer.hh" +#include "com/centreon/common/pool.hh" using system_clock = std::chrono::system_clock; using time_point = system_clock::time_point; @@ -48,9 +48,7 @@ class http_client_test : public ::testing::Test { public: static void SetUpTestSuite() { srand(time(nullptr)); - g_io_context->restart(); - pool::load(g_io_context, 1); - log_v2::tcp()->set_level(spdlog::level::info); + log_v2::tcp()->set_level(spdlog::level::debug); }; }; diff --git a/broker/http_tsdb/test/stream_test.cc b/broker/http_tsdb/test/stream_test.cc index 8ef245e4b7a..808650a10d1 100644 --- a/broker/http_tsdb/test/stream_test.cc +++ b/broker/http_tsdb/test/stream_test.cc @@ -28,11 +28,10 @@ using system_clock = std::chrono::system_clock; using time_point = system_clock::time_point; using duration = system_clock::duration; - #include "com/centreon/broker/file/disk_accessor.hh" #include "com/centreon/broker/http_tsdb/stream.hh" #include "com/centreon/broker/log_v2.hh" -#include "com/centreon/broker/pool.hh" +#include "com/centreon/common/pool.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon::exceptions; @@ -48,7 +47,6 @@ class http_tsdb_stream_test : public ::testing::Test { log_v2::tcp()->set_level(spdlog::level::info); file::disk_accessor::load(1000); - pool::load(g_io_context, 1); } }; diff --git a/broker/lua/test/lua.cc b/broker/lua/test/lua.cc index bf64266749d..d101af1d8c8 100644 --- a/broker/lua/test/lua.cc +++ b/broker/lua/test/lua.cc @@ -45,12 +45,9 @@ using namespace com::centreon::broker::lua; #define FILE3 CENTREON_BROKER_LUA_SCRIPT_PATH "/test3.lua" #define FILE4 CENTREON_BROKER_LUA_SCRIPT_PATH "/socket.lua" -extern std::shared_ptr g_io_context; - class LuaTest : public ::testing::Test { public: void SetUp() override { - g_io_context->restart(); try { config::applier::init(0, "test_broker", 0); } catch (std::exception const& e) { diff --git a/broker/rrd/test/rrd.cc b/broker/rrd/test/rrd.cc index 8b1ab1dc293..f9dd96646bf 100644 --- a/broker/rrd/test/rrd.cc +++ b/broker/rrd/test/rrd.cc @@ -29,12 +29,9 @@ using namespace com::centreon::broker; -extern std::shared_ptr g_io_context; - class Rrd : public ::testing::Test { public: void SetUp() override { - g_io_context->restart(); try { config::applier::init(0, "test_broker", 0); } catch (std::exception const& e) { diff --git a/broker/simu/test/simu.cc b/broker/simu/test/simu.cc index b75607098b9..79fe0e17539 100644 --- a/broker/simu/test/simu.cc +++ b/broker/simu/test/simu.cc @@ -30,12 +30,9 @@ using namespace com::centreon::broker; using namespace com::centreon::broker::misc; using namespace com::centreon::broker::simu; -extern std::shared_ptr g_io_context; - class SimuGenericTest : public ::testing::Test { public: void SetUp() override { - g_io_context->restart(); try { config::applier::init(0, "test_broker", 0); } catch (std::exception const& e) { diff --git a/broker/stats/test/stats.cc b/broker/stats/test/stats.cc index 68e3d2673e8..3d033e0ee76 100644 --- a/broker/stats/test/stats.cc +++ b/broker/stats/test/stats.cc @@ -33,22 +33,19 @@ #include "com/centreon/broker/misc/misc.hh" #include "com/centreon/broker/misc/string.hh" #include "com/centreon/broker/multiplexing/engine.hh" -#include "com/centreon/broker/pool.hh" #include "com/centreon/broker/sql/mysql_manager.hh" #include "com/centreon/broker/stats/builder.hh" #include "com/centreon/broker/stats/center.hh" +#include "com/centreon/common/pool.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; -extern std::shared_ptr g_io_context; class StatsTest : public ::testing::Test { public: void SetUp() override { - g_io_context->restart(); - com::centreon::broker::pool::load(g_io_context, 0); stats::center::load(); mysql_manager::load(); config::applier::state::load(); @@ -69,7 +66,6 @@ class StatsTest : public ::testing::Test { mysql_manager::unload(); file::disk_accessor::unload(); stats::center::unload(); - pool::unload(); } }; diff --git a/broker/stats_exporter/src/exporter.cc b/broker/stats_exporter/src/exporter.cc index 36ae74d4fbc..1b3e4b1862d 100644 --- a/broker/stats_exporter/src/exporter.cc +++ b/broker/stats_exporter/src/exporter.cc @@ -1,27 +1,27 @@ /** -* Copyright 2023 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2023 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/stats_exporter/exporter.hh" #include "com/centreon/broker/config/endpoint.hh" #include "com/centreon/broker/log_v2.hh" -#include "com/centreon/broker/pool.hh" #include "com/centreon/broker/sql/mysql_manager.hh" #include "com/centreon/broker/stats/center.hh" +#include "com/centreon/common/pool.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::stats_exporter; @@ -30,7 +30,8 @@ namespace metric_sdk = opentelemetry::sdk::metrics; /** * @brief Default constructor. */ -exporter::exporter() : _connections_watcher{pool::io_context()} {} +exporter::exporter() + : _connections_watcher{com::centreon::common::pool::io_context()} {} /** * @brief Initialize the metrics to export. diff --git a/broker/storage/inc/com/centreon/broker/storage/rebuilder.hh b/broker/storage/inc/com/centreon/broker/storage/rebuilder.hh index 0ffbd81faa0..5a54d160fe9 100644 --- a/broker/storage/inc/com/centreon/broker/storage/rebuilder.hh +++ b/broker/storage/inc/com/centreon/broker/storage/rebuilder.hh @@ -19,9 +19,9 @@ #ifndef CCB_STORAGE_REBUILDER_HH #define CCB_STORAGE_REBUILDER_HH -#include "com/centreon/broker/pool.hh" #include "com/centreon/broker/sql/database_config.hh" #include "com/centreon/broker/sql/mysql.hh" +#include "com/centreon/common/pool.hh" namespace com::centreon::broker { @@ -69,6 +69,6 @@ class rebuilder { }; } // namespace storage -} +} // namespace com::centreon::broker #endif // !CCB_STORAGE_REBUILDER_HH diff --git a/broker/storage/src/conflict_manager.cc b/broker/storage/src/conflict_manager.cc index 6c00fb5b53e..82a5f7dca58 100644 --- a/broker/storage/src/conflict_manager.cc +++ b/broker/storage/src/conflict_manager.cc @@ -99,7 +99,7 @@ conflict_manager::conflict_manager(database_config const& dbcfg, _instance_timeout{instance_timeout}, _stats{stats::center::instance().register_conflict_manager()}, _ref_count{0}, - _group_clean_timer{pool::io_context()}, + _group_clean_timer{com::centreon::common::pool::io_context()}, _oldest_timestamp{std::numeric_limits::max()} { log_v2::sql()->debug("conflict_manager: class instanciation"); stats::center::instance().update(&ConflictManagerStats::set_loop_timeout, @@ -927,7 +927,8 @@ int32_t conflict_manager::unload(stream_type type) { * @param d The BBDO message with all the metrics/indexes to remove. */ void conflict_manager::remove_graphs(const std::shared_ptr& d) { - asio::post(pool::instance().io_context(), [this, data = d] { + asio::post(com::centreon::common::pool::instance().io_context(), [this, + data = d] { mysql ms(_mysql.get_config()); const bbdo::pb_remove_graphs& ids = *static_cast(data.get()); diff --git a/broker/storage/src/rebuilder.cc b/broker/storage/src/rebuilder.cc index 4842288d174..946f80fdae2 100644 --- a/broker/storage/src/rebuilder.cc +++ b/broker/storage/src/rebuilder.cc @@ -1,20 +1,20 @@ /** -* Copyright 2012-2015,2017,2020-2021 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2012-2015,2017,2020-2021 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/storage/rebuilder.hh" @@ -56,7 +56,7 @@ rebuilder::rebuilder(const database_config& db_cfg, * @param d The BBDO message with all the metric ids to rebuild. */ void rebuilder::rebuild_graphs(const std::shared_ptr& d) { - asio::post(pool::io_context(), [this, data = d] { + asio::post(com::centreon::common::pool::io_context(), [this, data = d] { const bbdo::pb_rebuild_graphs& ids = *static_cast(data.get()); diff --git a/broker/storage/test/conflict_manager.cc b/broker/storage/test/conflict_manager.cc index ee01b733263..90837f3a95a 100644 --- a/broker/storage/test/conflict_manager.cc +++ b/broker/storage/test/conflict_manager.cc @@ -34,12 +34,9 @@ using namespace com::centreon::broker; using namespace com::centreon::broker::sql; -extern std::shared_ptr g_io_context; - class ConflictManagerTest : public ::testing::Test { public: void SetUp() override { - g_io_context->restart(); try { config::applier::init(0, "test_broker", 0); } catch (std::exception const& e) { diff --git a/broker/storage/test/perfdata.cc b/broker/storage/test/perfdata.cc index 88708574b66..53da8f7d50e 100644 --- a/broker/storage/test/perfdata.cc +++ b/broker/storage/test/perfdata.cc @@ -29,8 +29,6 @@ using namespace com::centreon::broker; -extern std::shared_ptr g_io_context; - /** * Check that the perfdata assignment operator works properly. */ @@ -199,7 +197,6 @@ TEST(StoragePerfdata, DefaultCtor) { class StorageParserParsePerfdata : public testing::Test { public: void SetUp() override { - g_io_context->restart(); config::applier::init(0, "test_broker", 0); } void TearDown() override { config::applier::deinit(); }; diff --git a/broker/storage/test/status-entry.cc b/broker/storage/test/status-entry.cc index 6a6d406dcc0..f37feef22ad 100644 --- a/broker/storage/test/status-entry.cc +++ b/broker/storage/test/status-entry.cc @@ -37,8 +37,6 @@ using namespace com::centreon::broker; using namespace com::centreon::broker::misc; -extern std::shared_ptr g_io_context; - class into_memory : public io::stream { std::vector _memory; @@ -72,7 +70,6 @@ class StatusEntryTest : public ::testing::Test { public: void SetUp() override { io::data::broker_id = 0; - g_io_context->restart(); try { config::applier::init(0, "test_broker", 0); } catch (std::exception const& e) { diff --git a/broker/tcp/inc/com/centreon/broker/tcp/tcp_async.hh b/broker/tcp/inc/com/centreon/broker/tcp/tcp_async.hh index 6205deed448..290227057ed 100644 --- a/broker/tcp/inc/com/centreon/broker/tcp/tcp_async.hh +++ b/broker/tcp/inc/com/centreon/broker/tcp/tcp_async.hh @@ -18,9 +18,9 @@ #ifndef CENTREON_BROKER_TCP_INC_COM_CENTREON_BROKER_TCP_TCP_ASYNC_HH_ #define CENTREON_BROKER_TCP_INC_COM_CENTREON_BROKER_TCP_TCP_ASYNC_HH_ -#include "com/centreon/broker/pool.hh" #include "com/centreon/broker/tcp/tcp_config.hh" #include "com/centreon/broker/tcp/tcp_connection.hh" +#include "com/centreon/common/pool.hh" namespace com::centreon::broker { namespace tcp { @@ -108,5 +108,5 @@ class tcp_async : public std::enable_shared_from_this { }; } // namespace tcp -} +} // namespace com::centreon::broker #endif // CENTREON_BROKER_TCP_INC_COM_CENTREON_BROKER_TCP_TCP_ASYNC_HH_ diff --git a/broker/tcp/src/stream.cc b/broker/tcp/src/stream.cc index 1a437dc3f3d..5527fb67d5c 100644 --- a/broker/tcp/src/stream.cc +++ b/broker/tcp/src/stream.cc @@ -26,9 +26,9 @@ #include "com/centreon/broker/io/raw.hh" #include "com/centreon/broker/log_v2.hh" -#include "com/centreon/broker/pool.hh" #include "com/centreon/broker/tcp/acceptor.hh" #include "com/centreon/broker/tcp/tcp_async.hh" +#include "com/centreon/common/pool.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon::broker; @@ -57,8 +57,8 @@ stream::stream(const tcp_config::pointer& conf) _conf->get_port()); log_v2::tcp()->info( "{} TCP streams are configured on a thread pool of {} threads", - static_cast(_total_tcp_count), - pool::instance().get_pool_size()); + static_cast(_total_tcp_count), + com::centreon::common::pool::instance().get_pool_size()); } /** @@ -78,7 +78,7 @@ stream::stream(const tcp_connection::pointer& conn, log_v2::tcp()->info( "{} TCP streams are configured on a thread pool of {} threads", static_cast(_total_tcp_count), - pool::instance().get_pool_size()); + com::centreon::common::pool::instance().get_pool_size()); } /** @@ -90,7 +90,7 @@ stream::~stream() noexcept { "TCP stream destroyed. Still {} configured on a thread pool of {} " "threads", static_cast(_total_tcp_count), - pool::instance().get_pool_size()); + com::centreon::common::pool::instance().get_pool_size()); log_v2::tcp()->trace("stream closed"); if (_connection->socket().is_open()) _connection->close(); diff --git a/broker/tcp/src/tcp_async.cc b/broker/tcp/src/tcp_async.cc index 47650dd00bc..7b9093a7be3 100644 --- a/broker/tcp/src/tcp_async.cc +++ b/broker/tcp/src/tcp_async.cc @@ -1,24 +1,24 @@ /** -* Copyright 2020-2021 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2020-2021 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/tcp/tcp_async.hh" #include "com/centreon/broker/log_v2.hh" -#include "com/centreon/broker/pool.hh" +#include "com/centreon/common/pool.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon::exceptions; @@ -166,7 +166,7 @@ std::shared_ptr tcp_async::create_acceptor( else { asio::ip::tcp::resolver::query query(conf->get_host(), std::to_string(conf->get_port())); - asio::ip::tcp::resolver resolver(pool::io_context()); + asio::ip::tcp::resolver resolver(com::centreon::common::pool::io_context()); boost::system::error_code ec; asio::ip::tcp::resolver::iterator it = resolver.resolve(query, ec), end; if (ec) { @@ -184,8 +184,8 @@ std::shared_ptr tcp_async::create_acceptor( } } } - auto retval{std::make_shared(pool::io_context(), - listen_endpoint)}; + auto retval{std::make_shared( + com::centreon::common::pool::io_context(), listen_endpoint)}; asio::ip::tcp::acceptor::reuse_address option(true); retval->set_option(option); @@ -238,8 +238,8 @@ void tcp_async::start_acceptor( log_v2::tcp()->trace("Start acceptor"); std::lock_guard l(_acceptor_available_con_m); if (!_timer) - _timer = - std::make_unique(pool::instance().io_context()); + _timer = std::make_unique( + com::centreon::common::pool::instance().io_context()); if (!_clear_available_con_running) _clear_available_con_running = true; @@ -251,8 +251,8 @@ void tcp_async::start_acceptor( me->_clear_available_con(err); }); - tcp_connection::pointer new_connection = - std::make_shared(pool::io_context()); + tcp_connection::pointer new_connection = std::make_shared( + com::centreon::common::pool::io_context()); log_v2::tcp()->debug("Waiting for a connection"); acceptor->async_accept(new_connection->socket(), @@ -328,10 +328,11 @@ tcp_connection::pointer tcp_async::create_connection( log_v2::tcp()->trace("create connection to host {}:{}", conf->get_host(), conf->get_port()); tcp_connection::pointer conn = std::make_shared( - pool::io_context(), conf->get_host(), conf->get_port()); + com::centreon::common::pool::io_context(), conf->get_host(), + conf->get_port()); asio::ip::tcp::socket& sock = conn->socket(); - asio::ip::tcp::resolver resolver(pool::io_context()); + asio::ip::tcp::resolver resolver(com::centreon::common::pool::io_context()); asio::ip::tcp::resolver::query query(conf->get_host(), std::to_string(conf->get_port())); asio::ip::tcp::resolver::iterator it = resolver.resolve(query), end; diff --git a/broker/tcp/test/acceptor.cc b/broker/tcp/test/acceptor.cc index 1c586eb4441..06a587b1f85 100644 --- a/broker/tcp/test/acceptor.cc +++ b/broker/tcp/test/acceptor.cc @@ -26,15 +26,14 @@ #include "com/centreon/broker/io/raw.hh" #include "com/centreon/broker/log_v2.hh" -#include "com/centreon/broker/pool.hh" #include "com/centreon/broker/tcp/connector.hh" #include "com/centreon/broker/tcp/tcp_async.hh" +#include "com/centreon/common/pool.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon::broker; using namespace com::centreon::exceptions; -extern std::shared_ptr g_io_context; const static std::string test_addr("127.0.0.1"); constexpr static uint16_t test_port(4444); @@ -46,9 +45,7 @@ static tcp::tcp_config::pointer test_conf2( class TcpAcceptor : public ::testing::Test { public: void SetUp() override { - log_v2::tcp()->set_level(spdlog::level::info); - g_io_context->restart(); - pool::load(g_io_context, 0); + log_v2::tcp()->set_level(spdlog::level::debug); tcp::tcp_async::load(); } @@ -56,7 +53,6 @@ class TcpAcceptor : public ::testing::Test { log_v2::tcp()->info("TCP TearDown"); tcp::tcp_async::instance().stop_timer(); tcp::tcp_async::unload(); - pool::unload(); } }; diff --git a/broker/tcp/test/connector.cc b/broker/tcp/test/connector.cc index e431c60943f..72bc3d6ee6d 100644 --- a/broker/tcp/test/connector.cc +++ b/broker/tcp/test/connector.cc @@ -23,13 +23,11 @@ #include "../../core/test/test_server.hh" #include "com/centreon/broker/io/raw.hh" -#include "com/centreon/broker/pool.hh" #include "com/centreon/broker/tcp/tcp_async.hh" +#include "com/centreon/common/pool.hh" using namespace com::centreon::broker; -extern std::shared_ptr g_io_context; - constexpr static char test_addr[] = "127.0.0.1"; constexpr static uint16_t test_port(4242); @@ -39,8 +37,6 @@ static tcp::tcp_config::pointer test_conf( class TcpConnector : public testing::Test { public: void SetUp() override { - g_io_context->restart(); - pool::load(g_io_context, 0); tcp::tcp_async::load(); _server.init(); _thread = std::thread(&test_server::run, &_server); @@ -51,7 +47,6 @@ class TcpConnector : public testing::Test { _server.stop(); _thread.join(); tcp::tcp_async::unload(); - pool::unload(); } test_server _server; diff --git a/broker/tls/test/acceptor.cc b/broker/tls/test/acceptor.cc index a967007e7ad..404e63b3b7b 100644 --- a/broker/tls/test/acceptor.cc +++ b/broker/tls/test/acceptor.cc @@ -28,20 +28,18 @@ #include "com/centreon/broker/misc/buffer.hh" #include "com/centreon/broker/misc/misc.hh" #include "com/centreon/broker/misc/string.hh" -#include "com/centreon/broker/pool.hh" #include "com/centreon/broker/tcp/connector.hh" #include "com/centreon/broker/tcp/tcp_async.hh" #include "com/centreon/broker/tls/acceptor.hh" #include "com/centreon/broker/tls/connector.hh" #include "com/centreon/broker/tls/internal.hh" #include "com/centreon/broker/tls/stream.hh" +#include "com/centreon/common/pool.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon::broker; using namespace com::centreon::exceptions; -extern std::shared_ptr g_io_context; - const static std::string test_addr("127.0.0.1"); constexpr static uint16_t test_port(4444); @@ -53,15 +51,12 @@ static tcp::tcp_config::pointer test_conf2( class TlsTest : public ::testing::Test { public: void SetUp() override { - g_io_context->restart(); - pool::load(g_io_context, 0); tcp::tcp_async::load(); tls::initialize(); } void TearDown() override { tcp::tcp_async::unload(); - pool::unload(); } }; diff --git a/broker/tls/test/nominal.cc b/broker/tls/test/nominal.cc index acffa3fdaaf..b39c6dcbcd7 100644 --- a/broker/tls/test/nominal.cc +++ b/broker/tls/test/nominal.cc @@ -25,29 +25,21 @@ #include #include "com/centreon/broker/io/raw.hh" -#include "com/centreon/broker/pool.hh" #include "com/centreon/broker/tcp/connector.hh" #include "com/centreon/broker/tcp/tcp_async.hh" +#include "com/centreon/common/pool.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon::broker; using namespace com::centreon::exceptions; -extern std::shared_ptr g_io_context; - const static std::string test_addr("127.0.0.1"); constexpr static uint16_t test_port(4444); class TcpAcceptor : public ::testing::Test { public: - void SetUp() override { - g_io_context->restart(); - pool::load(g_io_context, 0); - } - void TearDown() override { tcp::tcp_async::instance().stop_timer(); - pool::unload(); } }; diff --git a/broker/tls/test/read.cc b/broker/tls/test/read.cc index 296eb53fcea..4c3bcf6967a 100644 --- a/broker/tls/test/read.cc +++ b/broker/tls/test/read.cc @@ -29,8 +29,6 @@ using namespace com::centreon::broker; -extern std::shared_ptr g_io_context; - class TlsStreamRead : public ::testing::Test { protected: std::unique_ptr _connector; @@ -43,7 +41,6 @@ class TlsStreamRead : public ::testing::Test { public: void SetUp() override { - g_io_context->restart(); try { config::applier::init(0, "test_broker", 0); } catch (const std::exception& e) { diff --git a/broker/tls2/test/acceptor.cc b/broker/tls2/test/acceptor.cc index bfd85f25035..8e53205ca5c 100644 --- a/broker/tls2/test/acceptor.cc +++ b/broker/tls2/test/acceptor.cc @@ -30,35 +30,30 @@ #include "com/centreon/broker/misc/buffer.hh" #include "com/centreon/broker/misc/misc.hh" #include "com/centreon/broker/misc/string.hh" -#include "com/centreon/broker/pool.hh" #include "com/centreon/broker/tcp/connector.hh" #include "com/centreon/broker/tcp/tcp_async.hh" #include "com/centreon/broker/tls2/acceptor.hh" #include "com/centreon/broker/tls2/connector.hh" #include "com/centreon/broker/tls2/internal.hh" #include "com/centreon/broker/tls2/stream.hh" +#include "com/centreon/common/pool.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon::broker; using namespace com::centreon::exceptions; -extern std::shared_ptr g_io_context; - const static std::string test_addr("127.0.0.1"); constexpr static uint16_t test_port(4444); class Tls2Test : public ::testing::Test { public: void SetUp() override { - g_io_context->restart(); - pool::load(g_io_context >, 0); tcp::tcp_async::load(); tls2::initialize(); } void TearDown() override { tcp::tcp_async::unload(); - pool::unload(); } }; diff --git a/broker/tls2/test/nominal.cc b/broker/tls2/test/nominal.cc index 5a42b30f613..d76f35b32e1 100644 --- a/broker/tls2/test/nominal.cc +++ b/broker/tls2/test/nominal.cc @@ -25,7 +25,6 @@ #include #include "com/centreon/broker/io/raw.hh" -#include "com/centreon/broker/pool.hh" #include "com/centreon/broker/tcp/connector.hh" #include "com/centreon/broker/tcp/tcp_async.hh" #include "com/centreon/exceptions/msg_fmt.hh" @@ -33,21 +32,14 @@ using namespace com::centreon::broker; using namespace com::centreon::exceptions; -extern std::shared_ptr g_io_context; const static std::string test_addr("127.0.0.1"); constexpr static uint16_t test_port(4444); class TcpAcceptor : public ::testing::Test { public: - void SetUp() override { - g_io_context->restart(); - pool::load(g_io_context >, 0); - } - void TearDown() override { tcp::tcp_async::instance().stop_timer(); - pool::unload(); } }; diff --git a/broker/tls2/test/read.cc b/broker/tls2/test/read.cc index 296eb53fcea..4c3bcf6967a 100644 --- a/broker/tls2/test/read.cc +++ b/broker/tls2/test/read.cc @@ -29,8 +29,6 @@ using namespace com::centreon::broker; -extern std::shared_ptr g_io_context; - class TlsStreamRead : public ::testing::Test { protected: std::unique_ptr _connector; @@ -43,7 +41,6 @@ class TlsStreamRead : public ::testing::Test { public: void SetUp() override { - g_io_context->restart(); try { config::applier::init(0, "test_broker", 0); } catch (const std::exception& e) { diff --git a/broker/unified_sql/inc/com/centreon/broker/unified_sql/rebuilder.hh b/broker/unified_sql/inc/com/centreon/broker/unified_sql/rebuilder.hh index 7fc7c618f32..b8ccb624625 100644 --- a/broker/unified_sql/inc/com/centreon/broker/unified_sql/rebuilder.hh +++ b/broker/unified_sql/inc/com/centreon/broker/unified_sql/rebuilder.hh @@ -21,9 +21,9 @@ #include -#include "com/centreon/broker/pool.hh" #include "com/centreon/broker/sql/database_config.hh" #include "com/centreon/broker/sql/mysql.hh" +#include "com/centreon/common/pool.hh" namespace com::centreon::broker { @@ -75,6 +75,6 @@ class rebuilder { }; } // namespace unified_sql -} +} // namespace com::centreon::broker #endif // !CCB_UNIFIED_SQL_REBUILDER_HH diff --git a/broker/unified_sql/src/rebuilder.cc b/broker/unified_sql/src/rebuilder.cc index 26fb58235f3..123a8a7a9d6 100644 --- a/broker/unified_sql/src/rebuilder.cc +++ b/broker/unified_sql/src/rebuilder.cc @@ -1,20 +1,20 @@ /** -* Copyright 2012-2015,2017,2020-2021 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2012-2015,2017,2020-2021 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/unified_sql/rebuilder.hh" @@ -66,7 +66,7 @@ rebuilder::~rebuilder() noexcept { * @param d The BBDO message with all the metric ids to rebuild. */ void rebuilder::rebuild_graphs(const std::shared_ptr& d) { - asio::post(pool::io_context(), [this, data = d] { + asio::post(com::centreon::common::pool::io_context(), [this, data = d] { { std::lock_guard lck(_rebuilding_m); _rebuilding++; diff --git a/broker/unified_sql/src/stream.cc b/broker/unified_sql/src/stream.cc index 8d579fbcb39..4b8fe58ea0f 100644 --- a/broker/unified_sql/src/stream.cc +++ b/broker/unified_sql/src/stream.cc @@ -166,12 +166,12 @@ stream::stream(const database_config& dbcfg, _max_log_queries{_max_pending_queries}, _next_update_metrics{std::time_t(nullptr) + 10}, _next_loop_timeout{std::time_t(nullptr) + _loop_timeout}, - _queues_timer{pool::io_context()}, + _queues_timer{com::centreon::common::pool::io_context()}, _stop_check_queues{false}, _check_queues_stopped{false}, _stats{stats::center::instance().register_conflict_manager()}, - _group_clean_timer{pool::io_context()}, - _loop_timer{pool::io_context()}, + _group_clean_timer{com::centreon::common::pool::io_context()}, + _loop_timer{com::centreon::common::pool::io_context()}, _cv(queue_timer_duration, _max_pending_queries, "INSERT INTO customvariables " @@ -835,7 +835,8 @@ int32_t stream::stop() { */ void stream::remove_graphs(const std::shared_ptr& d) { SPDLOG_LOGGER_INFO(log_v2::sql(), "remove graphs call"); - asio::post(pool::instance().io_context(), [this, data = d] { + asio::post(com::centreon::common::pool::instance().io_context(), [this, + data = d] { mysql ms(_dbcfg); bbdo::pb_remove_graphs* ids = static_cast(data.get()); diff --git a/broker/unified_sql/test/conflict_manager.cc b/broker/unified_sql/test/conflict_manager.cc index ca9f5a464c2..3f2b99647bf 100644 --- a/broker/unified_sql/test/conflict_manager.cc +++ b/broker/unified_sql/test/conflict_manager.cc @@ -1,20 +1,20 @@ /** -* Copyright 2018 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2018 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/unified_sql/conflict_manager.hh" @@ -32,13 +32,10 @@ using namespace com::centreon::broker; using namespace com::centreon::broker::sql; -extern std::shared_ptr g_io_context; - class USConflictManagerTest : public ::testing::Test { public: void SetUp() override { try { - g_io_context->restart(); config::applier::init(0, "test_broker", 0); } catch (std::exception const& e) { (void)e; diff --git a/broker/unified_sql/test/perfdata.cc b/broker/unified_sql/test/perfdata.cc index 512ab44ddf2..474c3bd37be 100644 --- a/broker/unified_sql/test/perfdata.cc +++ b/broker/unified_sql/test/perfdata.cc @@ -29,8 +29,6 @@ using namespace com::centreon::broker; -extern std::shared_ptr g_io_context; - /** * Check that the perfdata assignment operator works properly. */ @@ -199,7 +197,6 @@ TEST(UnifiedSqlPerfdata, DefaultCtor) { class UnifiedSqlParserParsePerfdata : public testing::Test { public: void SetUp() override { - g_io_context->restart(); config::applier::init(0, "test_broker", 0); } void TearDown() override { config::applier::deinit(); }; diff --git a/broker/unified_sql/test/rebuild_message.cc b/broker/unified_sql/test/rebuild_message.cc index 8370ed851d9..fce15b3203c 100644 --- a/broker/unified_sql/test/rebuild_message.cc +++ b/broker/unified_sql/test/rebuild_message.cc @@ -38,8 +38,6 @@ using namespace com::centreon::broker; using namespace com::centreon::broker::misc; using namespace google::protobuf::util; -extern std::shared_ptr g_io_context; - class into_memory : public io::stream { public: into_memory() : io::stream("into_memory"), _memory() {} @@ -76,7 +74,6 @@ class UnifiedSqlRebuild2Test : public ::testing::Test { void SetUp() override { io::data::broker_id = 0; try { - g_io_context->restart(); config::applier::init(0, "broker_test", 0); } catch (std::exception const& e) { (void)e; diff --git a/broker/unified_sql/test/status-entry.cc b/broker/unified_sql/test/status-entry.cc index e359798cbaa..da7122ca0fb 100644 --- a/broker/unified_sql/test/status-entry.cc +++ b/broker/unified_sql/test/status-entry.cc @@ -37,8 +37,6 @@ using namespace com::centreon::broker; using namespace com::centreon::broker::misc; -extern std::shared_ptr g_io_context; - class into_memory : public io::stream { std::vector _memory; @@ -72,7 +70,6 @@ class UnifiedSqlEntryTest : public ::testing::Test { public: void SetUp() override { io::data::broker_id = 0; - g_io_context->restart(); try { config::applier::init(0, "test_broker", 0); } catch (std::exception const& e) { diff --git a/broker/victoria_metrics/src/connector.cc b/broker/victoria_metrics/src/connector.cc index 30c1090602e..47bb952138b 100644 --- a/broker/victoria_metrics/src/connector.cc +++ b/broker/victoria_metrics/src/connector.cc @@ -1,25 +1,25 @@ /** -* Copyright 2022 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2022 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/victoria_metrics/connector.hh" #include "com/centreon/broker/http_client/https_connection.hh" -#include "com/centreon/broker/pool.hh" #include "com/centreon/broker/victoria_metrics/stream.hh" +#include "com/centreon/common/pool.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::victoria_metrics; @@ -36,10 +36,10 @@ connector::connector(const std::shared_ptr& conf, std::shared_ptr connector::open() { if (!_conf->is_crypted()) { - return stream::load(pool::io_context_ptr(), _conf, _account_id, - http_client::http_connection::load); + return stream::load(com::centreon::common::pool::io_context_ptr(), _conf, + _account_id, http_client::http_connection::load); } else { - return stream::load(pool::io_context_ptr(), _conf, _account_id, - http_client::https_connection::load); + return stream::load(com::centreon::common::pool::io_context_ptr(), _conf, + _account_id, http_client::https_connection::load); } } \ No newline at end of file diff --git a/broker/victoria_metrics/src/factory.cc b/broker/victoria_metrics/src/factory.cc index 76425730462..79f3aaa3d37 100644 --- a/broker/victoria_metrics/src/factory.cc +++ b/broker/victoria_metrics/src/factory.cc @@ -1,25 +1,25 @@ /** -* Copyright 2022 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2022 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/victoria_metrics/factory.hh" #include "com/centreon/broker/config/parser.hh" -#include "com/centreon/broker/pool.hh" #include "com/centreon/broker/victoria_metrics/connector.hh" +#include "com/centreon/common/pool.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace nlohmann; @@ -50,7 +50,8 @@ const json factory::default_extra_metric_column = R"([ {"name" : "serv_tag_grp", "is_tag" : "true", "value" : "$SERV_TAG_GROUP_NAME$", "type":"string"}])"_json; factory::factory() - : http_tsdb::factory("victoria_metrics", pool::io_context_ptr()) {} + : http_tsdb::factory("victoria_metrics", + com::centreon::common::pool::io_context_ptr()) {} io::endpoint* factory::new_endpoint( config::endpoint& cfg, diff --git a/broker/victoria_metrics/src/main.cc b/broker/victoria_metrics/src/main.cc index 6424b7b794c..aad5d1ebb3b 100644 --- a/broker/victoria_metrics/src/main.cc +++ b/broker/victoria_metrics/src/main.cc @@ -1,20 +1,20 @@ /** -* Copyright 2022 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2022 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include @@ -29,7 +29,6 @@ #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/io/protocols.hh" #include "com/centreon/broker/log_v2.hh" -#include "com/centreon/broker/pool.hh" #include "com/centreon/broker/victoria_metrics/factory.hh" using namespace com::centreon::broker; diff --git a/broker/victoria_metrics/src/stream.cc b/broker/victoria_metrics/src/stream.cc index 26a95b97421..d0000f28819 100644 --- a/broker/victoria_metrics/src/stream.cc +++ b/broker/victoria_metrics/src/stream.cc @@ -1,27 +1,26 @@ /** -* Copyright 2022 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2022 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/victoria_metrics/stream.hh" #include "bbdo/storage/metric.hh" #include "bbdo/storage/status.hh" #include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/string.hh" -#include "com/centreon/broker/pool.hh" #include "com/centreon/broker/victoria_metrics/request.hh" using namespace com::centreon::broker; @@ -84,4 +83,4 @@ http_tsdb::request::pointer stream::create_request() const { ret->set("account_id", _account_id); return ret; -} \ No newline at end of file +} diff --git a/broker/victoria_metrics/test/factory_test.cc b/broker/victoria_metrics/test/factory_test.cc index fda2e259f5a..e114faff650 100644 --- a/broker/victoria_metrics/test/factory_test.cc +++ b/broker/victoria_metrics/test/factory_test.cc @@ -26,7 +26,6 @@ using system_clock = std::chrono::system_clock; using time_point = system_clock::time_point; using duration = system_clock::duration; -#include "com/centreon/broker/pool.hh" #include "com/centreon/broker/victoria_metrics/connector.hh" #include "com/centreon/broker/victoria_metrics/factory.hh" #include "com/centreon/exceptions/msg_fmt.hh" @@ -35,14 +34,7 @@ using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace nlohmann; -extern std::shared_ptr g_io_context; -class VictoriaMetricsFactory : public testing::Test { - public: - static void SetUpTestSuite() { - g_io_context->restart(); - pool::load(g_io_context, 1); - } -}; +class VictoriaMetricsFactory : public testing::Test {}; TEST_F(VictoriaMetricsFactory, MissingParams) { victoria_metrics::factory fact; diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt index faef6dc9663..e320764b7b8 100644 --- a/common/CMakeLists.txt +++ b/common/CMakeLists.txt @@ -43,6 +43,7 @@ add_custom_command( # Set sources. set(SOURCES ${SRC_DIR}/hex_dump.cc + ${SRC_DIR}/pool.cc ${SRC_DIR}/process_stat.cc ${SRC_DIR}/process_stat.pb.cc ${SRC_DIR}/process_stat.grpc.pb.cc diff --git a/common/doc/common-doc.md b/common/doc/common-doc.md new file mode 100644 index 00000000000..aa2c67ff42a --- /dev/null +++ b/common/doc/common-doc.md @@ -0,0 +1,10 @@ +# Common documentation {#mainpage} + +## Table of content + +* [Pool](#Pool) + + +## Pool + +After a fork, only caller thread is activated in child process, so we mustn't join others. That's why thread container is dynamically allocated and not freed in case of fork. diff --git a/common/doc/pictures/logo.jpg b/common/doc/pictures/logo.jpg new file mode 100644 index 0000000000000000000000000000000000000000..0bcd7358aa9c7ffa817d9a30008efcd4d1fe676d GIT binary patch literal 49244 zcmeFZcUW7;wl^%7#Btn0FkqXOfDOSIu)tJNj$?{#ieh7W3y3a+=uH9=lb8+xOh+g- z-GF3)L>Cx?kf|~V5J(_Qw*Ub`AUeEq&PndQ-*fNxKJPzypYQq3puP9Z-fPyH`OTU& zvuCg2ck1DI zlmqaS8VW$50#Ne_P+3b^RST%1a9dUD_HDpv0N}SXpU!~W%F4ITrl0zQ^HCB2aPs$m zN=fI7I`yC8pCo>|_o>XMHavrZ{Irymd;=AoKb1le0*5JuIr}LA6>lp6wDrRLoFP!R zpl@8chAk!>wZLln|XxU6G#LUqUkE7r~8d|m{u6f z59Su+{7o3l$2U+bOh@Vu=34ytr`t+W-~2%m1l5uHXWgw$fB5DeJizT6RYf%g2v9}i z8+A=ZpsJ>Z@||0suuxOFt*HdOqi`Fjbz4*GHt?H&1u4F?09SXd$NGl6=}7TQ`p+uB{QhG5-(vMAp)2GsI=|ompFf1VLX_Nm++c3LL4kZ+fuE}XCsR|? zzsUbvwlLUV)PX^d-TtF)|1EXklW;#brN?f8@ZbQ58=qYIlPEu}djW3FLGXYlaJbK( zi2uK6+keXArtci&rX%(LRKI`f-aqL~;jUip;r~6|Uuyacb(ypW5NiysrO|_ul`Q_mf7${P>df-2%Kq+*}O< z;IME0Xbml||G6xh|0BPD<#qj^%X0UB%&WvNjM69l{7?G&=PiCG_!RxC_wf^d^z|*f! zoe%(=6gY88;KXq!K$362PMkh@>JJ0;$w&bJU!M8m?70)4pFI89DL#SYSD&7rIC=Wy z>CewzIRC{N0N}*QQ>Q=s{LB{uXTSay_@&_GyN{fOr2KzQTNjpA)(A^~fvXp}rmC*_ zy;X1sp3pvY|o}=r@0f z{deTw2>cs?ek-*-^R5wGv~)oA zm#Qv7qrUdI3$~fl9+mTjq*y|lVf^aiO<7lStfG%KkfG?4NlFwmp^xG%aRQ_6?onYbsV(qG;&z*@QjP&PQkqg8f7~rixm}+Tik*{jEAycBL^dE z2i?5@;bLixY9%v;aGfQBy*?$J+q;vm=3q7c7y1_}L+Ytx%>m zROM+s+2*jB<_?;5s1AvIv#>eLl@Yg$fJ#ocOvgi1NV0ecIGQ4V&E6{EL5j z@5MBdeOleF_PgGzl@UiT9=oj)v()dw<&;&ZZJ}?-Ax;xzxWpZFiR?`l+j|}3G|G{~ zn(?5{L!*%#0zrf^`;gL@ypvjtR&dU@`gL8wx78&izTZd7o3hepr&D+Ms&hYUH7K4nYdB*??yRKW=v%w$(;3G+N|Z8xGicyA+01(aZmCt(%`AA#^?JV%avs+rng=yraF_#T0IK_vx!7_3QmyO3j}T~MCgaz z9JwUC`j2?FJ@zXW&E}Bn&-fgAZ5~|x*jR|o<2kKaadV0cjsadqnzMMYzzXG=cg5nB z;HGNr18RC+&K^_`q)5vr0C(wHcGFNR_S((S`WZ&?c;MB#^`ntE1HhRb@~{9FM7_k&0H|+Ye+pGAIGFCgyh@N7?&xjckzf)F2@qG zup(HG8L~y!de*NQK$h)!X)_{214|!2WFT>+lbN>36;0Fd>6}8iyk1Jt zFs1goY4l+eZP|g>R=bRF*Ai>3eC-@!V)Ah$R`zMnJ-;S3A=fPJ4<250AbRL_~hkOB9jvB3h6N88Sl%u5XX-2o$y-{+{L6-c3#G} zF|65#Wu-HjZci^vg{GWm4r)gyB{indzD*lDxK*+9D&A{XKOmwp$%$lYzIf@uk=&~~ znCy-9Cci$>KEq0@$=>pu^+f7va0Q9YxV|I>>5(n6(Zmjc;=Mi8vY$7=G@{NjrOhiC zGU3=|^NUAimv_lk1svUXg-IqG9(sXJz;3Rl-t$n{==C(WM9F-LWBvt)W!XL}YP*rV z+|WVPVfqzO#-L8#vu6KQ|Aj&iJVkPrj*+*{EnKjt6 zltpQhRka`DTDFzl@H16A2L+FS32l2&iTQ67k{6I3!Hq4Hq*Z_>GZN$Ct}W~K{jAdp z8{H-XX`7;x9J_?svj^a5&iqctrG4EOS^HOx0oQ`jyJBtoV?xbMhpo&h|MGnbp*979 zrT;ECV&1gBe`I#}hOJe{YVgdJaog-Ka~@Ilv8)WZw(4?pZE6M^1YLOHqMELIv=UHh zUzm`PP;M{Q++Q%*qqWD;wO9~`D{`)}>tMo_y4ly+pia}*%na{+s8?QJP)<&W3nl-v z=AA&h3q=EUd50hqC2s72X*k&+t5EN^8S)0ES#;KQ$aP#;6!x^~rgUp^A(?i+`d#vB z+upq0*Z0fgYHLT#1DlmM_u260%3gSTb}E>zbegPMU8Zei+*x@aedJjCnU15eK3rwT z60Nfa(x1mBL>u+(tq2MY>qCM29^Oo81~Vmt+evBb&&FI_mWeUrLrq%OID+Nw?BDwVxoM134KNY@xa$d)>!?fnp9z!3LiX-4Nr|H2iYk(rQ> z4-IN!ZWlN+dF_?Si)9}gYv|HmM7a+wceEk*uyIK?h+HHqIs=~HGsw>C+vho`N5i9? z-1Ik(0dK}&2U^DfJxaRyQn;kqKmIRty8sWNr;zF6DXLGL*?5 z-cynLQd$*+yndxiRQFLR;m(lPoss;x-t<9}psFxB4^M&$uyeW3&NMZ15Ks1e6Nk{5 zwhN|qH+mae?9$%NTLJq9w+^ZvERFJ<%3ObRvaswh9s(Jc9~MX4Ut87yd*DE3Tiu<3 zkiz_90IwlH--In5>FaHFh{y>^m_ymHPYs=e+jVGO3Qr-leboy-%k%P^i(5}AtXB=4 zidt1VpYc?u$ZK5P_PEpao+N!JqPg}; zC-hM@^pUEx6Lv<-%Bq~kF?DzR7CYR>P_(BJHXK7a1T3)({!)GeiicgWr$M(0j4jX( zox!1_%fW$a-5CmO{%@98jW8{Z(vi}#@*H3PQhWjFX3(;Kw`JcRt~>P=0B}>}+A+Yx z=NOQ%5?x?%yA3Wm6BTnX9eap=+>1(zPS&Cvq`(i^TJ_gb#@_(Mww(z7nEj*s`Y}To zQ8E3gNVsbfB8R6bK_>LjRQsJ&>}gWl(6q=$=CsBwW83U%mRAW22n2#mOw2ey;HZpj z6*x^?HjH(W<2hO^YP9tm_Dm*#fzbRv-}`}jf=wsH3BKqG0+ zggyM1dH!my*_QH$UQyH6OMZ@W+2A}JP^a&C6}{Gu+Lkgx#1dt&;A+xU{5a%>EGwRy zsJ|7z4eoC$&K@fN+xy>%$n1@?>uL8J>+{3*%LcUjHmq*A=O?^zxt7*`+DXx;E>uog z)ANJh9Z6}2wBE5m$+={)QCw1b_*_EE-SkHzTCGAbZ2xFL&)NC zj+_1Lm*OvZWn|5La}8zvb>^w3lPg+UPDDXqTc{#}ZPT0GqaIhPag>7dBCsK!Uw2_I z(l1F0hObZkF2--9lP~bRy$k`L56~YmK-W zF`K&Fi zQz4;TLUeg0BduUN(cpk}*!$ilY9@!(N`+EtwAd1AIrMLn5SDC@=OD3p2k;$kND~l}vUMl#p@~_gQ+XUSFH%ht zo$1BWRJQZ6mTNVsFM(9)M#L=ZJ=dzAnjdRa`Bq5G?E%K9$g81Iq96W1Y8m@nRzp@%%DS&(`{fxiHI5)mL3+U<&)fWg6{C4e1HVbAQFkHh(b&#RrRjs7@1B=A-eO`W$md>tp zYIri2;mI(ERTu6*9!!xIl1hx6%8brv3I%r`EEWWUI!(Y2QYGc4stotHj)0?AFS zWtOv#7#e?M(KOgUTEj9{9H)MmKqR*wat39!-VQhJa z3%k{Pr8?F0tIxtW*hTou?&QqGNysKo^l0Fs&CCHPt#Lnh>v^4`P+!YE;}|1hmVHJC z$6NYQUK$8))BOr_@gS%mN6D<#7#6uvC`vW0==aPaXN@GRwK=YsaV1!5`bh6yP1e`! zzgaQQtq_SvFLb{K|58P((ya^2C_>4NqlUPFh*6i!?2i*(N%*csULp|t4pynOp>sQ8 zBE*W2^b6Zk%5bOB$en6uL!CI4tr2_MTUw$}$1-1xouT>?@jO+$Xn@9htd7>CH~0NG zFo8hMwRVJkMwmcoLw94GjKLSDt+4_XqmH$BTPmRlTwJ~9KH`cEky0?R=*@3Vct5x# zQl4VA1WykXL-p8n*M!?YA0o$hlCBSaAehMZBcE?gLd9>T`05Fs5{n-fqJpJ#Nfqw3 z*K72C46`~r=m(R~k%$!uNE;nxF^P4{(1AgnWw6tQqAE*y(R*(Ps0gzK=4d$9p&vPk zt*f*t&o>kkP)pWLJQLxb=OCk*Z>X&?6S>{(S&$1uW)T-+kI+#^g~tFm>$(SKpNt4& zcqPw3un*!n@yrOYSuGnf$)mf3gHr_d&o>MowMku%8?7P4D#3Fnk=4)KoQ^zd zRG9;ZJ$pP0uKG~wU{sh6;jkpc?d`&W{Eh1TL_d_S2KvpSSDiytqEN&@Rs_SmgltnF zsFEQBIa5VW^xT(Yo2d@QWQ7-535^;K4|#8xF`J~lX`e&EU>ngRV}-hcd_xc=+N&+# zQ1=*+!PvS-Y0WpX=D&xa;WaME?PEXzT!req2V2S6L8x)}BEn*O=RPUi|JhWGpJ85y zx^dKIErK4>Gh#SBMx0Z&%7vdGSws61-ROB;H3;t8-})6BtLxlfS@(9I#~pOHV4f8O z6xS5ZSwkrV-DKS)dorUZg5&%6~bMZB7-|pi9YkAZ)2bY&v7=2HPh)-;wIoZS6PPo|5A?B$p_ruWwZQ zad(@Wi<I(7zy&FJ!g)tBnY zwK7%oWb!-d?(R64>t_6B_I%;nFn1jxpjD3Masq^aM`|e%{LQ@*mbQ4<9#ZMrW{JE& zwuLu6r!*5|GWLSiJJJ3Qx%N)(1L>);8DESo4`W4gpK~-``G=&6#8#il z(%O3IZ6tUt4mGi;GtRyD``~)NqJl)Cm~+Q7X>T%myIN%w=C!O=SUW8)A;E3a4pjFn z=+BtE5|`sE^t4u`1mDL{YrB__24cC(w!NZ0R&UoiXsEmb8t%Xo zpYtjlg7388`u0$S!8#oo?DfrFaj6^?I#QXuFxw4hX+7qO(BTtp;I=v5;SbzZP_1uh__J@9HAje#0p_wKI2V#-dl&5iFoMPsAR|7!MWy4i%H8~?)IwN z9GcBpW57y1$jx9RIb~9Ql_}+#U*eTVmVjP?shf5TzgZ5u1}jM>4W)Kp2C7GTJf} zjbWo6Z{@9bFPBKkC8XIx5{7WrON-v3YkW_o6*VS=v9>%rySck>)@qL51@VZlkyAI$ zQNX$5S8Y2+qJ36~>2d}0hf_7GQ&UpA76|^ZsWOx}7!szjjq! zc^TpPuC(=opp>QusI^x^L$bpr48`xZbXLMbGHNg*5QiQ0TYCgf_C@uyKUkj+ z2})9&LQ_qTer@+8eitm)9X#D!ydHghfio(Q__>WLG7EG;OA}P|d*A$vr&ZPL<;fdQ zw)W5U{=y5Vh=pW!zil*ksBDLyZ;P2DCxmh_CYdD)M}^EChZd#Z8Y#(-8#O#`K~*)B zb{lmJDpEq%8H)F-6(skv@BJPI-+Gby4*Xl&Tbdj#L;RMBvFNj(GOAMZT9RGf^jFxE zYw z9*>^d*-g2y?$ye%;V7Mt-Hb(r>F)9wRHnaI zM{GC&-yrQIlnN`m7pZR$d1Nw~9mCNE^>2pDNRNxJO-{nqJtw-x3$qMSRgv@o>&1$I z7J^T^6r#qPi^IlG(#HD@%qEj=R1Pj}Ufp1+?wRB%I9|&mR$>GMw zJ&&x6U^D|Kb2#zw@eywFKLJv&h`bnFyFY$ZqDHEJ?rU_GWPR?!;d7snS=T_vnywn_ zt*X;?SE{lVG#J89HwC#Q2H7&v1T{bZ(^$%jGW-{c`DRrOO3M7a_Gs zX=-ak79zX411f}H(`Xi2n{H?n!(e?=bUUNMYVwzD(`(<21X-7r6_N`X!uW8J=i%~7 zU$yE=ll%vCKJ$ohL1*|dcT<;Uw<(LehEygBuvxZAd>^2eAIFOv&;E+s89t>0i?!+W zqc`66i$g7ENXQ#S ze>Yd74tvO|c4&*5OU;^Zltred+ej=D*Q_)x>`T2$lyC8ao-EMz{*pwL6{1Uu@-$j^g`E-Q5`!s~3Am zZ6#pr-oet3pI|~nIx>kFTiaVsLxF8cU~BXhUgypld#Z1_l>-9Tk8_(>+g=x!_lPj# zWnJB%mzi7af7V*6WDhbLxAGntrGb0JD6dwR@)3)bI3jIObR4n0rEfM#Jk+H)9#V8?z35N@AgokI_X$i_ z6gIExIL1Zo`51+`xG0E2irMwgkw>~~m=L$XV)U2H#|s}>tM=_OcCkB5*94MQ9ggks z4NSE#j@K*_`%X%x`7Y;GrSDYyYUoVUmugZGCixe}X+>)i3+1HF-MoN+sZ)6U(X3K> zzkbkis`xSBMRDiaRTWDZYz7*8!=r^F_VbvP*n;iMjCRMeCL)I6Rb`vD;~3EwHcN`i zfdWUB7phA=yfE@ZE`w;M$VYCO;^`M=^^%;B#*3DfMVb2{QNM`F%)1Z6R_YvT+-9;O zyyv-~`6sp`d6+}Y=dv#vkl1nT^^FvXjn9hNZhx>{!KvpYFE)20BpXJN(;1QEK&Z5LI4;Krl`NP+?eS`Som!tcfVIYi3B%`4t7`7u2r z>#JPJ;(L@Wm<<6oYm<|cS(a~F(e71hFG2>+3ffd1P=T}sW@RHQ`bCP#0;)(fI%Jf0 zK`@a8{;ZD)SN(oKP`03a#3w#+S}la=m+#~L@r!A5KPX3=c( zoUo|+ydB~C=ODcyhJ=G7*6P`w$zGowsR-PG^C$^$Z4FCVS$dgK#{aOZEXyeMC`l^`Yz2OTKtIniztY`~(4 zU2n$Zt>WWeEousKN?-2^QL?$vl=~q+K4_i-BRBxCV%Pl2c)dH zzt`rN+~pE^2^CNZ%~PS@tZ-K}wye6E+6>dqh6Q^}MRs>3LN-X*Fq5FD@k=mASqzVeL4%Z$h73 zw)F@{UqxTdJ&Jm*!Sv_~{U?T+hLxGuhAjeKNk6KX?3s6bm#h!A3U!*7nDTJKlF5w4 zw$%Kbwa}N)7DiOz$B8!k^)6NE1BDAQV^VHmzOJ9$rT9QKgXC4_&ACOw!c)OR2Wc z3pB%$9M$TY)ORn_Jw8KZDBW zs#a~2+wT@89iOgiM0_`@nt*wtzbd8Rm0&3Y3y+J7W4crMgSpngYSQj&*6W2~ZxyT0 z(O^3#8DqNKLr7I21Xy zx_Vt&A;>2-KXyA4>`W~|q9sI-kwU5Lka99tO`VjANMCiISA0;K(h!z?g)}vK6r!z0 zhb9gvgmHT%fPzCALs3q#>5k6}bLg#}y(EOzN|}?EnFZYsy3;C0RN-8@Hc$P?-tf5i zbZ|o{PkPjQmUx*EREK_h``)-Ng~r%Tdd{u-7xa=8^JRC)+jB4JEz8{@np3~|uc4E6 zqE+vXi3P{mE+L|?e?O*dy;r+C_!wy>BSIy5q0(x`2;Ymye+Vw8Npcr&Q!We|ogZSr zJie;hUW~$bjMf6{f0;uq+i(&{Exat=o&fJcEMCH=o35_RBEoM5s3DzVTnM3L%*+Tw zQEMtJr%wEWheVNrI(-*gR?@t47%XFRn6Ywj48YFaJF^p}lOOOm>B)Z;b7EZ$R^&ic zJ?NsX5nGxG_% zv$Lq{Llt;9Dg*P%Wq8Kz3AETH`Y}&+sJ1|oq3i1ykq*AkV9_J=4S(m36dZrKaXY8l zMH(&{WMmVkPwRwqPB|}GNvF-ETz$8o8g;tl`esetAQciQR(mT@r8iJjB(vuIa2iL| z8{$~b8jMOy^XT8T@LH5GpIgzEdQMyB(9{L-a3`$~Q+s$0lY0my-!FX567=Ha55*2q z;zKH4jRe5IU8-GA8Nl-hDok|}I*G0z`J5uIlzPvmDgvcYS9d?Bw;~=tODgL;5rt^U z)BhJbC-&~0uaik2h7}iv&$-_25EQ>&Yb>9ZMiTQeuzI)HSU#+8Vev$NOAsiaqJlR{ zqWq%E8QKkikPH*zQZBt%g=V1CUQz3oT`ZmQOAtR$ehe@0Bw>wd}qK{NFQaD#*j5$Yk9C!AH2dV!8%&u|20@ zv91nuDZb*yGH>oaeeqpV^|_I2U5#s@?!Xj8nn*1;My*m;L9H+&TNh#AWnEYc1>fH` z8kd*@i_Y4sWNWBjUbv`UU3T%qf#~NBmSsBIt26D-GLYG*m+m3e?k-X?RFEZ31t@qC z`xRI~hgx+Z#T0C7M^8PmysL_~ACZ*0m%&i9M9fy#`Bn-}WY}9a4pbOmf+H?uZ<~*C z$D<1mh$_*?YcE7OJ1hJ!Ul)PulU8y2DN<=)|1N$=>J0&}^XOjv< zY70g3U?u!Ftbk=DvrQ`-Y+m2!xHc>XEa(#vhCXul#u?DS`*U4ttOr>L^^%2ZzBbEZo_;m zt6)Pe<1)Z5>O7u5l={#m;iQBv*v!f#>YQ)qhDpq>;Nb=r0&A&?ZH%9nN|Mm4W_U_S#uuUE=d4}_P@wLu{ zjaygbTrtfu(S|e?!OnRIBc{2=ygooRO>`#>eB;ZlVjfp{Ij3^xF#Ed@P*2`~|03$l z7w^rkjO?Kdy$zwJaw@4}eOuLVosXF9xCH)yfq6e1ZF;1F`EZn~P2CYlIVqkCe9Cn@8S9NJ;p(Me6(e&iny&rF9!+fLoxJg4UxO?KiL?R>H5#NL!#zN+^@ z^4IA@Xylpqw+_>e0pii)pLj;szmKkRJqG*~B@(+;y(#&RTAtBC@G-zO`lpoOqp7<` zxQwF{JC2g0_3tD9KOqfU=1Fa%E%Nq{0Reh%z*=M{r{7t}fVqFx@tM|kH3*Tbw;n+% zYFeJH6xMy*l!fgUmfv<<%4jq09d?opIvl#|4R5Ot6bT`X!&Nr0-*PSjJ8M|5m*jj? zc<}+y0%jxtDq$W6hLpi!~y_O=tA9G@>HFPLln^GR7c~ zY9_Jt)8DAje~IF2cJynFLflP}Vf5LVruYx5M$>)7xC)hE+FV6ScmKIEcS+|Wm-CqV z9BbQhmW`FBk)-_C2(&mwoxA|n%8vdfFskUc-Hx9E9kVj>!VJTRoX%|z#d9Rw5)eKu zn0;Z*IyXKJPbzCqLD;Qu4d_@8ZN@vTiL_EI(91*O)+jdWwl|L6h|gVURk7D9u&%Mi z0oAJbC+72SG-F~LFFn;f1?obgF$|ho)#;_~<$;8~@Gs$rp)BaR;A=@e)3>_Fy2PAJ z>rDgiU02s6`0I(ve&jinhD2gcc%Xwr^!d?F6I(q!ao%oNpm}(mcEdslQHeiEs^h5U zM+G%rl zTK@^&xvg~)W0o2*^C7?Px{pPzO#!b+xtU6l8LwFMv)&m*l+A+V10|C8M+Ar8I;Lsg zoUp^K29h53Z?OD-9MLygVi7a~nNdDL-CjE;`*xs@;bh$UrTeY@Tbeb7+V)0|%HQ`< z?&m}CS}3*eb{M)Q{u1MKWQgevA;ca(C`~SZtl;fQJk-1E5K50Q(T@3J!vAOK{;unZ zw=boXY9f?Ij$W+$4{7Zv=vAhqY0xSMH1ka-zx9=M?JB0-N#^~k#q|ijRa@j_Jqnh` zekh9o)|YD;8o4Dwb9Q`4j-590HAlnYu{EoDjtXy;cFbZP5mfW!>4PyA39?bm@Ck}z zZLBKPiwx={aTqt0e%TLPQF;yvoHr>rmE#}v8EMnsrvMZ`OE&fn(kxYDsnl0fT~S5m zrG#bsk+>X!GF902UR(KUo~B(1@rWY1QFwOKBVw!;v-0G~b&ok6`z-o-Ul%dmQuWrG z@{g@PN`^MCSaw3?E@_WMMjY?*oo^8LKjiEzDl9`(rJL<{ls1B|+1H8=+~V8cO85vK zo_bxMA-*O63R9xfT(wza6qUvKl)!0pj9Yya-PBQMt(f+qx*1nKG*6crSznvQTd7^e zo2zNr!9Jcq;(q*BYn^eUsudI_*Dp0=z6NLJ4y&2S492I~SKr^T7R&T0k*&-l4pz8S zMINorg^El^_^Q4QL!TKnZ!4amBk4W_x-2rB!w{Oqg8T6+IrFRP)$^@7?V5?trW!jn zE@Dlq+ChD=Y}344+zt#B$`V~c>xr*6L_K)F+4?Ht0<+{dUFpgnpd8H%IF->d8=yQ*40pdiZ%+Z{IFL*_i658OkFgFzNN2nBj>(kBE31?v>duDO@EL&_p>QS71~7f6r8`$YS{ zOIiP`oHJj>GggiPR!p=r*{oJi@U7POQ+uhb+Qf+B+5CyXo+}}Ys_h4Gr!lYMA69Im zU@q3v{mbKLy4H%u;O^IPI+BjVPWbVJ`?MOziJ$40ltcW+J8EjG82K#--D}hdQ(iD?;q(ZHgfk?H+OK`A26u@y&*{_tLit_7DU6CNRn8 z?cuD%JC?Yx6!yzp`3R$!$mWnU13EF>JAP3=7W+$_>y)BRPncf>(M+qzPS?N@YNS^r zLCIgdN_hksmredxr&2rHyU(q^`xmUI!@7>nDu> zcOuu8Rali?%RWuo+pV^=uAuQ&1D8CgG3Z&Yj_iL`fxj)KiY+8yWg;HV7fSbN zFTMqGQqFWjH!6IyN$FCEykuSL-7uAz++1?D7-?C>6UE}MpkAUW-97kukTDxu<$Al%l|YH8JWSrKPmo9{w!db}^jE_)hM_O>Dg zW+vVrA?B~ue|dnhl`v3bESy_ss#6V|g}SyQ47Jl}5+;R$5k`BefqFk4AY>wDy1O(_ zCAj5GPnbzZt?tvCbV5T27zHp@z&(1@-ZJD*gRVMZmW&PUlbj|Fi zT)5)0Y%FKMaoF6vtXH%zlm%O;kITu2blVh!`}5zQW{8}r2>ScnH3O65cX@csQKwN&w@ zrmn>jZ~OQv_aNe;LnkZ(({8${q9Hc<9UOukjrNdsd*+VKvb;a~;Bu8^?|GcEbz%1v za&he0nFH`o9C0O)5A>B5_4to45fb{sLav-A&sN(75=QWdVAiVQP2F9b`TqP$e!AWt zChlc7rvCclti52uY=LdET9J5wbMJ#?LM8lcRi|w>hDMGU-6X(m=~9nqi?N?C4z;@T zcF9{C4D?CYYAxHwEQ1>>6p3CJ$3bUxgQrSIrzq0WWzRS2u8!DUc>c7fD@#Xf#khV| zfNq$2>9g5ff4{;`COhKcQG)0RcOIv?ls2S6nc7(%XB>@(W9lW-|~w zcyrrGtws}6(wn?jWOg`4GTV@k1OdfL+*6Gr4VtM$KWZ0J#$CH|jkhmd73?rk+j}hq zRKC^d;*lN6Ey0=A6WvEO;jUK{V4ys>z(avw3=q2g}q)6uMlm+)JF?iQHihXU* zir%@Zm7$r^{3``gC0)7jTFplAst)Kp@)GpQ9Mnk+3>Twyw=@n+oU!V)?|#eSC|-Dl zwKahuLz8D3{g`U4x9|r`Ze&#=Vl*CA>Js9Vp_!i?5=m+Zy*76k+@RJR8$@2J+X^M? zp%T?}@x2L$I_}z;c-tt8R(rm)qQluR%DR%d^+X7&-$p$8XHCpC&OP_i_UstZu6t{B{MQITAiI+ z@$o4cg5sg6N`ae~UIWB#@(i4CLPivv3f^S@N)_iUC*@;mN2+6wQEy9z5q#l`rFRVy z=mz?#I%NJ<$zlgrPF*K8fqs{~W3@ZB)s~-C0FTGoK4QKe9f^Xi6b*9mg|uL6g*Od4 zJE2PSsmz(Co+{2kY88`gX>*V5d^wtqdb-O@TJUulvM5kieuU#K3TMGaq_vcO%m% zW$|6LgUBkgkKFgZpM4Y>cT9|(C6RZwMP`v^5T9I}81Eze~z6p8QPEMWd08`j^vu z7jy{9PRPOhTVuCoodM7|#;ig@^Omdf9c49%%&+@F0p`_#_RS%i$}=rLza_LV#r>L2whL4LyaE;o*@0=VbMTb{#gY=49U+bhMvn?C3Po6w^T=bxF#8Xu( z(l_=|q)hFDh&fWWcxf(hu9#F2;aDqNUCEzi=y!H@tryLR>D?m*X$^>WZiY3)UZTym zitVUCF!nY$*D9KfcEg&W-OyGpKSK`QjQRy(Cw|9yKJ3PBir0q(^}rV3^%{q>=#?WxMez&c*l5YE-uw`=6n9GT3|K2Tg?+ zm`s>wE^~JWhJ>h=2CyOw!->+g*Zo_(H8y`Gtu4BLPh{2Hhi_`Txb_~kZd2(w_!r@f*8vx)EZRr?bEq*SDdDDAj((y8^V1l#zYS@BnWP{y=Rid(+ zUDl@FQ6}$~qtdP=%+wkc)s+saF&m(})J2t*)He7fAx5t~wtTh`qUNyf*Jl~mol$Jd z6>OO$wLL&J*$!@a&GOgi6{04aMXJV{eQj>p668y8+KH2tOy;ZkeE}halo{k_&WbHNE>1^`IcS`N8O9^?d`TeDVmXHX8 zka*PgNAfX1?!dKaBIuUov~Fx|wsPt!Jv_>M;o23t5Q;I#3+^{IBixwd$|G=%wuk#l z>|b}=^;Wh=?GzOHP$e_uXVM7sdmU_q-K72a)}4d{kIz~qOjuE>;*pMg&8ADQOtGJx zZ)(^{Iru>fQaSR()i{s3ez00tl}&9{?I*1{ILLbs?9+_x!|+kSme6%qA`&}z zH$Q%f3l42ts?@b$>1k7X_HI0dZm-QNPIS+$GWcFy!XAy$-$wP(6q$|QR;KPFy&)2; zTjS{-#Etvgnv}qi0SgNYHMsCCYapZ}R@`rzWL@oLOM=>V!i1__q@-}-Qv9IxeM-at zchs>gc;Bpjj;x7+<}IrB2WVovUuj|t3=F)>YPR(c&j<>5=F!#Tr=s;FMI3B}$Fl2*lOZi6rit10!6YOtcAK8#5Um2w2b_ zgls69UzIg8SH<>hl024-Yc0*+o!{Z01|ukqJ`fIuA?t%vGI(h|bw zFa`ySQ8|8s;HS{)`EBNPl76l6)7T@4(RT9YxA6|TR}(V2p~57@l60$^u!3Q=cRqJa zsrWgR{c^5#P!;Fky6x{7R%#5pTE_K?aR@JD2lRzPQ_VqEO3%WRYDK!|XeFU9kn4H= z5<|^m(;?j*MQ!K=KW)`Dvpm^(*Ac%Ke^CZlP`EDgG8`$ObExWZ+U%CbsqM9`C@{RX z9$Q}@J>a{dzloX&-QGn?Qz8%Q=(_0Jb*y>4fg=Yk_?D(75&-yUSI2gGg8A(qqc(l? zREllwh~-Vr%~v-nJrhtxT zN%U)~n6P$y&(e3LbS>DkOPsYsSY5u;+ceF#AjFgB`S4!v zIp@>)@PFP9XMftswXbVmd+*=+t+np8?t7I{{v4X^D5bb1iTuY4_+3NRM}|*E_Vx7< zmDUeF@x&Z<_^$9yPLM5IB%kkm%UfqYu&Uxu&0n~ncGqH$#Wg^@?RhopJKs$p$#(Sk zx9@!OAaUfa*(T&czo0O2Y*Sfeb#7>7YiN$}py`xUy@ok9iH)_K@{{^Uo9_pn-KG57 z?)rkA#?)oK>6V10REsR?W01Ii2wI*-*fC8S<@_M(brM$nAn?;f6^&Mb6KM9iw) z3dZG{i|k|o#7Q+qxNin1G-nT>SPm;j`zKy=gWNqi+%Bh#g;P4&fhM04$1W{jnb+M! zkA!4%XrL|H%m(W2XsV4JsRF&UfBM9l7p%o-m&wO0=>bupC-R7ftknJgwgF1V5YUb7 z`|-5-h39|5+ugqoR~;S&7eqe)V)wCGy*{X!Eadhf0V~CAPxIb=89#9!(=nc*(z$mW@&s}l^#Vc zTF=k1Z+1PlKfrAJfr4JYgh^dWSGechsg6A+4-0&YvxvGMIU|R;_i$2W9nGv+EpA3S zu#cK^3t2FgGQ4d+!1k7NwZ3kKd@i;rvnZ38ONDl=_}bxq!b0Z?((s#biMXZ4ij+sI z99{fRd`J2GW>`H!L_)s447VCpQua&n52a`F)~Wz&XUU-B%oG*H%WC!>uo zg0o83)rrauxzhw}k)osRkcv-VfJ1!zq}#J2E~z>g_iZJwb=B1ty$7wdUh=~sVjX&y z{GN|iedinVQ`bj;m5W6x5@qwY7fo(C6b}uQF*S0M?s8UXl_y2|-}#Jtn={y6%95jz zeM7!ZYCmzUcEv51PxRpXGXVp22oKP@&VA?mHGGDh z^@KZC`TBbO`H(q(SfjBlU05hOaC0n1p$R>41ar zZU0MfD+M{oR7&Wxn-GnSnK$BAPN*zyMr#6(6fW<|Gd4XX*|&baQ+98>akTGzu{k`@ zFEsI5*bL~@?-5GE(0g89LyIMt*5IWTCNRUhU{DvVV@o-3{ExxGk58jXCe--#bv977 zFxUjy#y&v1nEcmWo$?rM{S@(W*x=lk*y>-t^IfWxesafCJLXM=J8U56rTj$yvy--z zfA;czOO6rR$1oBF8>8xF|7_h>usyjUJXNsJ=;+;iem{=7Cs{XD-9Hh~uC2qo){({V z=x-~F40x0tmHVi9=BEJPz`dP_`RDUA$A|K;*{BStWr9&(Z4QgKOew16lbWT~ZC*Ai@5G7r9NqaFpYF=LQX*NWxz>Ugc$fzw1q zo+lQHpVZS~v(L9h@F#J#M|TGF+iG7#%(Ahs91_(PWA)YC3u?SiT^=SHKP=3e39yrz z$eteBoU9FPKU5sNnP=;=T2^R+LCH=LN1ZSm@pJ(JeF4E*`1MdKz7%TKZsa{IqleHJ zO+S0-KM9FSr-YUaz|58xr%98^)eh@wi~9r4v%F=@_pfh}W8BdO<-Pxh<01Yp$HU7M z)_{}y7A{$dL;qPJKlH%S>zw&035$?|mZ&^k15wg1ip^N5*cv_Wo<_%Je#MaVynl8x zLC?Esgm*ogErIzRlcWwdXZrp|b=p#>Sa$R)e!Z07l3aZ&Vq^a5rWs@R6-B-Vd(O+b zbZ$XH@JvX{MU;vsm2w#Xwgy#_)9}=JvRS)r18+wgvBC*l%ReZU0i?(%`3rx_Ka$H_ z_f;d10&YFr81cyd_cQ%Bk8_f#1|_FI>vR3}^kl!pxeCTyl$6I7AP|NNi|yW$X3(RV z)PxB+}RGC^+0?rG)3X7GLU^aj#9Ew8X~E!umSUT1m>R9O0f zX0_LCEHuN@2T+tNuWqY5BKM{*4PUWm4(?MWt4Dag*?<$BX7#@Cx?x|hG#n}iDmdA_ z3A|vm>($}U@{i9@aagj=UXysJvTfH$ORWu1`W!`TYEp0n?&E zbqs17w)(sf7YWv=*L$BsPD>Xq#X2P3Vk;&5=ZpP+-GYD6r!*XsYr)vWdH@CO0=3<= zyyk<48nQPWaJsasckJHEVaf{jh{;f~gsR|F?4$Jw1Ld@aa^FVft7Td_c<;wd0iST?d_Dw$_5Bg@ns?UibPoQ!cE-FO-SH$W?tS~@9MHPjqYJ~XaO;m zAwBrgWT~j+pa15f{?EOD*V|bQCuyN%$43C%TR#KhG71nmX=`~ujSTlv2aP@6rOvwM*TKt!fyUkZv zXyw`wf=732N-mQn2?(}cIvt;EN`mwJ({5VoR6b}D<(`k4BwsGeL$0DNJ3>;Q4+mZn z0I$_CRdj73?!M!4kuzs4*Y*8O$?1%CfX>*?*4o97^qf)l#f!YEPJRa3s3Pb9`)Kjl z-!lcChL<{yQ=9-}Ah{93XmsV|kkz@B_qXaER}?DQL9 z#3~*ArdxkcF1CIt-)5j#Txsm{tnN?>d{91Kt$hHh&X01p)Zw1Xr8olxznDMDQex^) zdge@rOvWQ6wB;kRb2_3%QjXg)1PLR=Q)`09=IU|LA=hQeH9nb;f&*SD0A^Gi6KUQA@VYjS5ww+6qU4)`_wQV-wjx~!=f=pEyO49Dim^rUl zc)(h9?=PsBaqev)tVcM$Q|07*5lUEBA5A{2Z&sIsH*B{ui#sAZPVvkEiesWlTj1(J zE2sxjNTMTOKRS(OGJR9a%g_J8dn5n#gYD2KCG6S0ct=-C`r79|_wXg?^sh_1EY*hm z3{&g6jDUsewi}uNZD2^Z$Wk@+jd7Mu#kaLPYx_F+x%w`JL%tD#F5`Rdb>ZNw66#1@ zge62yuM~tC_J&RR9_#z(N!6Nu;-R?;byXG-00UkeE`(h-2z;K6asx(t9-Rv``F*lC z!1=b<%1+r#pl2gc0#einkFN=x8q@A?>wlyju#$MADmcH(z3W>*Xb1R>)?`Iq&O}(5 zrpg{yANcd8pozcFT=oGLHV(nh+piA;0gje;pc=_Va?IGf?Upr=UcX%L$=HwEO3bsC zCPEvB4lXwH4w`i^< zcUNJPm34{Si_l1{ClIV$+CSAVIdjnx>JvddSk)MM6uePfr}RfF=!DWMR&XUtatZau zsw`;mi8txRTKmDRew>UvJ1;vx z*=Lr^a(>IiK-B18AUh`t6yIq33<* zrJ*ghqXqM$ zbrzO>f>b#rgE-h2m2$U=12PD28pJDF7p{tsYh>*fYk8Fq7Xb1%Wc2f0@y&ojp; zd(tDsDWf{NgNJk8TYrXic+1V&fe zJ$|CVdZ)!fRJZtv$MI#2lL|G$e4b+Obbgeek`5(LTiUv~-?@203lRlQn2cId@sYRG zS{Mv)OkYs+U6Q_kMLkh*yC;9UY;?As=@j+gth4^Qludq9%vU!igH%D@dGj{t+)L>= zNb-#;@~&-j*GQ4gb_|mJqjf#GD2($wuvwqu%+?nqd6dtL3f5G6IDPq|ub_K%o>g7F zq`(nWZ0d(KDH??yhVAc8$18G6uxl&!R2A3RRna%|Gj)#q1sEf@oCxp?EF5c+AIb`>=rY<;m0dFghk36 zW6a0?3eB15P}d}${4twqN>&jn1bm3wt=w!`)9D2s-`&2n{lAS*y!TFxqp&LYUzGBAjlY;o#eKQL3I&%fql+vWd&Nt6 znDr)esuz04NK8H^OdqHt2%es7zCOpw89hM#6Bts+D_bk1GmZ7A1*bIqAF8tK^kvU* z!%=h60pD5>Do3GuuG;s*)2^h|G$|Q?03|(ph||to!#nCd@zYKa6F;Z417?^l`QFw> z;>0y;98znnl<=q1ul3u(bgeRegUQ9olUo^G5sB_;+z#;gX-;Sv;9c;sl_BT&Rk-g9C@!M)&%`tx49#2T))M#A$)#MRbhPRX(2cr%B_K>&u6)VJ&bHSx_!kn% zt2pnd49Bc4JM`7-7v1OlYtq2@o9C)PNt-Au&{eA*W3vtrJmrYoJ&4=MUcGh6N!}8P zT?%$Qq3p#BCAY@s9F}NzIz8#&D3`m3DE+oTlug`EvhYKSmOmG36?{DAEo(nMI=XWt z_V|x(Cn{m!JD+^PTESFBMTJk8=t4_CHj5pOmYzQ@RBx{xI2^1POgDfA=(4&qsr5q) zDFI1eaaPS?VBAslsn#(OX8-TxVi;Q#g&coL_)2#In07d7D3?k{VD zMFTb3wSIF|_7lZzR?8`mIclAG8jkXx12bt!UcW8db^t-&LeF zvK0SeF%^gWG$h8o9Tz6yI2Dz8u9Ut|i4XJ7LAbSiByn|Bm$fzy90J+spuo|pfp$-h zVVZ8Y_Rjulw}kKZt!E_L`G1|kzofy+{ciXkTi^ED9n1M?UBVnv-Br7noi6L>@73We zTAeU6dORN`e^lipia`nK;dff11*Oc(bqfCZ-yZ3|b1J($4_%30>?<6%~QCSjo)spvlVq^-;oriy?rEa})S)j`z zS$&UGh4pRlD-(!XcbOyF$@}O;s@&56FEhp#BOA>>Z1+6hdG)Zb@6=g9V_vMeug`Of zTq7f6kdwT;9i^|^`JJyr(7fkq7j=#Bd|U?etkyhX3g!=-RLLqf1nEOl88DN+jH$R! zB)R7$hCvvqj*Z1*0{_sYoa`0aiS9Rc70JP+wKRTrrYMJQ?TF?FLT8_=X)I?M(!4U<&E5?LjY=d9bK(@9)*ZiBXkTma z!x_$8I$T{Ku!?6Wo!0>+^ESOI7P}(bo5=nGjw~J6cLO!UeuCKIPPZ0z8Ns8E4ZtGS;5i9Gkq8_lP@iUA1BAry8Et0W*_(aIm|C@$HC+N%t-L76Y~E-|x6MZmjdC3Bhb4Yn(z;-O>Qfh-FcC z8(2sHn$Tl-zbHh1s%&BW$L_MI87JCuu9*OnK9yY9(Klk zF#5vY(mX@mUTQJLqG02PRh9R*I zuM!v~?LIQf4$Qd8nAc_H?Hn9AYMBhqQrOj)h^HSh!`top*Tpr&yv#we#^lh(>J(cI zu;$0l-5>C_p(c>h+&yaTRqKu$ey{M#DOBvbdR>HBXeM@DxU_i`b^a-6(ZKb&STKL` zwu|Jgqt~qKe8}nyZGfz;S`&(nqmW%Tow4R~S^(hcE#MVu0I8Z6HJU&k z9RrRsBNG?$4`l7umCqzE`|IE!I&7Z6i~ZL*{1wMBK(~Ab`|Oi8BkOaGwr|xR?ax?? z`aJ4kbYpT;O-)g6c!2?sxP^ehc3|9`R%l^8}{+7p74+j!tN~YV(Lw@Ct%$4Pr{=%+1f|_-cW~xTSf3+FYMRr zg0oUKD+){3({PcFM4_kYjQtV($Ye|_=o5&&!-#3->ib^gh0|GYfh(UmvRk_jIi#{~ z#vXdp8DwDqpofG+bnL#E0da^(9-u4vO1ZYRz7=m$rWJ4X^oR0Msy#v!cU@CXU7GC9sRZow)uRsWJy}`!V&W ziSs&6Vo~AC*W~K)^#z-1jBWE5n=Zvq;GK>}7;q=e$bE3?edDiL_b^q`B3sSJf9&2} zlYTnXXseHoyDRnRWwMmW^k*%LsvNI>Z3es6x?dK$-)eBFRWv2DKbAN1AxSyKjy<-7 zbCpOxx(oI_wy>=W3wX|1DL^l5)20b5vCT)9ZNXIfn&EyW*^-#Y4%ke=bgY5q{~B5e z)JWzs5Z7_JO9cd5Y#M#+{V*p|{ui$@_gO;Km$SFcG8>g|N;WK}0e&%0BA*IH*6KJ^ z8Vu-^8Yo@!CK6!>WRhizpVY*u3ksA@(!5q_)mqlPNJtud<3&H73Cp{z6Oil`k5pii zM25yA^9S8N>nh)Ro;~%p8odU-f_-K2$OPJ9MM#KO0XO@0Te2XTno;Z4W(V3)d&J%) z@X7PL?>i!r0yQcvSOv$M+mFXwF|A<3#cV8AV2+SfuX;-A-f#pIyxit>n@K2%tf)?d z;u;pNJ;;m9PAGN`utMHAKGqcN_P?6>ekvp911s05wm9up&dZV|=d>$>jnHcnEYHFR zrXO0-&}lCzNlw%<-F3l0yqFbv?7b97*~=joKH0829U2v!Hrt)uy|)-m*SHd*IN118LZZ*2(jZ8DtZC-O1wZ zr+SAU^Hwlt;%)>WcDqJ5%31!>B`tny&9z(GCd2INU#M1LEc(jfq313B3nVFh!Aj17 z?B7j^ZR=CO5!)x-)=#>hmEm2JBHR{aOt=@nD7kG=)h&lsx@{GlF&fW^i<|csDtje= ziXGiqpN;QMpmPEj1ldE}efUCKr`6;mStlmgBW205)ti^jM^7V6`A=i2>1!r8C6Isp zb1s2DW%<_-^Nijd(z*Ga7RJaMes$kd(;C4TYXd+X4wF{Dn%+L{J8@c2QOTV9-SVe* z>aIr*t|N1js`XORV`+NE7PWUfb|(FHkiQ=m!<_DCYm$+^Iqu|6sA~${YwqXbJyh~o z{NU}yZF=MA*`eYgf-VDFz3VUUxWIwjzPaxS7QSQu)}!q2PsCJejSwWve>-EX)g!y? zm8t!tiV>QorhzJyZ=0!+;ykd6K=oR>PuR!Bop7^2!!7PnmLa;ngt&FVj6Hwf%8YOR znRlGtSh>m$edoJvc0v`Gp|)?)^QpzUMHOKWa=xwl2@1XhY^Ur;BXigBuxy$>R$!C1 zO_v$GLW&o5UCcjdZkG(1y`vZQnX!b9`^uyiU)m1=umSujczd?E1Mcp?Fx9~Zr3QEu zflJOD%CTkTDPBQ_Z6YS*iBxb z)!2RpUCwsHx!5mP>jn1zw4-0srl*RNzB**q@ia|dh1Wljz{80?RU{-B!lvEay9Y-;eG1lX|mI4Mv8vi?I$ZPjz=Ob|2qK7=K78L=WWrMKyn-Y&=TOKqbeTZR6 z1Se_BW6gocXZzCzW3WE%qubD<&sFfyshuz-&l-daugVNgUAWyy&(wJ$ncd)@Ct>JP zn=XII8@?f1LZ+_wwzC}Myd;Yy_3D$kIjHl;nKM=4qv0Q+!t-5LYunLX`kAtykMrcj z4JTGC7gKN8-$Z}*sTY|X1a$M?VQ)jP;ehuWQYHHZq ztaiuPC3+ipb^yPlQ!VBXzgcnQXPw8&k&azR8i2I58eM{%yyy`*y{D4=| zFxPODU}45!BE7)V)5yAHe`4%F&?PX3g_Kz|*Y14`?2OVHrO zpno^-eM(43q*o-a(=jZx=b=nAkH>lQG@YUR+y7|h(S}YYyNDXZ>ge`Nd{fE~ZL+w#={>U+ z&*ntauj-td%pS?f#N0|>B+mfvM*9V6Rl2k_`DRZk$rOS-Cl96=dbY~aHkqmp`P{Zb zlBC(wS!6APlz~rc6cm~1Ompx(Uafw(L;xd;fXG%fN3InIR`bLTWv(T zw0!Q*yG~aq)Yd_Kknl~$icOcNR_}xHl9Bz(8s>qjcC*U9BA+O?>LGu+0^}QQmvnN? zCSAbkCm{%dxf(d=E6xb&%bc!bO=`v=k<6M(*u9j4d8B3bN9tIg&S{8FTiE(y2M*=Q{<5@oaQVxoBZQi%8S_a%=Hn73$`~gw{|v z+^4)MSo)^lAT%Uee)W!;tW~GXrYU^8@nW_E)VXuCy>iC1`dvAseWV<;UvIWJ=Dj;# zYSElfy~sB;Tph_uuYL zT`3QHcX$JR@;j~U>$kTFOSR_48aV%ln3){AwIE7e`a-P+OC)AsKI`6WYcbF34@6#Yzum3-VhCz4@p7nl6aNw3 zZ2oQ#vTBKNyiM&{OT1rH(Pn(rJj>{1_FYyoPe^Cmk=DWnwUzaHIew}y)?bp}3r9D* zdVzqXP(wW-jsPA}eRqv$&9XZRmAX=!*=&-mMY)XVys&+{`CMp}f55YG=7@)9pKd9g^L%bC>oQncgj}2Um%onIPMP?Z2&x8$>e|xSUVyEQKiw~PH&6JgH?bLa6tVF zJ7ssKcB@jKSKh?~3(5R5xxZ{Q84UUt*nj9+e2x%q8$2`q@o&OyhP%z*ymi^Km1uY5 zqHB5V*)bftQ^1+~5j)(OeiM>DO-@H_usf%%r4Ak=M5b$lj<;{^@f*VZ!EiCubvM

-T6XX>XkTFzkUd{gwQrJ+erbvG&s zlz$RhSjccaKS;;dG3R(z+{9~;+nCllp@4r&@3(E0;T9lRSXN9cx`0&DpAnPaTvrQx zIg1kAqHMe=#>5po3P)XGaVHS^zwGM{L`N|d5n{6(h`J)>L-X0?24C9}@)}sE{94b5 z{NOV7!KL&8j1MCmN-4jbm|2$9d-ax}eBl+f<&HA42FV`TkJLta!1KNL+3KRY*<4FB z6J0hWa9FY{{k4?Llkluow%0|ojKR+ty(S&mpmFmcfOL+VC5+}uSu9ECD)(`IAHx8p z8F;%cBZNi^I7U{gdO`O)Uq3)Xs$ganP1;E&p>QJ8jXJ{1Qhzn(lKF!lX}s@^Os~z= zU{<&GCj;NX!tB#()wC{#VmcHwWImH0L?*{A;LW~9c({Ma#3%mRpsvNzDwfk;ZKXxD z^R!A508h}}W!+kv^-S??DM2Ym_{8g@7di_AJBQZRA;|h=1=9{mBaQvzf{Q`KeLTYR z>wF0*x%u9;Dzm`lJ6g2xUP~W!1t)Br&C`cA&PMI~L+Mw&Dx+GQy=dx%1qeZ&KEYgM zd|AK~Z??89x<*le1cK}?Y=cAyV}e#=)-kQ-yew*)5p&G?Ed1{TDoS?CA?G_^S@(%m zuV$?9-&>4%Sqk?-;g0^jbv;+JSecEe$W5rq2hVz_)nL^;tg?_tar0tsYDoec5KV&_D|>v zfax&UQ}RQy)=4eN(XjL`7~mb`LP=8=N^X%8U6LKPbZ=F~@H(5}RORY`)0MBSr>VdL zb1+M(KzJovbBDJ523@s^>8*>X@84WtA|IXLEE@(DG{qoF@pV#59^&C4IED+?ga#2cVnUGfHXEQYi!$h8jtVYcPAHC@F z>&Dw^m_@A0lSKoBVhcDMcUa`+=BKvM;y0`(D5CY09LlcoP~hlq*($cXVmgS`pZ+&y$iQ=jG0?;dq~Jh zgrYrmZ~B%r;O6r4!@j|!?L)SF=@7DwHst!#^K4!Hdp_56-Y+?3uTeEBsS|Kze(7g> z=^f%*^LOd0Z+gCg+aKKK)I0X7GI{~OjzgcA`x%5EI3N8Hu3AEMJ32 zdm_yo7vz%(W24uEyX@E`9c{EP)CwXc|Ec5oHjQc>bN&EMB=Pe@*MXP6q}8si zuT>LFkpZoG@6OEJOxWTD1HqleIZLDyDPB zIm^-Lftq8HIfFk38G?#k*FG~>^w8czCDwyoV1@2CeI9AAw-p`t~ zA_dtrJBQd2AJt)?hF2sK-&cWp&HKb}0{xrD>)Cj3&g`&%s@>9RS<_9V6Dvx)lq1pISZ->lj^ zjsBeaRttz&sqG+y(MYEYBqaIP-$;?4iU{J30U4`1^tLPxh^^6Y?Px|`v0wvIQm2Vc zgM*tWtY%>WD|(*rm?fCWGEb+e5mq-prM{Q@1mDLRdux(jE4V%X1q$ zvyA>AhNNsVlk;P}qN!-Ylvc0*gdf>zie$!Mxf-@}(e`n;rW87&B zb?)6o$KITwv@$bhfCiOSi}VrslQw5#US+^R_S>CvJv-@g~Z`d zn*Tmre(vytx(<9bC`?(L8kUU$z?T>12w4e_Nta1+p#kZvOT3mYr&?4Npk^0xhURs~ zbI;mTof9i&gF7Sn>VDctl}*7NJ0aMhW}6lUvmH?2E=P!PBk#%ksWv73(#2Cs_wHx=lCVi73f z`OB^=O~`S=grdVk%<2S!L^?H^Q=zm)fAk_JMZmb8xzd*g&!oV1uXLJsABOr!C{sqA zO8XvYODiUXb`;R|#=FxlRcRWIxOF|{$e!^|eTGlP`(uCiGI`+aKk<_O+#Mge0d~j_ zl;ot3H8TXZQA<{0mRBq-j7CqR=?=Me3)Fy%nS$6F-nZ$B%7vquIN2dR6=o-jft8q)R}+-?~N{@eFe z)XM)HS9Mg=Hw^^qMA2ldTUX$*!v4*65_>|;=_7<>S^YF>DA7yp!o9SwUM~(xir3PTf3WX=AwGr0?TVO%L|U_{YO;n{Bqlp%9XIN#=703 zj*Nj!lSb;H;1`jaPP5LD-Z8r1@L zpgc`my$2ntO~!K#)k#=}x6#sRIs3{zd;%#Ix42DPI+Z??gls}1zTtJ#Ik!_qR6SB^ zBar0*yN=r^Dd5i~(VuIPd{Vc*24%&QFZF-6P1uxD{SuImaVgn=E~IN#LaDc)8gOmk zuVA=TfN-Qb$hJ2z*_zPwG!W2#m#{UMbciTG2Na{ffZDu;N3FwG?YE;P4JKw5MsZ#B z!uKW&{?RhVU+YQs0c17v*c?uusJvf=>kO#%p1R=LzowfS=+(Q`W<>KKDLK>YJu94Z zy(f^{&+U2@v@Om_Z-`oi^ab6HaH3^Ab6H(0bXna9ovn1#5F31hwLgYPI$+h?a)%bc zlZd!X^fi~YDjPdM0UchASi`JUV78B@*AKE@`w4DUnlL$AwGg?;ldz*`9vjf@k7!+v zA<=4|!khT_4_Nc;{sP>3-VboGbS_9VA9SNx?R|Az<#=iDl63N-4{Ih9@99I^aLb7SgA( z8Klu36Y_ikuwa|e&t0h9ZH?Jj-5=a_UuakBSjgj;>?{8GfHAE!*RMg4*c=Ppkn&1d z@wcf}wS3nGdP_{iEA=*bxN$@k0;&PSTH~zDq>IaY_$Q-cenR?+SRYF?X`z)C^_@@d zYHoqQr6tsnic@DMb7R(T5nkI;VnDl!D-=LV+Qa4M{>TIDZQQgCSR4t!H zv1tpDc2QNlD#*x9*)yc8qA>2kF4VGSK7J?RC?cSxv_ao}gh9xs1yuZ+$C;^s3*37B zC-;`$gER1w6x3nk%0HVZ$2G~^DuDbRZ9n%&u`MOcqAK*IML8Y6L@I+0Hxf?(xJ}oP zE%O(N7G5m@!_dR8@`+UWv)Z(;Ga*H4-)tdV;@CNp#we%3>QJ(4@vZpTDu zDZjNlDbN+($yyvdMs)%Ys#kwIBCI|+5jg0HdCg4(5`Z2zbc}EOqn>iq^PMl`q|%i= z^lFQjtANL-&S2%CJKJ-FnTsITF}u9^KIGT#FHO^J-KUnYb2;QE&8P+EV3P&n?T+j; zsFru*uYM?byvL`AQAewh?0$1`>t%I=fUd5|H&qXLGp;_)ALfo-`Moe*O^s<7t#8AT zmGq062u&%FrIVhH#EjfSKl$~jQnQzZFH8>a6us%Mrc$sZc_@1Ucu-!w9)2q9`n7B2 zL^(pH8t*kExjvz&El7xQNa25&=T*-Yus;qvi454hzni$}bPcIpH`q_7O(meriGM5~ z+bwV1SrfLVvZ6_l`ASZn+{GUnc|ji5sYg!r^n$g=pKXg34w2N{b%n2=C*r%^k{;P< zf5L`z`aa2%-0j;G)krDSHA$J-fAFkVD`=rxK=AHN$&p1bk8?I=#wzCip!1B!Fg`-q z@m8%WaMzfBj5Nxf2mRaj%6YaIcp5?gOV0|I@pF+qGlymJuV*I_&Rib2@PZS7I=LOK z#<3S(Lw|}+#7KRJQ2Ufjava4g=Dla$t(|B&n{oD0Yb{9D^T|s4oGmfL4#7gPezm87OQ!YLkVfxM&AO!lDe<)mE8J9S*Z0mDFk(4Y%|9h^tJJ;&Ss8I$(kzX zm&r+$YRXZt1Fw#~iW7-?Z@uLh*?A}*+O(Og6CBk&@kE8+=Qe)p0XmV9!%M4~UT_e7 zU$?%t?W3rHhpe>RXQyfhX8YD*7UbbOCd8l`M4lmtw6 zTK4%kzAWpgbJJozZ?7RYS=A;_Vg_$KY;{ohvqIatMbWnF#Z`ecG7bRk+PJbNekJKyQM76Xb{i^?(O&@9?Tj`*E#KaAB#Bg7mk1qYA_ z0c$Y@CWshi#7u<$D$tC=r6b0jB1uCqXG;pz2Tcv865|Iw==T zcXn2K&sPm6ygA<#x^OwA{c-0w7r`5a@O<+`lKrIoh%z~@mZPhxd^lLguyJ90#N-q_ zie8S!0)4iJZ2@I%0+MpLgZn25Fmo4Fd-SJSb>y#oT=VnDw{Nh^Z;zV&$7g;D?95_r z#%h;0agyDi2!%akS?EeJww9Zk8V78Gvg9w-4WxT>vFHs)CtI9YPWCR|JtoFs9q{4E z-p^v7A~LOLOdDXodYn=2&V%hhsrWby(R$O@u2P=IQy@hQb&!fWPF#7N(p!S32KIZr z4d_%}&)tY6x@Wj1I*-anae)Ye+3jKzFRPaH!;;srHeKY0o`_ z0cmybU74bY?|f$l%1>eiTV!^9JlfRisA0(0M<29WZza0-N(qXCI`s^)PegKeJk~T_ zR%6>ie`^*DUOy}QaAHrp5I_s6U-Z3-)8amCpBTeAK>A<{}u^6S+859O$R~^&LjQ;m-lSXBi$?0P- zTqDzid8xt6fX&OhUY$*?AP?+H}HT)G)s!3p%f?CsyZF|%C*pRAcaEq=H zYnpdOA>Db&y^4yGb~^%MXLj)4`F?CBpQ;6Uedi0j`kgNc_GFAC32eTA?1%)8p!U&6 zEzUc8;SQZMck}Nxs}Ol`NFyq3e8f&$gvu_!$%NTy3mD+-c_SCVbVJMiDNViouho2`uKq}LjRp6do48zs?x(8{K z+aiS~-)ib;+b;oo89@Me5ogA=yxY-=Edza?oxL^oH4-izeuT)AT#dAHgX)rdP$Gw_ zdrvUA*cPMjd@@N@xw1Cu+tSkxWee- z$k1q1kXnUHscdSMN7C}NJ8v4jO^SPZs)iiKX_N&`ee%Sbeoa>y7dFp*CA=|q_zbeV znx{lJupvcSzc}(x8o|vm2v6VkSvind>RmW`6}hO_;oxqe67F9h=@vw|6j_thq>SLM zyo<7n`C1$^imdPE3KC{1gmuuwdBN29JC{9N)KmqWavFbGlNp=7i(AGt(*I@yJs(Uq77mv4_s?#^}=^g|0pZdI{kJU4OGvr-#dI#Yt~?np@2+zoh++O_`Vp$d%4 z;!V5;@eZTjApKzu(l=y={n|LUuC-WFmFtQ2-a{@==Ql;^83FkQhTMNPINvXQ5X^o5oliI+O0Q5T zf#nu>cB9%5I@P{}urQI8T9$RfS|&EB54fiaPedgYoa)L0lUV8E$K$jEC}Dg)9FpGF zs7odyh?4t)6ubK(mNPD^%}@K*va25S%&X}dY8N!S(WHZ~ze4-G)iGoGYA(a%REfPm zW0S#1yThO`!&|j$s%vt!nPIv6s{+!4edS-uI?&i+2@9j90cO)}(pAC*&pY&cA=@LD zBZGBaXTqyxJI1y;6IOnk(AxIw@wJ)%yubezs^z!GlPle*_7{Q$#AFgnkBlGYI|N#6 z`b^3h2rd9MN8%PlmXs3}Ow5fbOjvCBP8-bO?}aV@C8dn|sZs?Gy@l8||NLOZlV7NQ z{fB=*?zg&v%W5B@9(FClEb0!5++-T9EmA8vUU=a`z+1nR9E?lD@uTS{`VfSdg#2AQ zISbputaU*H-J^(;XPUe@++&pe6K)I#UjDBJiRzleb6>=O@m`pI_Y@u5wvfEIUfbGk z=Rdr5w5PaY=k3?+4Q>t9zVrRnb5FqwR+e*_BJg*)>5aY8PrHrkUU@6k_pRT|<}D>r z#I2=cTfNYu;zi+A&#R=Z9oPYhq4ZSz+=ktT%e`;g(4(U)Qj@m%k#1nj-ZEj)bx}!4 z_*j{XiGEk#@b4r?<)EiAN+G6o@DpivV{jE<{+$mWV>XNA>nJ3Y156dqcX^acp3d?rbMN}aB(Q6ZI#}u@K6My3 zSl@xG7ZJTzrF_{+;|oYQ<^|_k`YYdZaGjqAKM{ExlhNu>W35sNmBmY_37LnLd$+;E z+3lQfsgyvy2Fw&O+7BwJhhDWU{DhDn@Lwzt2bArPeHAJESMO4JxAEXjU-3L`d1%`g zH%+o$Q`s$b3kXmk)9~p-EDd6cD{34X^XQfs;yjzvT36E!Ivzi@X9FK`mHMU}71!0< zkfWe_gxydLFzQT?{$qEY_|dS|!h@~HjU#3K1RRXhSsJWZIKzt@fT`v}w-&F*4Bw#9 z-Ze2`Yh%TDmvxU+rH&isGQT=N69U1FZu(D6>`@nZ+*;;qf51`_zFst^TW#3AlVZTz z2__#Xdjyov%^i3k;AZHdR%I0hxA8(x z!(aVh?VVRtlj*w0-OEwOf^0=Zr5#0JV<-a%NZ)%zkQ!;BgVLpi-a?s?Eg%pO0@BGy z3ndWgQZoV}K!8XKC6EY_5<*B2NQ2URUUb>2USC?mAOAoa9$NR+5_igSI&x~+~&52SC3w86^%SJ6BAT2ICn|!-X?YX=3MLi&Qa~%#wkP%9px075mbk+qj8dt|uiY z(c)qgc0jE!m>95qPEWKW86!sapS&hT65zaVz$qEQ(r?SRjz51Qr-PwscKY!PHPs8L zU1vj^)nz?Y#3Z(F@79!6VDhoV>`iHzfsh;@r%r{JE*T09Ae4*ruL_jx*&WM}ODxak zneAV`kbDz^>6E@mLFH5ugf>V-b04DefjJ{yFS&i!?{Sj)Oyc1?D3?W!eAyuspVy*i zo|0h!w434HuUnixsvHU1lKYD4F&rXh){j&DNyuYufPH{I*LfV7WaYRgTZ75)lGDW~ zy`%x*BL@6a@0_diJ~)vaS>Jt+%luh3#OC?Eyh#x0-uE+Tc9X}N?G$;&cfzd)JpIcl z#xVM3HtG=h*Ur>A7I30S?xWO6uc^lHlqh-PnaRK$mJB@~ec?1kh0gyBdw;Xg7`2|o zU+>dCd7uH@ZY+Fbb&Y3__Dou?{D|J3<9|Gs70P~-oCJPK9*p_ju*U6K#avPjoTYT! z`fBzxH-$wz{=Cd`Y8-2VW6#zImDWn3yVDfBF8d-R4>obdo6TBNooy71kJn0YtxL?X zeR<1C`=}?|BHQ_5W7WH-H0P=pbnoajhZUa0{A4W>JYW_HkI7H;@FXm(mFZ+!5pCt2 z@e8W^WO}5q5Lwhcj!DD^tNK4GyKpZoiSJv$U&z$NiPe4XD8&A{Gsn^o)XhFHNA4#7 zYKM9_cCLreh!t0|D?ZvW^=PxN!Za)gtD8IUrlmYU`+MZZEmI_}rZ@we^ltwRoNGmv zEdDp~^nrm3Zuw7#X`aL9$N(Yy^Xg?a@vHpuuX?YcA&Ld2op)mIM1FAm+25xY)45{5 zYefqiY&24mji*$f*@GWF%Jl=FnB;+XSWaA-f$rHP4GoJl7^==n$ko% zX&)sU&juGVA(~=hA6|rDk28zPChu@1qG}V7dF4g!@Q7LRN=mzButpJ0WM0cD6Qtzc zq8rR)b-d?HHwXw^k7>dSg7Cbn1K()Q9PyZ^ESyHZ?2?{TSW02r!x^ttjyOPBmUttJ(_+znRFHEqJFiE|iPP{)Bg(nylbifT zvQPAXL0 zB;Jb}kpYjb(F`PMCM!8d(l@1g>Z05X9h)}G+WQ)#9(aX6dL!e=S&*-uZc#jXMA&@& z)AVc-^o~=Ms&odg0}beL>TzU>xLKi+Uzm$*q3Br;If+y4XIRj(L$0A z_V?(!dyFo8Cq1)V{GfJguFF!wbW)HCxgMlUdixc% z+{Qo|im4jPL(V(XqkmGr1T+|!`)TT|<6si*YER@x4Di1D^w+pF*)~sX-r|-7NlzY2 zVZx;vJl3_QL0tbbTtAuMyM{*A(L`(v%XD~COsvoMYz~h<4*y(>kjD-t&Z3vPrrs_*{eDIStQY2951omx zTF**;w(t4iUnbI{9LWp=!>^`0An1n{qEE~k*eiM>tpEw0smc`9t9X(}q&p_SdUUle zVIh_+9`nE~LOd3Wcx56iipy?s{mA!@jj4==qhbrZw~{j;FL8k}s*+lV*vG&nW&6Ba zTJDZ3u%HxSMWo{lMjzmUvCcmFIB&miFk=5XZjoGW6CGC-12Pa1G0ex2(!Zrs4d^Fb z(cbF^{zXHXy#^5>y%0(W+)PCxcgz(xC#Ys^#7sTL(-YcoC*>dh9HZkTxCyLet%5d5 zJ$I3FY1pCVTQ;UNdo0EOlVtq^qUSqKy(Pnk)X z=vU;Q1Q@oGCBFc)DgHS6*de>{Fi5(^qb2Ub<9-xn-Tic%uJVPBAt!%7180yO2(Af$ zLx2AN+I2xsqU%Jlp?)53E%fBXA##1|L1F{Rayqw>t>V{xgSJlo?8&d=FZf+JEmhg& zGs`}m`S{QOq;WrkU2v_qo%j#VZ_gVSHu;(uA;vW`vpXo2Z5H6UHo&cU%lv+1^5rqJ zSWO9W-**mO(gjV?)mANv1r*c^nzk)s-gg!_+Ia}y!KY2L>pSjP=)m#K3+Yt<{qJWg zNMpunxu>F2;fT`CvM2M>H-h4cUm@G*TtT10eDc#JbYB!5gIvIW@-^<7o@rrL&5Mrx zfM}oK5;6$s?pCEk1AeDgxqfm(5MHbWqd_GiI_!;9-vIQY%1$s1hd51HsE^ksML-nfa#2_x<906jQ? zX`6e8U@94;XWJ;nD2Nv0x|6c{+=Kf(v8y>hGm?c3Yuy$<8W|05;7DwcCU0vm-OM~C zRysXCkm7pb@671eDU=F5LJ^Civ3o@&2;B0*nO1C3PO};F(<*I~v1Xy%N+9o~Dqhyc zSJ~eK=W$iE#zKy2lyW3hZ4}JdfJ?nRe%dg{yyf~p&A=V#0bD0-OF6V=zT!P{ZsXMX z>s2$sF}of#Wi@q4i0D5a^lUxI`!4B4FqMXV`?Or$6WXe1#u_2<^Zdj_YxV4~J94Xw z#MpMD$j82G(YQi6$H{BtQs5@uax0l~c)awQS;nMJa)Lrp_x259^7ma^yy7-)cVCwv z$bh=*KV`oP209aF#bg1+y;E%uOn*y2Ysh-pD^?{r1MER*PW4cGYAhRdGa*&ve{aKn7k*amVm%HR+tw)$I-+z$Jx(E0$eIu zca36saV5&H985c&s9Cgj*X6HZp!VBM4bwYb=I_F-v>XnN5!>%94D+6%xh-Jrh0a{U49XH6}iHy zDT|7;sVR6(GNs{#GBhcHPT@$p*R}FR^^MuD42mF2D6*ytNv_Dw;w3m|B~BDDnMM0h z!9}qd06hc~6=AQR!9KdN1Idh*G&31+jfgY%AZiF@S6js+Bb$3|uv-9cZ|@{K7u6cO z;>iP9N85eV_^od z6>Fpb*24&DtgyqzUym=^v@05A{JcmoCR7QyvLCv^G?fIH4XyD>^0!pIFpqo>EP2Dj$p#+yEO$gI*&y(1*0kfms%|fze_NOdW%e)XscVoz zKlyP}F5|!(6Qs;{jb6fa?sG0FA@Ik(2t^TWjA0^JCno4hgzG%?RzZQN_4IfiG@5y)!&bjM)oEAX-2QON zlHi+idCVC=@7>f76~9C%=v195PWVO%|NH8Q#p%qLwXb)08yeVvL$punCKT`IC=iM5 z-_J~2*3GQVjVuAaRSiy4r15Qo3Da2{hOfbe4Sq_xuXSoD38x+RbMmtE5DmM$?C^Xm z_ua-2LXA|&fQ@k_%jHUH$vaFzgC;m#)eN&Z=dO4XO-q4u*$M+k*`g z60co~O6NHBbeF7H;EzOR->GF*2ROE*xm!#*XUoRWb5aXd#U;kR8pqfLB8@ZZpbi~k z6YvPk2Vg3IAuYVlIkAQxJDW@z4&JWac33;2s#ovsiRWqC%0$$YoClpyZwJXMOgm=T zOQa7#8wMKv!dWT|X}epH8W~a9R@k5G4fX~B>=C}2qt5~!y$d4C!Sj&V!YyDv!!U%b z)(ad8T`THf<6?^{(4`_$VN&|?%lKUBcF1)X6ZeY$f?vF;LD))*v5-un&TBNs&)$bU zAAGFm43^)4fj)f$6&{>0-d)ig=Gk_V?jAg)%8rm}Ns6+ff*u~4286}Oc&d38!S^_cb;z=NeER+-6me9A zn!ozKK0#6cnE?5o3E6S^J!(Z}Gr%2PN72317r*>;wFd0TOU`}RK9nrd=z;= zN@tLdnkWZGkvUx?oczHlnw6iiac&2e+7xwdHbys8L*npG$CT$flmTrFdbe#}(DVu( zwxIH*5(k84%qgR92>0aa$W2}!&26+Xe!zvbiSpfD<21?h%Sv5?o^Ek1ycH)^Mpsgs z_=%Udm0^?lS3%1;j_1I?;+M?0QhXBTvFpeGhah7m#Hk--CK1;vfdmvv< zul1Iucy|xG0{;l>Z%S=aP%UVKQR4^H-3kHcbzIbSvNWZ0BAZ^%jBn2v1&kg6)dn}v zNF40GNwkW(F3{sP`P4Mat}J$cwx6_TWPB=ht!ud{a~JJEW=UV2i`KK&6Y6CAom3lm zz!Iy2f-~!eMwV;;-7{sI-3obvz&CqG17^GnWo?72hciH%lt3@;gC^&lhOM~V>*l7z zGM1V1QwnG|p4Di-hj6)-;}}i16eNQL6Xa(~kY*+BRY`FZ_``_9je=YwP(nVK( qiHG=q&U*PDeSSQDDDXpp9}4_X;D-V~6!@XQ4+Z{H3jFQ+(tiVmB _instance; + + const std::shared_ptr _io_context; + const std::shared_ptr _logger; + asio::executor_work_guard _worker; + size_t _pool_size; + std::forward_list* _pool; + pid_t _original_pid; + mutable std::mutex _pool_m; + + void _stop(); + void _set_pool_size(size_t pool_size); + + public: + pool(const std::shared_ptr& io_context, + const std::shared_ptr& logger); + pool(const pool&) = delete; + pool& operator=(const pool&) = delete; + ~pool(); + + static void load(const std::shared_ptr& io_context, + const std::shared_ptr& logger); + static void unload(); + static pool& instance(); + static asio::io_context& io_context(); + static std::shared_ptr io_context_ptr(); + static void set_pool_size(size_t pool_size); + + /** + * @brief Returns the number of threads used in the pool. + * + * @return a size. + */ + size_t get_pool_size() const { return _pool_size; } +}; + +} // namespace com::centreon::common + +#endif // CENTREON_COMMON_POOL_HH diff --git a/common/src/pool.cc b/common/src/pool.cc new file mode 100644 index 00000000000..ef92c077e99 --- /dev/null +++ b/common/src/pool.cc @@ -0,0 +1,173 @@ +/** + * Copyright 2020-2022 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#include "pool.hh" + +using namespace com::centreon::common; + +std::unique_ptr pool::_instance; + +/** + * @brief The way to access to the pool. + * + * @return a reference to the pool. + */ +pool& pool::instance() { + assert(pool::_instance); + return *_instance; +} + +/** + * @brief create singleton + * must be called in main only + * + * @param io_context + * @param logger + */ +void pool::load(const std::shared_ptr& io_context, + const std::shared_ptr& logger) { + if (_instance == nullptr) + _instance = std::make_unique(io_context, logger); + else + SPDLOG_LOGGER_ERROR(logger, "pool already started."); +} + +/** + * @brief unload singleton + * must be called in main only + * + * @param io_context + * @param logger + */ +void pool::unload() { + _instance.reset(); +} + +/** + * @brief A static method to access the IO context. + * + * @return the IO context. + */ +asio::io_context& com::centreon::common::pool::io_context() { + return *instance()._io_context; +} + +/** + * @brief A static method to access the IO context. + * + * @return the IO context. + */ +std::shared_ptr pool::io_context_ptr() { + return instance()._io_context; +} + +/** + * @brief Constructor. + * it doesn't start any thread, this is the job of set_pool_size + * Don't use it, use pool::load instead + */ +pool::pool(const std::shared_ptr& io_context, + const std::shared_ptr& logger) + : _io_context(io_context), + _logger(logger), + _worker{asio::make_work_guard(*_io_context)}, + _pool_size(0), + _pool(new std::forward_list()), + _original_pid(getpid()) {} + +/** + * @brief Destructor + */ +pool::~pool() { + _stop(); + if (_original_pid == getpid() && _pool) { + delete _pool; + } +} + +/** + * @brief Stop the thread pool. + */ +void pool::_stop() { + SPDLOG_LOGGER_DEBUG(_logger, "Stopping the thread pool"); + std::lock_guard lock(_pool_m); + _worker.reset(); + if (_original_pid == getpid()) { + for (auto& t : *_pool) + if (t.joinable()) { + try { + t.join(); + } catch (const std::exception& e) { + std::ostringstream sz_thread_id; + sz_thread_id << t.get_id(); + SPDLOG_LOGGER_ERROR(_logger, "fail to join thread {}: {}", + sz_thread_id.str(), e.what()); + } + } + _pool->clear(); + } + SPDLOG_LOGGER_DEBUG(_logger, "No remaining thread in the pool"); +} + +/** + * @brief + * + * @param pool_size + */ +void pool::_set_pool_size(size_t pool_size) { + size_t new_size = pool_size == 0 + ? std::max(std::thread::hardware_concurrency(), 3u) + : pool_size; + + std::lock_guard lock(_pool_m); + if (new_size <= _pool_size) { + return; + } + + SPDLOG_LOGGER_INFO(_logger, "Starting the TCP thread pool of {} threads", + new_size - _pool_size); + + for (; _pool_size < new_size; ++_pool_size) { + auto& new_thread = _pool->emplace_front([ctx = _io_context, + logger = _logger] { + try { + SPDLOG_LOGGER_INFO(logger, "start of asio thread {:x}", pthread_self()); + ctx->run(); + } catch (const std::exception& e) { + SPDLOG_LOGGER_CRITICAL(logger, + "catch in io_context run: {} {} thread {:x}", + e.what(), typeid(e).name(), pthread_self()); + } + }); + + pthread_setname_np(new_thread.native_handle(), + fmt::format("pool_thread{}", _pool_size).c_str()); + } +} + +/** + * @brief set pool size + * it only increases pool size + * + * @param pool_size if 0 it set size to max(nb core, 3) + */ +void pool::set_pool_size(size_t pool_size) { + if (_instance) { + _instance->_set_pool_size(pool_size); + } +} diff --git a/engine/precomp_inc/precomp.hh b/engine/precomp_inc/precomp.hh index 70fe1cd993f..0b573db6565 100644 --- a/engine/precomp_inc/precomp.hh +++ b/engine/precomp_inc/precomp.hh @@ -38,6 +38,7 @@ #include #include #include +#include #include #include #include diff --git a/engine/src/main.cc b/engine/src/main.cc index 2581b42c043..b0171ca7648 100644 --- a/engine/src/main.cc +++ b/engine/src/main.cc @@ -23,6 +23,7 @@ #include #endif // HAVE_GETOPT_H #include +#include #include #include @@ -39,6 +40,7 @@ namespace asio = boost::asio; #include +#include "com/centreon/common/pool.hh" #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/broker/loader.hh" #include "com/centreon/engine/checks/checker.hh" @@ -73,7 +75,6 @@ using namespace com::centreon::engine; std::shared_ptr g_io_context( std::make_shared()); -bool g_io_context_started = false; // Error message when configuration parsing fail. #define ERROR_CONFIGURATION \ @@ -117,6 +118,7 @@ int main(int argc, char* argv[]) { // Hack to instanciate the logger. log_v2::load(g_io_context); configuration::applier::logging::instance(); + com::centreon::common::pool::load(g_io_context, log_v2::runtime()); logging::broker backend_broker_log; @@ -442,20 +444,7 @@ int main(int argc, char* argv[]) { broker_program_state(NEBTYPE_PROCESS_EVENTLOOPSTART, NEBFLAG_NONE); // if neb has not started g_io_context we do it here - if (!g_io_context_started) { - SPDLOG_LOGGER_INFO(log_v2::process(), - "io_context not started => create thread"); - std::thread asio_thread([cont = g_io_context]() { - try { - cont->run(); - } catch (const std::exception& e) { - SPDLOG_LOGGER_CRITICAL(log_v2::process(), - "catch in io_context run: {}", e.what()); - } - }); - asio_thread.detach(); - g_io_context_started = true; - } + com::centreon::common::pool::set_pool_size(1); // Get event start time and save as macro. event_start = time(NULL); @@ -522,6 +511,8 @@ int main(int argc, char* argv[]) { // Unload singletons and global objects. delete config; config = nullptr; + g_io_context->stop(); + com::centreon::common::pool::unload(); return retval; } diff --git a/engine/tests/main.cc b/engine/tests/main.cc index be22daf9825..b19121fb531 100644 --- a/engine/tests/main.cc +++ b/engine/tests/main.cc @@ -1,29 +1,29 @@ /** -* Copyright 2016 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2016 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include #include "com/centreon/clib.hh" +#include "com/centreon/common/pool.hh" #include "com/centreon/engine/log_v2.hh" std::shared_ptr g_io_context( std::make_shared()); -bool g_io_context_started = false; class CentreonEngineEnvironment : public testing::Environment { public: @@ -51,8 +51,13 @@ int main(int argc, char* argv[]) { testing::AddGlobalTestEnvironment(new CentreonEngineEnvironment()); com::centreon::engine::log_v2::load(g_io_context); + com::centreon::common::pool::load(g_io_context, + com::centreon::engine::log_v2::runtime()); + com::centreon::common::pool::set_pool_size(0); // Run all tests. int ret = RUN_ALL_TESTS(); + g_io_context->stop(); + com::centreon::common::pool::unload(); spdlog::shutdown(); return ret; } diff --git a/tests/bench.py b/tests/bench.py new file mode 100644 index 00000000000..b3bdd7f3e50 --- /dev/null +++ b/tests/bench.py @@ -0,0 +1,259 @@ +#!/usr/bin/python3 + +# +# Copyright 2009-2023 Centreon +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may not +# use this file except in compliance with the License. You may obtain a copy of +# the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations under +# the License. +# +# For more information : contact@centreon.com +# + +import tkinter as tk +import matplotlib +import argparse +import boto3 +import os +import re +from unqlite import UnQLite + +# With the following line, matplotlib can interact with Tkinter +matplotlib.use('TkAgg') + +import matplotlib.pyplot as plt + +from matplotlib.backends.backend_tkagg import ( + FigureCanvasTkAgg, + NavigationToolbar2Tk +) + + +def download_from_s3(file_path: str, bucket: str): + try: + s3_resource = boto3.resource('s3') + s3_resource.Object(bucket, os.path.basename( + file_path)).download_file(file_path) + return True + except Exception as e: + print(f"upload to s3 exception:{e}\n") + print("Have you defined AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY env variables?") + return False + + +def list_collection(database): + """! try to retreive the collection list in an unqlite file + @param database unqlite database + """ + collection_name = set() + collect_name_extract = re.compile(r"(\w+_(?:engine|broker)_\d+).*") + # one collection per stat + # in global db, all collection row are object where [0] contains a sort of collection name + with db.cursor() as cursor: + for row in cursor: + m = collect_name_extract.match(row[0]) + if m is not None: + collection_name.add(m[1]) + return collection_name + + +def extract_tests(collect_list): + """! Build a tree from the DB content. This tree has two levels, the first one + is the executable *engine* or *broker*. The second level is the name of the test. + + Args: + collect_list List of collection returned by list_collection + + Returns: + A dictionary of the form: {'engine': { 'test_name1':'collection_name1',... }, 'broker': {'test_name1':'collection_name1',...}} + """ + engine_broker = {'engine': {}, 'broker': {}} + test_name_extract = re.compile( + r"\w+_(\w+)_((?:engine|broker)).*") + for collection_name in collect_list: + m = test_name_extract.match(collection_name) + if m is not None: + engine_broker[m[2]][m[1]] = collection_name + return engine_broker + + +def list_origin_branch(collection_name: str): + """! list origins (develop, dev-23.04.x....) + @param collection_name name of an unqlite collection + @return a set of origins + """ + collection = db.collection(collection_name) + return {row['origin'] for row in collection} + + +def list_conf(collection_name: str, origin: str): + """! list machine configuration (cpu memory) for a commit branch (develop, dev-23.04.x....) + @param collection_name name of an unqlite collection + @param origin develop or dev-23.04.x + @return a set that contains strings like \n + """ + collection = db.collection(collection_name) + selected = collection.filter(lambda row: row['origin'] == origin) + return { + f"{row['cpu']}\n mem:{int(row['memory_size'] / 1024 / 1024 / 1024)}" + for row in selected + } + + +class App(tk.Tk): + def __init__(self, tests_tree): + super().__init__() + + self.title('Centreon-Collect Benchmarks Tool') + + menu = tk.Menu(self) + menu_exe = tk.Menu(menu, tearoff=0) + menu.add_cascade(label="Executable", menu=menu_exe) + + self.collection = tk.StringVar() + for k in tests_tree: + menu_collection = tk.Menu(menu_exe, tearoff=0) + for kk in tests_tree[k]: + menu_collection.add_radiobutton(label=tests_tree[k][kk], variable=self.collection, value=tests_tree[k][kk], command=self.collection_chosen) + menu_exe.add_cascade(label=k, menu=menu_collection) + self.config(menu=menu) + origins_label = tk.Label(self, text = "Origins") + origins_label.grid(column=0, row=0) + self.origins_list = tk.Listbox(self, selectmode="SINGLE") + self.origins_list.grid(column=0, row=1) + self.origins_list.bind('<>', self.origins_list_changed) + + confs_label = tk.Label(self, text = "Configurations") + confs_label.grid(column=0, row=2) + self.confs_list = tk.Listbox(self, selectmode="SINGLE") + self.confs_list.grid(column=0, row=3) + + update = tk.Button(self, text = "Update", command=self.update_graph) + update.grid(column=0, row=4) + + self.fig = plt.figure() + plt.subplots_adjust(left=0.22, right=0.98, bottom=0.1, top=0.99) + self.ax = self.fig.subplots() + self.list_com = [] + ax_origin_choice = None + origin_choice = None + + self.ax_conf_choice = None + conf_choice = None + + # create FigureCanvasTkAgg object + figure_canvas = FigureCanvasTkAgg(self.fig, self) + + # create the toolbar + toolbarFrame = tk.Frame(master=self) + toolbarFrame.grid(row=4, column=1) + NavigationToolbar2Tk(figure_canvas, toolbarFrame) + + figure_canvas.get_tk_widget().grid(column=1, row=0, rowspan=4) + + def collection_chosen(self): + self.origins_list.delete(0, self.origins_list.size()) + origins = list_origin_branch(self.collection.get()) + for i, o in enumerate(origins): + self.origins_list.insert(i, o) + self.fig.canvas.draw() + + def origins_list_changed(self, evt): + # Note here that Tkinter passes an event object to onselect() + w = evt.widget + if len(w.curselection()) > 0: + index = int(w.curselection()[0]) + self.origin = w.get(index) + confs = list_conf(self.collection.get(), self.origin) + self.confs_list.delete(0, self.confs_list.size()) + for i, c in enumerate(confs): + self.confs_list.insert(i, c) + + def confs_list_changed(self, evt): + # Note here that Tkinter passes an event object to onselect() + w = evt.widget + if len(w.curselection()) > 0: + index = int(w.curselection()[0]) + self.conf = w.get(index) + + def update_graph(self): + global db + collection = db.collection(self.collection.get()) + if self.ax_conf_choice is not None: + self.ax_conf_choice.remove() + self.ax_conf_choice = plt.axes((0.01, 0.01, 0.18, 0.2)) + points = collection.filter(lambda row: row['origin'] == self.origin and f"{row['cpu']}\n mem:{int(row['memory_size']/1024/1024/1024)}" == self.conf) + sorted(points, key=lambda row: row['date_commit']) + self.fig.canvas.draw() + self.plot_boxplot(points) + + def plot_boxplot(self, collection): + commits = self.prepare_boxplot_data(collection) + self.ax.clear() + self.list_com.clear(), + list_commits = list(set(commits.keys())) + for list_commit in list_commits: + self.list_com.append(list_commit[:8]) + self.ax.boxplot([commits[col] for col in commits.keys()], labels=self.list_com) + + self.ax.set_xlabel("Commits") + self.ax.set_ylabel("Normalized Values") + self.ax.set_title("Benchmark Data") + self.ax.set_xticklabels(self.list_com, rotation=45, ha='right') + self.ax.set_xlim(0, len(list_commits) + 1) + self.fig.canvas.draw() + + # for index in range(len(list_commits)): + # boxplot_tooltip(index) + # mplcursors.cursor(hover=True, highlight=True).connect( + # "add", lambda sel: sel.annotation.set_text(f"{sel.artist.get_label()}\n Commit : {list_commits[int(sel.artist.get_xdata()[int(sel.index)])]}\n No:{len(commits[list_commits[int(sel.artist.get_xdata()[int(sel.index)])]])}") + # ) + + def prepare_boxplot_data(self, collection): + global data_column + data = {col: [] for col in data_column} + commits = [] + for row in collection: + for col in data_column: + data[col].append(float(row[col])) + commits.append(row['commit']) + + list_commits = list(set(commits)) + commits_data = {cola: [] for cola in list_commits} + for row in collection: + for col in data_column: + if row['commit'] in commits_data: + commits_data[row['commit']].append(float(row[col])) + return commits_data + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + prog='bench_plot.py', description='Draws a summary on the benchmarks') + parser.add_argument('-f', '--unqlite_file', default='bench.unqlite', + help='Path to the unqlite database file') + parser.add_argument('-d', '--data_column', + default=['query_write_bytes'], nargs='+') + parser.add_argument('-b', '--bucket', default='centreon-collect-robot-report', + help='The S3 bucket to use to get the unqlite file') + parser.add_argument('-e', '--executable', help="Which executable to select for benchmarks, among (engine, broker)") + parser.add_argument('-l', '--local', action="store_true", default=False, help="To work with a local database file") + args = parser.parse_args() + + if not args.local and args.bucket is not None and download_from_s3(args.unqlite_file, args.bucket) != True: + exit() + + db = UnQLite(args.unqlite_file) + collection_list = list_collection(db) + + tests_tree = extract_tests(collection_list) + data_column = args.data_column + app = App(tests_tree) + app.mainloop() diff --git a/tests/broker/command-line.robot b/tests/broker/command-line.robot index fd5202f76a4..4f3d2d9b2e4 100644 --- a/tests/broker/command-line.robot +++ b/tests/broker/command-line.robot @@ -26,7 +26,7 @@ BCL2 Sleep 1s Ctn Start Broker With Args -s5 ${EtcRoot}/centreon-broker/central-broker.json ${table} Create List Starting the TCP thread pool of 5 threads - ${logger_res} Ctn Find In Log With Timeout ${centralLog} ${start} ${table} 30 + ${logger_res} Ctn Find In Log With Timeout /tmp/output.txt ${start} ${table} 30 Should Be True ... ${logger_res} ... Didn't found 5 threads in ${VarRoot}/log/centreon-broker/central-broker-master.log From e7f421f0c13b71024df6b2697bfa689a8ce691c6 Mon Sep 17 00:00:00 2001 From: May <110405507+mushroomempires@users.noreply.github.com> Date: Thu, 16 May 2024 15:35:20 +0200 Subject: [PATCH 06/60] chore(deps): absorb May-24 dependabot dependencies (#1335) * chore(deps): bump actions/download-artifact from 4.1.1 to 4.1.7 (#1311) * fix(broker/grpc): Stream rewritten, it works better and is far simpler (#1291) REFS: MON-38483 * chore(deps): bump actions/download-artifact from 4.1.1 to 4.1.7 Bumps [actions/download-artifact](https://github.com/actions/download-artifact) from 4.1.1 to 4.1.7. - [Release notes](https://github.com/actions/download-artifact/releases) - [Commits](https://github.com/actions/download-artifact/compare/6b208ae046db98c579e8a3aa621ab581ff575935...65a9edc5881444af0b9093a5e628f2fe47ea3b2e) --- updated-dependencies: - dependency-name: actions/download-artifact dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --------- Signed-off-by: dependabot[bot] Co-authored-by: jean-christophe81 <98889244+jean-christophe81@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps): bump actions/upload-artifact from 4.3.0 to 4.3.3 (#1310) * fix(broker/grpc): Stream rewritten, it works better and is far simpler (#1291) REFS: MON-38483 * chore(deps): bump actions/upload-artifact from 4.3.0 to 4.3.3 Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 4.3.0 to 4.3.3. - [Release notes](https://github.com/actions/upload-artifact/releases) - [Commits](https://github.com/actions/upload-artifact/compare/26f96dfa697d77e81fd5907df203aa23a56210a8...65462800fd760344b1a7b4382951275a0abb4808) --- updated-dependencies: - dependency-name: actions/upload-artifact dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --------- Signed-off-by: dependabot[bot] Co-authored-by: jean-christophe81 <98889244+jean-christophe81@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps): bump actions/checkout from 4.1.1 to 4.1.4 (#1309) * fix(broker/grpc): Stream rewritten, it works better and is far simpler (#1291) REFS: MON-38483 * chore(deps): bump actions/checkout from 4.1.1 to 4.1.4 Bumps [actions/checkout](https://github.com/actions/checkout) from 4.1.1 to 4.1.4. - [Release notes](https://github.com/actions/checkout/releases) - [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md) - [Commits](https://github.com/actions/checkout/compare/b4ffde65f46336ab88eb53be808477a3936bae11...0ad4b8fadaa221de15dcec353f45205ec38ea70b) --- updated-dependencies: - dependency-name: actions/checkout dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --------- Signed-off-by: dependabot[bot] Co-authored-by: jean-christophe81 <98889244+jean-christophe81@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps): bump veracode/veracode-uploadandscan-action from 0.2.6 to 1.0 (#1308) * fix(broker/grpc): Stream rewritten, it works better and is far simpler (#1291) REFS: MON-38483 * chore(deps): bump veracode/veracode-uploadandscan-action Bumps [veracode/veracode-uploadandscan-action](https://github.com/veracode/veracode-uploadandscan-action) from 0.2.6 to 1.0. - [Release notes](https://github.com/veracode/veracode-uploadandscan-action/releases) - [Commits](https://github.com/veracode/veracode-uploadandscan-action/compare/0.2.6...v1.0) --- updated-dependencies: - dependency-name: veracode/veracode-uploadandscan-action dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --------- Signed-off-by: dependabot[bot] Co-authored-by: jean-christophe81 <98889244+jean-christophe81@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps): bump actions/setup-python from 4.7.1 to 5.1.0 (#1248) Bumps [actions/setup-python](https://github.com/actions/setup-python) from 4.7.1 to 5.1.0. - [Release notes](https://github.com/actions/setup-python/releases) - [Commits](https://github.com/actions/setup-python/compare/v4.7.1...82c7e631bb3cdc910f68e0081d67478d79c6982d) --- updated-dependencies: - dependency-name: actions/setup-python dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps): bump joonvena/robotframework-reporter-action (#1247) Bumps [joonvena/robotframework-reporter-action](https://github.com/joonvena/robotframework-reporter-action) from 2.3 to 2.4. - [Release notes](https://github.com/joonvena/robotframework-reporter-action/releases) - [Commits](https://github.com/joonvena/robotframework-reporter-action/compare/413a90b26bb8a49eebc51af51f1631500ef0339d...f99583edc5902bd73a61df5c37d1321bc38890ca) --- updated-dependencies: - dependency-name: joonvena/robotframework-reporter-action dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps): bump docker/build-push-action from 5.1.0 to 5.3.0 (#1244) Bumps [docker/build-push-action](https://github.com/docker/build-push-action) from 5.1.0 to 5.3.0. - [Release notes](https://github.com/docker/build-push-action/releases) - [Commits](https://github.com/docker/build-push-action/compare/4a13e500e55cf31b7a5d59a38ab2040ab0f42f56...2cdde995de11925a030ce8070c3d77a52ffcf1c0) --- updated-dependencies: - dependency-name: docker/build-push-action dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps): bump docker/login-action from 3.0.0 to 3.1.0 (#1243) Bumps [docker/login-action](https://github.com/docker/login-action) from 3.0.0 to 3.1.0. - [Release notes](https://github.com/docker/login-action/releases) - [Commits](https://github.com/docker/login-action/compare/343f7c4344506bcbf9b4de18042ae17996df046d...e92390c5fb421da1463c202d546fed0ec5c39f20) --- updated-dependencies: - dependency-name: docker/login-action dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps): bump actions/cache from 4.0.0 to 4.0.2 (#1242) Bumps [actions/cache](https://github.com/actions/cache) from 4.0.0 to 4.0.2. - [Release notes](https://github.com/actions/cache/releases) - [Changelog](https://github.com/actions/cache/blob/main/RELEASES.md) - [Commits](https://github.com/actions/cache/compare/13aacd865c20de90d75de3b17ebe84f7a17d57d2...0c45773b623bea8c8e75f6c82b208c3cf94ea4f9) --- updated-dependencies: - dependency-name: actions/cache dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps): bump docker/setup-buildx-action from 3.0.0 to 3.3.0 (#1312) * fix(broker/grpc): Stream rewritten, it works better and is far simpler (#1291) REFS: MON-38483 * chore(deps): bump docker/setup-buildx-action from 3.0.0 to 3.3.0 Bumps [docker/setup-buildx-action](https://github.com/docker/setup-buildx-action) from 3.0.0 to 3.3.0. - [Release notes](https://github.com/docker/setup-buildx-action/releases) - [Commits](https://github.com/docker/setup-buildx-action/compare/f95db51fddba0c2d1ec667646a06c2ce06100226...d70bba72b1f3fd22344832f00baa16ece964efeb) --- updated-dependencies: - dependency-name: docker/setup-buildx-action dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --------- Signed-off-by: dependabot[bot] Co-authored-by: jean-christophe81 <98889244+jean-christophe81@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --------- Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: jean-christophe81 <98889244+jean-christophe81@users.noreply.github.com> --- .github/workflows/actionlint.yml | 4 ++-- .github/workflows/centreon-collect.yml | 12 +++++----- .github/workflows/docker-builder.yml | 10 ++++----- .github/workflows/get-version.yml | 2 +- .github/workflows/libzmq.yml | 10 ++++----- .github/workflows/package-collect.yml | 4 ++-- .github/workflows/rebase-master.yml | 2 +- .github/workflows/rebase-version.yml | 2 +- .github/workflows/release.yml | 2 +- .github/workflows/robot-nightly.yml | 6 ++--- .github/workflows/robot-test.yml | 30 ++++++++++++------------- .github/workflows/veracode-analysis.yml | 8 +++---- 12 files changed, 46 insertions(+), 46 deletions(-) diff --git a/.github/workflows/actionlint.yml b/.github/workflows/actionlint.yml index e9b57c04346..8388e621380 100644 --- a/.github/workflows/actionlint.yml +++ b/.github/workflows/actionlint.yml @@ -21,7 +21,7 @@ jobs: runs-on: ubuntu-22.04 steps: - name: Checkout sources - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + uses: actions/checkout@0ad4b8fadaa221de15dcec353f45205ec38ea70b # v4.1.4 - name: Download actionlint id: get_actionlint @@ -42,7 +42,7 @@ jobs: runs-on: ubuntu-22.04 steps: - name: Checkout sources - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + uses: actions/checkout@0ad4b8fadaa221de15dcec353f45205ec38ea70b # v4.1.4 - name: Install Yaml run: | diff --git a/.github/workflows/centreon-collect.yml b/.github/workflows/centreon-collect.yml index 7bed8c61631..5525e3df391 100644 --- a/.github/workflows/centreon-collect.yml +++ b/.github/workflows/centreon-collect.yml @@ -69,10 +69,10 @@ jobs: steps: - name: Checkout sources - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + uses: actions/checkout@0ad4b8fadaa221de15dcec353f45205ec38ea70b # v4.1.4 - name: Login to Registry - uses: docker/login-action@343f7c4344506bcbf9b4de18042ae17996df046d # v3.0.0 + uses: docker/login-action@e92390c5fb421da1463c202d546fed0ec5c39f20 # v3.1.0 with: registry: ${{ vars.DOCKER_INTERNAL_REGISTRY_URL }} username: ${{ secrets.DOCKER_REGISTRY_ID }} @@ -105,7 +105,7 @@ jobs: steps: - name: Checkout sources - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + uses: actions/checkout@0ad4b8fadaa221de15dcec353f45205ec38ea70b # v4.1.4 with: path: centreon-collect @@ -136,7 +136,7 @@ jobs: steps: - name: Checkout sources - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + uses: actions/checkout@0ad4b8fadaa221de15dcec353f45205ec38ea70b # v4.1.4 - name: Publish RPM packages uses: ./.github/actions/delivery @@ -171,7 +171,7 @@ jobs: steps: - name: Checkout sources - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + uses: actions/checkout@0ad4b8fadaa221de15dcec353f45205ec38ea70b # v4.1.4 - name: Publish DEB packages uses: ./.github/actions/delivery @@ -195,7 +195,7 @@ jobs: steps: - name: Checkout sources - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + uses: actions/checkout@0ad4b8fadaa221de15dcec353f45205ec38ea70b # v4.1.4 - name: Promote ${{ matrix.distrib }} to stable uses: ./.github/actions/promote-to-stable diff --git a/.github/workflows/docker-builder.yml b/.github/workflows/docker-builder.yml index 606eae9f9df..b0f7f768353 100644 --- a/.github/workflows/docker-builder.yml +++ b/.github/workflows/docker-builder.yml @@ -90,26 +90,26 @@ jobs: steps: - name: Checkout sources - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + uses: actions/checkout@0ad4b8fadaa221de15dcec353f45205ec38ea70b # v4.1.4 - name: Login to Registry - uses: docker/login-action@343f7c4344506bcbf9b4de18042ae17996df046d # v3.0.0 + uses: docker/login-action@e92390c5fb421da1463c202d546fed0ec5c39f20 # v3.1.0 with: registry: ${{ vars.DOCKER_INTERNAL_REGISTRY_URL }} username: ${{ secrets.DOCKER_REGISTRY_ID }} password: ${{ secrets.DOCKER_REGISTRY_PASSWD }} - name: Login to Proxy Registry - uses: docker/login-action@343f7c4344506bcbf9b4de18042ae17996df046d # v3.0.0 + uses: docker/login-action@e92390c5fb421da1463c202d546fed0ec5c39f20 # v3.1.0 with: registry: ${{ vars.DOCKER_PROXY_REGISTRY_URL }} username: ${{ secrets.DOCKER_REGISTRY_ID }} password: ${{ secrets.DOCKER_REGISTRY_PASSWD }} - - uses: docker/setup-buildx-action@f95db51fddba0c2d1ec667646a06c2ce06100226 # v3.0.0 + - uses: docker/setup-buildx-action@d70bba72b1f3fd22344832f00baa16ece964efeb # v3.3.0 - name: Build image ${{ matrix.image }}:${{ matrix.tag }} - uses: docker/build-push-action@4a13e500e55cf31b7a5d59a38ab2040ab0f42f56 # v5.1.0 + uses: docker/build-push-action@2cdde995de11925a030ce8070c3d77a52ffcf1c0 # v5.3.0 with: file: .github/docker/Dockerfile.${{ matrix.dockerfile }} context: . diff --git a/.github/workflows/get-version.yml b/.github/workflows/get-version.yml index 6cbd4b86595..d18322ecd67 100644 --- a/.github/workflows/get-version.yml +++ b/.github/workflows/get-version.yml @@ -44,7 +44,7 @@ jobs: release_cloud: ${{ steps.get_version.outputs.release_cloud}} steps: - - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + - uses: actions/checkout@0ad4b8fadaa221de15dcec353f45205ec38ea70b # v4.1.4 - name: install gh cli on self-hosted runner run: | diff --git a/.github/workflows/libzmq.yml b/.github/workflows/libzmq.yml index 072d91e620e..f289fa48b1d 100644 --- a/.github/workflows/libzmq.yml +++ b/.github/workflows/libzmq.yml @@ -67,7 +67,7 @@ jobs: shell: bash - name: cache rpm - uses: actions/cache/save@13aacd865c20de90d75de3b17ebe84f7a17d57d2 # v4.0.0 + uses: actions/cache/save@0c45773b623bea8c8e75f6c82b208c3cf94ea4f9 # v4.0.2 with: path: ./*.rpm key: ${{ github.run_id }}-${{ github.sha }}-rpm-libzmq-${{ matrix.distrib }}-${{ matrix.arch }} @@ -131,7 +131,7 @@ jobs: shell: bash - name: cache deb - uses: actions/cache/save@13aacd865c20de90d75de3b17ebe84f7a17d57d2 # v4.0.0 + uses: actions/cache/save@0c45773b623bea8c8e75f6c82b208c3cf94ea4f9 # v4.0.2 with: path: ./*.deb key: ${{ github.run_id }}-${{ github.sha }}-deb-libzmq-${{ matrix.distrib }}-${{ matrix.arch }} @@ -153,7 +153,7 @@ jobs: steps: - name: Checkout sources - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + uses: actions/checkout@0ad4b8fadaa221de15dcec353f45205ec38ea70b # v4.1.4 - name: Publish RPM packages uses: ./.github/actions/delivery @@ -188,7 +188,7 @@ jobs: steps: - name: Checkout sources - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + uses: actions/checkout@0ad4b8fadaa221de15dcec353f45205ec38ea70b # v4.1.4 - name: Publish DEB packages uses: ./.github/actions/delivery @@ -212,7 +212,7 @@ jobs: steps: - name: Checkout sources - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + uses: actions/checkout@0ad4b8fadaa221de15dcec353f45205ec38ea70b # v4.1.4 - name: Promote ${{ matrix.distrib }} to stable uses: ./.github/actions/promote-to-stable diff --git a/.github/workflows/package-collect.yml b/.github/workflows/package-collect.yml index 82134278272..b3b0cc4ded6 100644 --- a/.github/workflows/package-collect.yml +++ b/.github/workflows/package-collect.yml @@ -80,7 +80,7 @@ jobs: steps: - name: Checkout sources - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + uses: actions/checkout@0ad4b8fadaa221de15dcec353f45205ec38ea70b # v4.1.4 - name: Install sccache run: | @@ -218,7 +218,7 @@ jobs: # set condition to true if artifacts are needed - if: ${{ false }} name: Upload package artifacts - uses: actions/upload-artifact@26f96dfa697d77e81fd5907df203aa23a56210a8 # v4.3.0 + uses: actions/upload-artifact@65462800fd760344b1a7b4382951275a0abb4808 # v4.3.3 with: name: packages-${{ matrix.distrib }}-${{ matrix.arch }} path: ./*.${{ matrix.package_extension}} diff --git a/.github/workflows/rebase-master.yml b/.github/workflows/rebase-master.yml index c2241297a0e..a49afb39f8d 100644 --- a/.github/workflows/rebase-master.yml +++ b/.github/workflows/rebase-master.yml @@ -16,7 +16,7 @@ jobs: if: github.event.pull_request.merged == true steps: - name: git checkout - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + uses: actions/checkout@0ad4b8fadaa221de15dcec353f45205ec38ea70b # v4.1.4 with: fetch-depth: 0 token: ${{ secrets.CENTREON_TECHNIQUE_PAT }} diff --git a/.github/workflows/rebase-version.yml b/.github/workflows/rebase-version.yml index 4be9a45361f..ef93c147a52 100644 --- a/.github/workflows/rebase-version.yml +++ b/.github/workflows/rebase-version.yml @@ -16,7 +16,7 @@ jobs: if: github.event.pull_request.merged == true steps: - name: git checkout - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + uses: actions/checkout@0ad4b8fadaa221de15dcec353f45205ec38ea70b # v4.1.4 with: fetch-depth: 0 token: ${{ secrets.CENTREON_TECHNIQUE_PAT }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e20fa63d9d6..d5fde4487e1 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -37,7 +37,7 @@ jobs: shell: bash - name: Checkout sources - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + uses: actions/checkout@0ad4b8fadaa221de15dcec353f45205ec38ea70b # v4.1.4 with: fetch-depth: 0 diff --git a/.github/workflows/robot-nightly.yml b/.github/workflows/robot-nightly.yml index cd7e2e13052..2e609cf9e4f 100644 --- a/.github/workflows/robot-nightly.yml +++ b/.github/workflows/robot-nightly.yml @@ -16,7 +16,7 @@ jobs: runs-on: ubuntu-22.04 steps: - name: Checkout sources - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + uses: actions/checkout@0ad4b8fadaa221de15dcec353f45205ec38ea70b # v4.1.4 - run: | gh workflow run robot-nightly.yml -r "dev-23.10.x" @@ -138,7 +138,7 @@ jobs: steps: - name: Checkout sources - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + uses: actions/checkout@0ad4b8fadaa221de15dcec353f45205ec38ea70b # v4.1.4 - name: Publish RPM packages uses: ./.github/actions/delivery @@ -171,7 +171,7 @@ jobs: steps: - name: Checkout sources - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + uses: actions/checkout@0ad4b8fadaa221de15dcec353f45205ec38ea70b # v4.1.4 - name: Publish DEB packages uses: ./.github/actions/delivery diff --git a/.github/workflows/robot-test.yml b/.github/workflows/robot-test.yml index abb048e82a2..c10e0629e55 100644 --- a/.github/workflows/robot-test.yml +++ b/.github/workflows/robot-test.yml @@ -50,17 +50,17 @@ jobs: runs-on: ${{ contains(inputs.image, 'arm') && fromJson('["self-hosted", "collect-arm64"]') || 'ubuntu-22.04' }} steps: - name: Checkout sources - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + uses: actions/checkout@0ad4b8fadaa221de15dcec353f45205ec38ea70b # v4.1.4 - name: Login to Registry - uses: docker/login-action@343f7c4344506bcbf9b4de18042ae17996df046d # v3.0.0 + uses: docker/login-action@e92390c5fb421da1463c202d546fed0ec5c39f20 # v3.1.0 with: registry: ${{ vars.DOCKER_INTERNAL_REGISTRY_URL }} username: ${{ secrets.registry_username }} password: ${{ secrets.registry_password }} - name: Login to Proxy Registry - uses: docker/login-action@343f7c4344506bcbf9b4de18042ae17996df046d # v3.0.0 + uses: docker/login-action@e92390c5fb421da1463c202d546fed0ec5c39f20 # v3.1.0 with: registry: ${{ vars.DOCKER_PROXY_REGISTRY_URL }} username: ${{ secrets.registry_username }} @@ -77,7 +77,7 @@ jobs: shell: bash - name: image to cache - uses: actions/cache/save@13aacd865c20de90d75de3b17ebe84f7a17d57d2 # v4.0.0 + uses: actions/cache/save@0c45773b623bea8c8e75f6c82b208c3cf94ea4f9 # v4.0.2 with: path: /tmp/${{inputs.image}} key: ${{inputs.image_test}} @@ -90,7 +90,7 @@ jobs: steps: - name: Checkout sources - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + uses: actions/checkout@0ad4b8fadaa221de15dcec353f45205ec38ea70b # v4.1.4 - name: List features id: list-features @@ -111,19 +111,19 @@ jobs: steps: - name: Checkout sources - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + uses: actions/checkout@0ad4b8fadaa221de15dcec353f45205ec38ea70b # v4.1.4 with: fetch-depth: 0 - name: Restore image - uses: actions/cache@13aacd865c20de90d75de3b17ebe84f7a17d57d2 # v4.0.0 + uses: actions/cache@0c45773b623bea8c8e75f6c82b208c3cf94ea4f9 # v4.0.2 with: path: /tmp/${{inputs.image}} key: ${{inputs.image_test}} fail-on-cache-miss: true - name: Restore packages - uses: actions/cache@13aacd865c20de90d75de3b17ebe84f7a17d57d2 # v4.0.0 + uses: actions/cache@0c45773b623bea8c8e75f6c82b208c3cf94ea4f9 # v4.0.2 with: path: ${{ inputs.package_cache_path }} key: ${{ inputs.package_cache_key }} @@ -183,7 +183,7 @@ jobs: - name: Upload Test Results if: ${{ failure() }} - uses: actions/upload-artifact@26f96dfa697d77e81fd5907df203aa23a56210a8 # v4.3.0 + uses: actions/upload-artifact@65462800fd760344b1a7b4382951275a0abb4808 # v4.3.3 with: name: reports-${{inputs.test_group_name}}-${{ steps.feature-path.outputs.feature_name_with_dash }} path: reports @@ -195,17 +195,17 @@ jobs: runs-on: ubuntu-22.04 steps: - - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + - uses: actions/checkout@0ad4b8fadaa221de15dcec353f45205ec38ea70b # v4.1.4 - name: Download Artifacts - uses: actions/download-artifact@6b208ae046db98c579e8a3aa621ab581ff575935 # v4.1.1 + uses: actions/download-artifact@65a9edc5881444af0b9093a5e628f2fe47ea3b2e # v4.1.7 with: pattern: reports-${{inputs.test_group_name}}-* path: reports merge-multiple: true - name: Upload the regrouped artifact - uses: actions/upload-artifact@26f96dfa697d77e81fd5907df203aa23a56210a8 # v4.3.0 + uses: actions/upload-artifact@65462800fd760344b1a7b4382951275a0abb4808 # v4.3.3 with: name: reports-${{inputs.test_group_name}} path: reports/ @@ -244,12 +244,12 @@ jobs: shell: bash # setup-python v5.0.0 relies on node20 which is not supported by el7 distributions - - uses: actions/setup-python@65d7f2d534ac1bc67fcd62888c5f4f3d2cb2b236 # v4.7.1 + - uses: actions/setup-python@82c7e631bb3cdc910f68e0081d67478d79c6982d # v5.1.0 if: ${{ inputs.distrib == 'el7'}} with: python-version: '3.10' - - uses: actions/setup-python@0a5c61591373683505ea898e09a3ea4f39ef2b9c # v5.0.0 + - uses: actions/setup-python@82c7e631bb3cdc910f68e0081d67478d79c6982d # v5.1.0 if: ${{ inputs.distrib != 'el7' }} with: python-version: '3.10' @@ -261,7 +261,7 @@ jobs: shell: bash - name: Send report to commit - uses: joonvena/robotframework-reporter-action@413a90b26bb8a49eebc51af51f1631500ef0339d # v2.3 + uses: joonvena/robotframework-reporter-action@f99583edc5902bd73a61df5c37d1321bc38890ca # v2.4 with: gh_access_token: ${{ secrets.GITHUB_TOKEN }} report_path: reports diff --git a/.github/workflows/veracode-analysis.yml b/.github/workflows/veracode-analysis.yml index c256df709b8..d13bede06ac 100644 --- a/.github/workflows/veracode-analysis.yml +++ b/.github/workflows/veracode-analysis.yml @@ -61,7 +61,7 @@ jobs: password: ${{ secrets.docker_registry_passwd }} steps: - - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + - uses: actions/checkout@0ad4b8fadaa221de15dcec353f45205ec38ea70b # v4.1.4 - name: Compiling Cpp sources run: | @@ -133,7 +133,7 @@ jobs: tar cvzf "${{ inputs.module_name }}-${{ github.sha }}-${{ github.run_id }}-veracode-binary.tar.gz" build - name: Cache - uses: actions/cache/save@13aacd865c20de90d75de3b17ebe84f7a17d57d2 # v4.0.0 + uses: actions/cache/save@0c45773b623bea8c8e75f6c82b208c3cf94ea4f9 # v4.0.2 with: path: "${{ inputs.module_name }}-${{ github.sha }}-${{ github.run_id }}-veracode-binary.tar.gz" key: "${{ inputs.module_name }}-${{ github.sha }}-${{ github.run_id }}-veracode-binary" @@ -163,13 +163,13 @@ jobs: delete-on-promote: false - name: Get build binary - uses: actions/cache/restore@13aacd865c20de90d75de3b17ebe84f7a17d57d2 # v4.0.0 + uses: actions/cache/restore@0c45773b623bea8c8e75f6c82b208c3cf94ea4f9 # v4.0.2 with: path: "${{ inputs.module_name }}-${{ github.sha }}-${{ github.run_id }}-veracode-binary.tar.gz" key: "${{ inputs.module_name }}-${{ github.sha }}-${{ github.run_id }}-veracode-binary" - name: Sandbox scan - uses: veracode/veracode-uploadandscan-action@0.2.6 + uses: veracode/veracode-uploadandscan-action@v1.0 continue-on-error: ${{ vars.VERACODE_CONTINUE_ON_ERROR == 'true' }} with: appname: "${{ inputs.module_name }}" From 74697275b8453b659d82b4f97893340d3f11d8fc Mon Sep 17 00:00:00 2001 From: David Boucher Date: Fri, 17 May 2024 09:54:50 +0200 Subject: [PATCH 07/60] enh(tests): new Bench tests and new viewer. MON-15480 --- tests/bench.py | 131 ++++++++++++++------- tests/broker-engine/bench.robot | 196 +++++++++++++++++++++++++++++--- tests/resources/Bench.py | 72 +++++++----- tests/resources/Broker.py | 31 +++++ tests/resources/Common.py | 6 +- 5 files changed, 354 insertions(+), 82 deletions(-) diff --git a/tests/bench.py b/tests/bench.py index b3bdd7f3e50..7ddf29be922 100644 --- a/tests/bench.py +++ b/tests/bench.py @@ -1,5 +1,4 @@ #!/usr/bin/python3 - # # Copyright 2009-2023 Centreon # @@ -77,7 +76,7 @@ def extract_tests(collect_list): """ engine_broker = {'engine': {}, 'broker': {}} test_name_extract = re.compile( - r"\w+_(\w+)_((?:engine|broker)).*") + r"[a-z]*_(.*)_(engine|broker).*") for collection_name in collect_list: m = test_name_extract.match(collection_name) if m is not None: @@ -108,6 +107,26 @@ def list_conf(collection_name: str, origin: str): } +def list_metrics(collection_name: str, origin: str): + """List the available metrics to display. + + Args: + collection_name: name of an unqlite collection + origin: The origin git branch + + Returns: + A list containing the available metrics. + """ + collection = db.collection(collection_name) + selected = collection.filter(lambda row: row['origin'] == origin) + metrics = [] + if len(selected) > 0: + metrics = list(selected[0].keys()) + for m in ["cpu", "nb_core", "memory_size", "branch", "origin", "commit", "t", "__id"]: + metrics.remove(m) + return metrics + + class App(tk.Tk): def __init__(self, tests_tree): super().__init__() @@ -115,53 +134,64 @@ def __init__(self, tests_tree): self.title('Centreon-Collect Benchmarks Tool') menu = tk.Menu(self) - menu_exe = tk.Menu(menu, tearoff=0) - menu.add_cascade(label="Executable", menu=menu_exe) - + menu_tests = tk.Menu(menu, tearoff=0) + menu.add_cascade(label="Tests", menu=menu_tests) + + self.columnconfigure(0, weight=0) + self.columnconfigure(1, weight=1) + self.rowconfigure(1, weight=1) + self.rowconfigure(3, weight=1) + self.rowconfigure(5, weight=1) self.collection = tk.StringVar() for k in tests_tree: - menu_collection = tk.Menu(menu_exe, tearoff=0) - for kk in tests_tree[k]: + menu_collection = tk.Menu(menu_tests, tearoff=0) + tests = list(tests_tree[k]) + tests.sort() + for kk in tests: menu_collection.add_radiobutton(label=tests_tree[k][kk], variable=self.collection, value=tests_tree[k][kk], command=self.collection_chosen) - menu_exe.add_cascade(label=k, menu=menu_collection) + menu_tests.add_cascade(label=k, menu=menu_collection) self.config(menu=menu) origins_label = tk.Label(self, text = "Origins") origins_label.grid(column=0, row=0) self.origins_list = tk.Listbox(self, selectmode="SINGLE") - self.origins_list.grid(column=0, row=1) + self.origins_list.grid(column=0, row=1, sticky="ns") self.origins_list.bind('<>', self.origins_list_changed) confs_label = tk.Label(self, text = "Configurations") confs_label.grid(column=0, row=2) self.confs_list = tk.Listbox(self, selectmode="SINGLE") - self.confs_list.grid(column=0, row=3) + self.confs_list.grid(column=0, row=3, sticky="ns") + self.confs_list.bind('<>', self.confs_list_changed) + + metrics_label = tk.Label(self, text = "Metrics") + metrics_label.grid(column=0, row=4) + self.metrics_list = tk.Listbox(self, selectmode="SINGLE") + self.metrics_list.grid(column=0, row=5, sticky="ns") + self.metrics_list.bind('<>', self.metrics_list_changed) update = tk.Button(self, text = "Update", command=self.update_graph) - update.grid(column=0, row=4) + update.grid(column=0, row=6) self.fig = plt.figure() plt.subplots_adjust(left=0.22, right=0.98, bottom=0.1, top=0.99) self.ax = self.fig.subplots() self.list_com = [] - ax_origin_choice = None - origin_choice = None - self.ax_conf_choice = None - conf_choice = None # create FigureCanvasTkAgg object figure_canvas = FigureCanvasTkAgg(self.fig, self) # create the toolbar - toolbarFrame = tk.Frame(master=self) - toolbarFrame.grid(row=4, column=1) - NavigationToolbar2Tk(figure_canvas, toolbarFrame) + toolbar_frame = tk.Frame(master=self) + toolbar_frame.grid(row=6, column=1) + NavigationToolbar2Tk(figure_canvas, toolbar_frame) - figure_canvas.get_tk_widget().grid(column=1, row=0, rowspan=4) + figure_canvas.get_tk_widget().grid(column=1, row=0, rowspan=6, sticky="nesw") def collection_chosen(self): self.origins_list.delete(0, self.origins_list.size()) - origins = list_origin_branch(self.collection.get()) + origins = list(list_origin_branch(self.collection.get())) + origins.sort() for i, o in enumerate(origins): self.origins_list.insert(i, o) self.fig.canvas.draw() @@ -172,11 +202,18 @@ def origins_list_changed(self, evt): if len(w.curselection()) > 0: index = int(w.curselection()[0]) self.origin = w.get(index) - confs = list_conf(self.collection.get(), self.origin) + confs = list(list_conf(self.collection.get(), self.origin)) + confs.sort() self.confs_list.delete(0, self.confs_list.size()) for i, c in enumerate(confs): self.confs_list.insert(i, c) + metrics = list(list_metrics(self.collection.get(), self.origin)) + metrics.sort() + self.metrics_list.delete(0, self.metrics_list.size()) + for i, m in enumerate(metrics): + self.metrics_list.insert(i, m) + def confs_list_changed(self, evt): # Note here that Tkinter passes an event object to onselect() w = evt.widget @@ -184,14 +221,27 @@ def confs_list_changed(self, evt): index = int(w.curselection()[0]) self.conf = w.get(index) + def metrics_list_changed(self, evt): + # Note here that Tkinter passes an event object to onselect() + w = evt.widget + if len(w.curselection()) > 0: + index = int(w.curselection()[0]) + self.metric = w.get(index) + def update_graph(self): global db collection = db.collection(self.collection.get()) - if self.ax_conf_choice is not None: - self.ax_conf_choice.remove() - self.ax_conf_choice = plt.axes((0.01, 0.01, 0.18, 0.2)) - points = collection.filter(lambda row: row['origin'] == self.origin and f"{row['cpu']}\n mem:{int(row['memory_size']/1024/1024/1024)}" == self.conf) - sorted(points, key=lambda row: row['date_commit']) + tmp = self.conf.split('\n mem:') + cpu = tmp[0] + mem = int(tmp[1]) + points = collection.filter(lambda row: row['origin'] == self.origin and row['cpu'] == cpu and int(row['memory_size']/1024/1024/1024) == mem) + + # We have to take care to the uncommitted files that also do not have date_commit. + new_points = [p for p in points if "date_commit" in p] + if len(new_points) > 0: + points = new_points + points.sort(key=lambda row: row['date_commit']) + self.fig.canvas.draw() self.plot_boxplot(points) @@ -199,13 +249,13 @@ def plot_boxplot(self, collection): commits = self.prepare_boxplot_data(collection) self.ax.clear() self.list_com.clear(), - list_commits = list(set(commits.keys())) + list_commits = list(commits.keys()) for list_commit in list_commits: self.list_com.append(list_commit[:8]) self.ax.boxplot([commits[col] for col in commits.keys()], labels=self.list_com) self.ax.set_xlabel("Commits") - self.ax.set_ylabel("Normalized Values") + self.ax.set_ylabel(self.metric) self.ax.set_title("Benchmark Data") self.ax.set_xticklabels(self.list_com, rotation=45, ha='right') self.ax.set_xlim(0, len(list_commits) + 1) @@ -218,20 +268,26 @@ def plot_boxplot(self, collection): # ) def prepare_boxplot_data(self, collection): - global data_column - data = {col: [] for col in data_column} commits = [] for row in collection: - for col in data_column: - data[col].append(float(row[col])) commits.append(row['commit']) + # Here we keep commits only once but we lose the commits order. list_commits = list(set(commits)) - commits_data = {cola: [] for cola in list_commits} + # Now, we restablish the order. The result is in commit. + i = 0 + while i < len(commits): + c = commits[i] + if c in list_commits: + list_commits.remove(c) + i += 1 + else: + commits.pop(i) + + commits_data = {cola: [] for cola in commits} for row in collection: - for col in data_column: - if row['commit'] in commits_data: - commits_data[row['commit']].append(float(row[col])) + if row['commit'] in commits_data: + commits_data[row['commit']].append(float(row[self.metric])) return commits_data if __name__ == '__main__': @@ -239,8 +295,6 @@ def prepare_boxplot_data(self, collection): prog='bench_plot.py', description='Draws a summary on the benchmarks') parser.add_argument('-f', '--unqlite_file', default='bench.unqlite', help='Path to the unqlite database file') - parser.add_argument('-d', '--data_column', - default=['query_write_bytes'], nargs='+') parser.add_argument('-b', '--bucket', default='centreon-collect-robot-report', help='The S3 bucket to use to get the unqlite file') parser.add_argument('-e', '--executable', help="Which executable to select for benchmarks, among (engine, broker)") @@ -254,6 +308,5 @@ def prepare_boxplot_data(self, collection): collection_list = list_collection(db) tests_tree = extract_tests(collection_list) - data_column = args.data_column app = App(tests_tree) app.mainloop() diff --git a/tests/broker-engine/bench.robot b/tests/broker-engine/bench.robot index b0029370eee..e7a9e727773 100644 --- a/tests/broker-engine/bench.robot +++ b/tests/broker-engine/bench.robot @@ -14,9 +14,14 @@ Test Teardown Ctn Stop Engine Broker And Save Logs *** Test Cases *** -BENCH_${nb_check}STATUS +BENCH_${nb_checks}STATUS [Documentation] external command CHECK_SERVICE_RESULT 1000 times [Tags] broker engine bench + # We need to clear the retention and to check that the JSON for the bench event is well generated. + Ctn Clear Retention + Ctn Clear Db logs + Ctn Clear Db comments + Ctn Clear Db data_bin Ctn Config Engine ${1} ${50} ${20} # We want all the services to be passive to avoid parasite checks during our test. Ctn Set Services Passive ${0} service_.* @@ -33,11 +38,12 @@ BENCH_${nb_check}STATUS Ctn Start engine Ctn Wait For Engine To Be Ready ${start} ${1} + ${start} Get Current Date ${broker_stat_before} Ctn Get Broker Process Stat 51001 ${engine_stat_before} Ctn Get Engine Process Stat 50001 - Ctn Process Service Check Result host_1 service_1 1 warning config0 0 ${nb_check} + Ctn Process Service Check Result host_1 service_1 1 warning config0 0 ${nb_checks} Ctn Send Bench 1 50001 - ${bench_data} Ctn Get Last Bench Result With Timeout ${rrdLog} 1 central-rrd-master-output 60 + ${bench_data} Ctn Get Last Bench Result With Timeout ${rrdLog} 1 ${start} central-rrd-master-output 60 ${broker_stat_after} Ctn Get Broker Process Stat 51001 ${engine_stat_after} Ctn Get Engine Process Stat 50001 ${diff_broker} Ctn Diff Process Stat ${broker_stat_after} ${broker_stat_before} @@ -47,7 +53,7 @@ BENCH_${nb_check}STATUS ${success} Ctn Store Result In Unqlite ... bench.unqlite - ... BENCH_${nb_check}STATUS + ... BENCH_${nb_checks}STATUS ... broker ... ${diff_broker} ... ${broker_stat_after} @@ -60,7 +66,7 @@ BENCH_${nb_check}STATUS ${success} Ctn Store Result In Unqlite ... bench.unqlite - ... BENCH_${nb_check}STATUS + ... BENCH_${nb_checks}STATUS ... engine ... ${diff_engine} ... ${engine_stat_after} @@ -73,13 +79,18 @@ BENCH_${nb_check}STATUS Ctn Upload Database To S3 bench.unqlite - Examples: nb_check -- + Examples: nb_checks -- ... 1000 ... 10000 -BENCH_${nb_check}STATUS_TRACES - [Documentation] external command CHECK_SERVICE_RESULT ${nb_check} times +BENCH_${nb_checks}STATUS_TRACES + [Documentation] external command CHECK_SERVICE_RESULT ${nb_checks} times [Tags] broker engine bench + # We need to clear the retention and to check that the JSON for the bench event is well generated. + Ctn Clear Retention + Ctn Clear Db logs + Ctn Clear Db comments + Ctn Clear Db data_bin Ctn Config Engine ${1} ${50} ${20} # We want all the services to be passive to avoid parasite checks during our test. Ctn Set Services Passive ${0} service_.* @@ -99,11 +110,12 @@ BENCH_${nb_check}STATUS_TRACES Ctn Start engine Ctn Wait For Engine To Be Ready ${start} ${1} + ${start} Get Current Date ${broker_stat_before} Ctn Get Broker Process Stat 51001 ${engine_stat_before} Ctn Get Engine Process Stat 50001 - Ctn Process Service Check Result host_1 service_1 1 warning config0 0 ${nb_check} + Ctn Process Service Check Result host_1 service_1 1 warning config0 0 ${nb_checks} Ctn Send Bench 1 50001 - ${bench_data} Ctn Get Last Bench Result With Timeout ${rrdLog} 1 central-rrd-master-output 60 + ${bench_data} Ctn Get Last Bench Result With Timeout ${rrdLog} 1 ${start} central-rrd-master-output 60 ${broker_stat_after} Ctn Get Broker Process Stat 51001 ${engine_stat_after} Ctn Get Engine Process Stat 50001 ${diff_broker} Ctn Diff Process Stat ${broker_stat_after} ${broker_stat_before} @@ -113,7 +125,7 @@ BENCH_${nb_check}STATUS_TRACES ${success} Ctn Store Result In Unqlite ... bench.unqlite - ... BENCH_${nb_check}STATUS_TRACES + ... BENCH_${nb_checks}STATUS_TRACES ... broker ... ${diff_broker} ... ${broker_stat_after} @@ -126,7 +138,7 @@ BENCH_${nb_check}STATUS_TRACES ${success} Ctn Store Result In Unqlite ... bench.unqlite - ... BENCH_${nb_check}STATUS_TRACES + ... BENCH_${nb_checks}STATUS_TRACES ... engine ... ${diff_engine} ... ${engine_stat_after} @@ -139,13 +151,18 @@ BENCH_${nb_check}STATUS_TRACES Ctn Upload Database To S3 bench.unqlite - Examples: nb_check -- + Examples: nb_checks -- ... 1000 ... 10000 BENCH_1000STATUS_100${suffixe} [Documentation] external command CHECK_SERVICE_RESULT 100 times with 100 pollers with 20 services [Tags] broker engine bench + # We need to clear the retention and to check that the JSON for the bench event is well generated. + Ctn Clear Retention + Ctn Clear Db logs + Ctn Clear Db comments + Ctn Clear Db data_bin Ctn Config Engine ${100} ${100} ${20} Ctn Config Broker module ${100} Ctn Config Broker central @@ -189,7 +206,7 @@ BENCH_1000STATUS_100${suffixe} END END - ${bench_data} Ctn Get Last Bench Result With Timeout ${rrdLog} 1 central-rrd-master-output 60 + ${bench_data} Ctn Get Last Bench Result With Timeout ${rrdLog} 1 ${start_check} central-rrd-master-output 60 ${broker_stat_after} Ctn Get Broker Process Stat 51001 ${engine_stat_after} Ctn Get Engine Process Stat 50001 ${diff_broker} Ctn Diff Process Stat ${broker_stat_after} ${broker_stat_before} @@ -239,3 +256,154 @@ BENCH_1000STATUS_100${suffixe} ... ENGINE 1 ... ENGINE_2 2 ... ENGINE_3 3 + +BENCH_${nb_checks}_SERVICE_STATUS_WITHOUT_SQL + [Documentation] Broker is configured without SQL output. External command CHECK_SERVICE_RESULT is sent ${nb_checks} times. + [Tags] broker engine bench without_sql + # We need to clear the retention and to check that the JSON for the bench event is well generated. + Ctn Clear Retention + Ctn Clear Db logs + Ctn Clear Db comments + Ctn Clear Db data_bin + Ctn Config Engine ${1} ${50} ${20} + # We want all the services to be passive to avoid parasite checks during our test. + Ctn Set Services Passive ${0} service_.* + Ctn Config Broker central + Ctn Config Broker rrd + Ctn Config Broker module ${1} + Ctn Broker Config Log central core info + Ctn Broker Config Log central processing error + Ctn Config BBDO3 1 + # No sql output to avoid broker to slow down too much + Ctn Broker Config Remove Output central unified_sql + Ctn Broker Config Remove Output central sql + Ctn Broker Config Remove Output central storage + ${start} Get Current Date + Ctn Start Broker + Ctn Start engine + Ctn Wait For Engine To Be Ready ${start} ${1} + + ${start} Get Current Date + ${broker_stat_before} Ctn Get Broker Process Stat 51001 + ${engine_stat_before} Ctn Get Engine Process Stat 50001 + Log To Console Sending ${nb_checks} Service check results + Ctn Process Service Check Result host_1 service_1 1 warning config0 0 ${nb_checks} + Ctn Send Bench 1 50001 + Log To Console Done + ${bench_data} Ctn Get Last Bench Result With Timeout ${rrdLog} 1 ${start} central-rrd-master-output 300 + Should be True ${bench_data} is not None No bench element received by Broker + ${broker_stat_after} Ctn Get Broker Process Stat 51001 + ${engine_stat_after} Ctn Get Engine Process Stat 50001 + ${diff_broker} Ctn Diff Process Stat ${broker_stat_after} ${broker_stat_before} + ${diff_engine} Ctn Diff Process Stat ${engine_stat_after} ${engine_stat_before} + + Ctn Download Database From S3 bench.unqlite + + ${success} Ctn Store Result In Unqlite + ... bench.unqlite + ... BENCH_${nb_checks}_SERVICE_STATUS_WITHOUT_SQL + ... broker + ... ${diff_broker} + ... ${broker_stat_after} + ... ${bench_data} + ... central-broker-master-input-1 + ... write + ... central-rrd-master-output + ... publish + Should Be True ${success} Failed to save Broker bench to database + + ${success} Ctn Store Result In Unqlite + ... bench.unqlite + ... BENCH_${nb_checks}_SERVICE_STATUS_WITHOUT_SQL + ... engine + ... ${diff_engine} + ... ${engine_stat_after} + ... ${bench_data} + ... client + ... callback_pb_bench + ... central-module-master-output + ... read + Should Be True ${success} Failed to save Engine bench to database + + Ctn Upload Database To S3 bench.unqlite + + Examples: nb_checks -- + ... 100000 + ... 300000 + +BENCH_${nb_checks}_SERVICE_STATUS_TRACES_WITHOUT_SQL + [Documentation] Broker is configured without SQL output. External command CHECK_SERVICE_RESULT is sent ${nb_checks} times. Logs are in trace level. + [Tags] broker engine bench without_sql + # We need to clear the retention and to check that the JSON for the bench event is well generated. + Ctn Clear Retention + Ctn Clear Db logs + Ctn Clear Db comments + Ctn Clear Db data_bin + Ctn Config Engine ${1} ${50} ${20} + # We want all the services to be passive to avoid parasite checks during our test. + Ctn Set Services Passive ${0} service_.* + Ctn Config Broker central + Ctn Config Broker rrd + Ctn Config Broker module ${1} + FOR ${name} IN @{CONFIG_NAME} + Ctn Broker Config Log central ${name} trace + END + + Ctn Config BBDO3 1 + # No sql output to avoid broker to slow down too much + Ctn Broker Config Remove Output central unified_sql + Ctn Broker Config Remove Output central sql + Ctn Broker Config Remove Output central storage + ${start} Get Current Date + Ctn Start Broker + Ctn Start engine + Ctn Wait For Engine To Be Ready ${start} ${1} + + ${start} Get Current Date + ${broker_stat_before} Ctn Get Broker Process Stat 51001 + ${engine_stat_before} Ctn Get Engine Process Stat 50001 + Log To Console Sending ${nb_checks} Service check results + Ctn Process Service Check Result host_1 service_1 1 warning config0 0 ${nb_checks} + Ctn Send Bench 1 50001 + Log To Console Done + ${bench_data} Ctn Get Last Bench Result With Timeout ${rrdLog} 1 ${start} central-rrd-master-output 300 + Should be True ${bench_data} is not None No bench element received by Broker + ${broker_stat_after} Ctn Get Broker Process Stat 51001 + ${engine_stat_after} Ctn Get Engine Process Stat 50001 + ${diff_broker} Ctn Diff Process Stat ${broker_stat_after} ${broker_stat_before} + ${diff_engine} Ctn Diff Process Stat ${engine_stat_after} ${engine_stat_before} + + Ctn Download Database From S3 bench.unqlite + + ${success} Ctn Store Result In Unqlite + ... bench.unqlite + ... BENCH_${nb_checks}_SERVICE_STATUS_TRACES_WITHOUT_SQL + ... broker + ... ${diff_broker} + ... ${broker_stat_after} + ... ${bench_data} + ... central-broker-master-input-1 + ... write + ... central-rrd-master-output + ... publish + Should Be True ${success} Failed to save Broker bench to database + + ${success} Ctn Store Result In Unqlite + ... bench.unqlite + ... BENCH_${nb_checks}_SERVICE_STATUS_TRACES_WITHOUT_SQL + ... engine + ... ${diff_engine} + ... ${engine_stat_after} + ... ${bench_data} + ... client + ... callback_pb_bench + ... central-module-master-output + ... read + Should Be True ${success} Failed to save Engine bench to database + + Ctn Upload Database To S3 bench.unqlite + + Examples: nb_checks -- + ... 100000 + ... 300000 + diff --git a/tests/resources/Bench.py b/tests/resources/Bench.py index 96a9ece707b..9ebf231de46 100644 --- a/tests/resources/Bench.py +++ b/tests/resources/Bench.py @@ -14,6 +14,7 @@ from dateutil import parser as date_parser from Common import ctn_get_collect_version from Common import ctn_is_using_direct_grpc +from Common import ctn_find_line_from class delta_process_stat: @@ -59,23 +60,28 @@ def ctn_add_value_to_delta_process_stat(delta, key, value): setattr(delta, key, value) -def ctn_get_last_bench_result(log: str, id: int, name_to_find: str): - """! extract last bench trace in broker log file - @log path of the log file - @param id id field of the bench event - @param name_to_find a string to find in the bench result like a muxer name - @return a json object that contains all bench time points +def ctn_get_last_bench_result(log: str, id: int, start, name_to_find: str): + """Extract last bench trace in the given log file. + Args: + log: The log file that should contain the bench event. + id: The ID of the bench event. + start: The date from which to start the look up. + name_to_find: The muxer name to find. + + Returns: + A JSON object that contains all bench time points. """ last_bench_str = "" p = re.compile( r".+bench\s+\w+\s+content:'(.\"id\":{}.+{}.+)'".format(id, name_to_find.replace(" ", "\s"))) try: - f = open(log, "r") - lines = f.readlines() - f.close() + with open(log, "r") as f: + lines = f.readlines() - for line in lines: + idx = ctn_find_line_from(lines, start) + for i in range(idx, len(lines)): + line = lines[i] extract = p.match(line) if extract is not None: last_bench_str = extract.group(1) @@ -87,18 +93,24 @@ def ctn_get_last_bench_result(log: str, id: int, name_to_find: str): return None -def ctn_get_last_bench_result_with_timeout(log: str, id: int, name_to_find: str, timeout: int): - """! extract last bench trace in broker log file - @log path of the log file - @param id id field of the bench event - @param name_to_find a string to find in the bench result like a muxer name - @param timeout time out in seconds - @return a json object that contains all bench time points +def ctn_get_last_bench_result_with_timeout(log: str, id: int, start, name_to_find: str, timeout: int): + """Extract last bench trace in the given log file. + + Args: + log: The log file. + id: The ID of the bench event. + start: The date from which we start to search. + name_to_find: A string to find in the bench result like a muxer name + timeout: A duration in seconds + + Returns: + A JSON object that contains all bench time points """ limit = time.time() + timeout while time.time() < limit: - json_obj = ctn_get_last_bench_result(log, id, name_to_find) + json_obj = ctn_get_last_bench_result(log, id, start, name_to_find) if json_obj is not None: + logger.console(json_obj) return json_obj time.sleep(5) logger.console("The file '{}' does not contain bench".format(log)) @@ -106,14 +118,20 @@ def ctn_get_last_bench_result_with_timeout(log: str, id: int, name_to_find: str, def ctn_calc_bench_delay(bench_event_result, bench_muxer_begin: str, bench_muxer_begin_function: str, bench_muxer_end: str, bench_muxer_end_function: str): - """! calc a duration between two time points of a bench event json object - @param bench_event_result bench result json object - @param bench_muxer_begin name of the muxer owned to the first time point (accepts regexp) - @param bench_muxer_begin_function name of the muxer function owned to the first time point - @param bench_muxer_end name of the muxer owned to the last time point - @param bench_muxer_end_function name of the muxer function owned to the last time point + """ Compute a duration between two time points of a bench event json object + + Args: + bench_event_result: bench result json object + bench_muxer_begin: name of the muxer owned to the first time point (accepts regexp) + bench_muxer_begin_function: name of the muxer function owned to the first time point + bench_muxer_end: name of the muxer owned to the last time point + bench_muxer_end_function: name of the muxer function owned to the last time point + + Returns: + A delay in seconds. """ + logger.console(f"Bench Delay {bench_muxer_begin_function}: {bench_muxer_begin} => {bench_muxer_end_function}: {bench_muxer_end}") time_begin = 0 time_end = 0 begin_re = re.compile(bench_muxer_begin) @@ -157,6 +175,7 @@ def ctn_store_result_in_unqlite(file_path: str, test_name: str, broker_or_engin row['memory_used'] = end_process_stat.vm_size row['event_propagation_delay'] = ctn_calc_bench_delay( bench_event_result, bench_muxer_begin, bench_muxer_begin_function, bench_muxer_end, bench_muxer_end_function).total_seconds() + logger.console(f"event_propagation_delay = {row['event_propagation_delay']}") if other_bench_data is not None: for key, value in other_bench_data.items(): @@ -183,8 +202,9 @@ def ctn_store_result_in_unqlite(file_path: str, test_name: str, broker_or_engin if ctn_is_using_direct_grpc(): test_name += "_grpc" db = UnQLite(file_path) - benchs = db.collection( - f'collectbench_{test_name}_{broker_or_engine}_{bench_event_result["id"]}') + test_name = f'collectbench_{test_name}_{broker_or_engine}_{bench_event_result["id"]}' + logger.console(f"Storing in DB: {test_name}") + benchs = db.collection(test_name) benchs.create() benchs.store(row) test = benchs.all() diff --git a/tests/resources/Broker.py b/tests/resources/Broker.py index 3634e18e658..c84d10de90f 100755 --- a/tests/resources/Broker.py +++ b/tests/resources/Broker.py @@ -1039,6 +1039,37 @@ def ctn_broker_config_add_item(name, key, value): f.write(json.dumps(conf, indent=2)) +def ctn_broker_config_remove_output(name, output): + """ + Remove an output from the broker configuration + + Args: + name: The broker instance name among central, rrd and module%d + output: The output to remove. + + *Example:* + + | Ctn Broker Config Remove Output | central | unified_sql | + """ + if name == 'central': + filename = "central-broker.json" + elif name == 'rrd': + filename = "central-rrd.json" + elif name.startswith('module'): + filename = "central-{}.json".format(name) + + with open(f"{ETC_ROOT}/centreon-broker/{filename}", "r") as f: + buf = f.read() + conf = json.loads(buf) + output_dict = conf["centreonBroker"]["output"] + for i, v in enumerate(output_dict): + if v["type"] == output: + output_dict.pop(i) + + with open(f"{ETC_ROOT}/centreon-broker/{filename}", "w") as f: + f.write(json.dumps(conf, indent=2)) + + def ctn_broker_config_remove_item(name, key): """ Remove an item from the broker configuration diff --git a/tests/resources/Common.py b/tests/resources/Common.py index 8d563e4d372..2e82f3a6d2f 100644 --- a/tests/resources/Common.py +++ b/tests/resources/Common.py @@ -233,9 +233,9 @@ def ctn_find_in_log(log: str, date, content, regex=False): res = [] try: - f = open(log, "r", encoding="latin1") - lines = f.readlines() - f.close() + with open(log, "r", encoding="latin1") as f: + lines = f.readlines() + idx = ctn_find_line_from(lines, date) for c in content: From 638297b7b9c2bb68c17e1c31daf6c4c966454d30 Mon Sep 17 00:00:00 2001 From: jean-christophe81 <98889244+jean-christophe81@users.noreply.github.com> Date: Fri, 17 May 2024 17:35:56 +0200 Subject: [PATCH 08/60] enh(broker/common) http_client is moved to common and new class http_server REFS: MON-35539 --- broker/CMakeLists.txt | 1 - broker/http_client/precomp_inc/precomp.hh | 49 -- broker/http_tsdb/CMakeLists.txt | 4 +- .../broker/http_tsdb/http_tsdb_config.hh | 49 +- .../com/centreon/broker/http_tsdb/stream.hh | 61 ++- broker/http_tsdb/src/factory.cc | 35 +- broker/http_tsdb/src/stream.cc | 43 +- broker/http_tsdb/test/stream_test.cc | 51 ++- broker/test/CMakeLists.txt | 2 +- broker/victoria_metrics/CMakeLists.txt | 5 +- .../broker/victoria_metrics/stream.hh | 43 +- broker/victoria_metrics/src/connector.cc | 21 +- broker/victoria_metrics/src/stream.cc | 9 +- broker/victoria_metrics/test/stream_test.cc | 14 +- common/CMakeLists.txt | 4 + .../http}/CMakeLists.txt | 21 +- common/http/doc/common-http.md | 223 +++++++++ .../com/centreon/common/http}/http_client.hh | 51 +-- .../com/centreon/common/http}/http_config.hh | 48 +- .../centreon/common/http}/http_connection.hh | 124 +++-- .../com/centreon/common/http/http_server.hh | 68 +++ .../centreon/common/http}/https_connection.hh | 62 ++- .../http}/src/http_client.cc | 9 +- .../http}/src/http_connection.cc | 172 +++++-- common/http/src/http_server.cc | 95 ++++ .../http}/src/https_connection.cc | 213 +++++++-- .../http}/test/http_client_test.cc | 115 ++--- .../http}/test/http_connection_test.cc | 430 +++++++----------- common/inc/com/centreon/common/hex_dump.hh | 9 +- common/precomp_inc/precomp.hh | 7 +- common/src/process_stat.cc | 34 +- common/test/CMakeLists.txt | 33 +- common/test/process_stat_test.cc | 33 +- common/test/test_main.cc | 62 +++ 34 files changed, 1425 insertions(+), 775 deletions(-) delete mode 100644 broker/http_client/precomp_inc/precomp.hh rename {broker/http_client => common/http}/CMakeLists.txt (62%) create mode 100644 common/http/doc/common-http.md rename {broker/http_client/inc/com/centreon/broker/http_client => common/http/inc/com/centreon/common/http}/http_client.hh (78%) rename {broker/http_client/inc/com/centreon/broker/http_client => common/http/inc/com/centreon/common/http}/http_config.hh (81%) rename {broker/http_client/inc/com/centreon/broker/http_client => common/http/inc/com/centreon/common/http}/http_connection.hh (61%) create mode 100644 common/http/inc/com/centreon/common/http/http_server.hh rename {broker/http_client/inc/com/centreon/broker/http_client => common/http/inc/com/centreon/common/http}/https_connection.hh (57%) rename {broker/http_client => common/http}/src/http_client.cc (98%) rename {broker/http_client => common/http}/src/http_connection.cc (69%) create mode 100644 common/http/src/http_server.cc rename {broker/http_client => common/http}/src/https_connection.cc (65%) rename {broker/http_client => common/http}/test/http_client_test.cc (80%) rename {broker/http_client => common/http}/test/http_connection_test.cc (63%) create mode 100644 common/test/test_main.cc diff --git a/broker/CMakeLists.txt b/broker/CMakeLists.txt index f1d1e076fc6..af3a9ac809c 100644 --- a/broker/CMakeLists.txt +++ b/broker/CMakeLists.txt @@ -521,7 +521,6 @@ add_broker_module(TLS2 OFF) add_broker_module(DUMP OFF) add_broker_module(GRPC ON) add_broker_module(VICTORIA_METRICS ON) -add_subdirectory(http_client) add_subdirectory(http_tsdb) # Lua module. diff --git a/broker/http_client/precomp_inc/precomp.hh b/broker/http_client/precomp_inc/precomp.hh deleted file mode 100644 index 07c1e1cc6d0..00000000000 --- a/broker/http_client/precomp_inc/precomp.hh +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2022 Centreon (https://www.centreon.com/) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * For more information : contact@centreon.com - * - */ - -#ifndef CCB_HTTP_CLIENT_PRECOMP_HH -#define CCB_HTTP_CLIENT_PRECOMP_HH - -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#include - -#include -#include -#include -#include - -#include "com/centreon/exceptions/msg_fmt.hh" - -using system_clock = std::chrono::system_clock; -using time_point = system_clock::time_point; -using duration = system_clock::duration; - -namespace asio = boost::asio; - -#endif // CCB_HTTP_CLIENT_PRECOMP_HH diff --git a/broker/http_tsdb/CMakeLists.txt b/broker/http_tsdb/CMakeLists.txt index ba26cfdaaa8..0303f80e592 100644 --- a/broker/http_tsdb/CMakeLists.txt +++ b/broker/http_tsdb/CMakeLists.txt @@ -19,10 +19,10 @@ # Global options. set(INC_DIR "${PROJECT_SOURCE_DIR}/http_tsdb/inc/com/centreon/broker/http_tsdb") -set(HTTP_CLIENT_INC_DIR "${PROJECT_SOURCE_DIR}/http_client/inc") +set(HTTP_INC_DIR "${CMAKE_SOURCE_DIR}/common/http/inc") set(SRC_DIR "src") set(TEST_DIR "${PROJECT_SOURCE_DIR}/http_tsdb/test") -include_directories(inc ${INC_DIR} ${HTTP_CLIENT_INC_DIR}) +include_directories(inc ${INC_DIR} ${HTTP_INC_DIR}) # Sources. set(SOURCES diff --git a/broker/http_tsdb/inc/com/centreon/broker/http_tsdb/http_tsdb_config.hh b/broker/http_tsdb/inc/com/centreon/broker/http_tsdb/http_tsdb_config.hh index 28345d663c4..069e2d32655 100644 --- a/broker/http_tsdb/inc/com/centreon/broker/http_tsdb/http_tsdb_config.hh +++ b/broker/http_tsdb/inc/com/centreon/broker/http_tsdb/http_tsdb_config.hh @@ -1,31 +1,32 @@ -/* -** Copyright 2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2024 Centreon (https://www.centreon.com/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCB_HTTP_TSDB_CONFIG_HH #define CCB_HTTP_TSDB_CONFIG_HH #include "column.hh" -#include "com/centreon/broker/http_client/http_config.hh" +#include "com/centreon/common/http/http_config.hh" namespace com::centreon::broker { namespace http_tsdb { -class http_tsdb_config : public http_client::http_config { +class http_tsdb_config : public common::http::http_config { std::string _http_target; std::string _user; std::string _pwd; @@ -34,14 +35,14 @@ class http_tsdb_config : public http_client::http_config { std::vector _metric_columns; public: - http_tsdb_config(const http_client::http_config& http_conf, + http_tsdb_config(const common::http::http_config& http_conf, const std::string& http_target, const std::string& user, const std::string& pwd, unsigned max_queries_per_transaction, const std::vector& status_columns, const std::vector& metric_columns) - : http_client::http_config(http_conf), + : common::http::http_config(http_conf), _http_target(http_target), _user(user), _pwd(pwd), @@ -50,9 +51,9 @@ class http_tsdb_config : public http_client::http_config { _metric_columns(metric_columns) {} http_tsdb_config() : _max_queries_per_transaction(0) {} - http_tsdb_config(const http_client::http_config& http_conf, + http_tsdb_config(const common::http::http_config& http_conf, unsigned max_queries_per_transaction) - : http_client::http_config(http_conf), + : common::http::http_config(http_conf), _max_queries_per_transaction(max_queries_per_transaction) {} const std::string& get_http_target() const { return _http_target; } @@ -71,6 +72,6 @@ class http_tsdb_config : public http_client::http_config { }; } // namespace http_tsdb -} +} // namespace com::centreon::broker #endif diff --git a/broker/http_tsdb/inc/com/centreon/broker/http_tsdb/stream.hh b/broker/http_tsdb/inc/com/centreon/broker/http_tsdb/stream.hh index a65c73838b2..bbe341c1120 100644 --- a/broker/http_tsdb/inc/com/centreon/broker/http_tsdb/stream.hh +++ b/broker/http_tsdb/inc/com/centreon/broker/http_tsdb/stream.hh @@ -1,38 +1,39 @@ -/* -** Copyright 2011-2017 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2024 Centreon (https://www.centreon.com/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCB_HTTP_TSDB_STREAM_HH #define CCB_HTTP_TSDB_STREAM_HH -#include "com/centreon/broker/http_client/http_client.hh" #include "com/centreon/broker/io/stream.hh" #include "com/centreon/broker/persistent_cache.hh" +#include "com/centreon/common/http/http_client.hh" #include "http_tsdb_config.hh" #include "internal.hh" #include "line_protocol_query.hh" -namespace http_client = com::centreon::broker::http_client; +namespace http = com::centreon::common::http; namespace com::centreon::broker { namespace http_tsdb { -class request : public http_client::request_base { +class request : public http::request_base { protected: unsigned _nb_metric; unsigned _nb_status; @@ -43,9 +44,8 @@ class request : public http_client::request_base { request() : _nb_metric(0), _nb_status(0) {} request(boost::beast::http::verb method, const std::string& server_name, - boost::beast::string_view target, - unsigned version = 11) - : http_client::request_base(method, server_name, target), + boost::beast::string_view target) + : http::request_base(method, server_name, target), _nb_metric(0), _nb_status(0) {} @@ -67,7 +67,7 @@ inline std::ostream& operator<<(std::ostream& str, const request& req) { return str; } -/** +/* * @class stream stream.hh "com/centreon/broker/influxdb/stream.hh" * @brief tsdb stream. * This class is a base class @@ -82,7 +82,7 @@ class stream : public io::stream, public std::enable_shared_from_this { // Database and http parameters std::shared_ptr _conf; - http_client::client::pointer _http_client; + http::client::pointer _http_client; // number of metric and status sent to tsdb and acknowledged by a 20x response unsigned _acknowledged; @@ -90,7 +90,7 @@ class stream : public io::stream, public std::enable_shared_from_this { request::pointer _request; // the two beans stat_unit and stat_average are used to produce statistics // about request time - /** + /* * @brief stat cumul * this bean is used to cumulate request for example during one second */ @@ -106,7 +106,7 @@ class stream : public io::stream, public std::enable_shared_from_this { stat _metric_stat; stat _status_stat; - /** + /* * @brief this cless calc an average over a period * */ @@ -129,8 +129,7 @@ class stream : public io::stream, public std::enable_shared_from_this { const std::shared_ptr& io_context, const std::shared_ptr& logger, const std::shared_ptr& conf, - http_client::client::connection_creator conn_creator = - http_client::http_connection::load); + http::connection_creator conn_creator); virtual request::pointer create_request() const = 0; @@ -139,7 +138,7 @@ class stream : public io::stream, public std::enable_shared_from_this { void send_handler(const boost::beast::error_code& err, const std::string& detail, const request::pointer& request, - const http_client::response_ptr& response); + const http::response_ptr& response); void add_to_stat(stat& to_maj, unsigned to_add); @@ -155,6 +154,6 @@ class stream : public io::stream, public std::enable_shared_from_this { }; } // namespace http_tsdb -} +} // namespace com::centreon::broker #endif // !CCB_HTTP_TSDB_STREAM_HH diff --git a/broker/http_tsdb/src/factory.cc b/broker/http_tsdb/src/factory.cc index 8a790ae5249..d456c708776 100644 --- a/broker/http_tsdb/src/factory.cc +++ b/broker/http_tsdb/src/factory.cc @@ -1,20 +1,21 @@ /** -* Copyright 2011-2017 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2024 Centreon (https://www.centreon.com/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include "com/centreon/broker/http_tsdb/factory.hh" @@ -244,7 +245,7 @@ void factory::create_conf(const config::endpoint& cfg, certificate_path = it->second; } - http_client::http_config http_cfg( + common::http::http_config http_cfg( res_it->endpoint(), addr, encryption, connect_timeout, send_timeout, receive_timeout, second_tcp_keep_alive_interval, std::chrono::seconds(1), 0, default_http_keepalive_duration, max_connections, ssl_method, diff --git a/broker/http_tsdb/src/stream.cc b/broker/http_tsdb/src/stream.cc index 5deb405ec6f..dc78b102350 100644 --- a/broker/http_tsdb/src/stream.cc +++ b/broker/http_tsdb/src/stream.cc @@ -1,20 +1,21 @@ /** -* Copyright 2022 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2024 Centreon (https://www.centreon.com/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include "com/centreon/broker/http_tsdb/stream.hh" #include "bbdo/storage/metric.hh" @@ -105,7 +106,7 @@ unsigned stream::stat_average::get_average() const { /** * @brief Construct a new stream::stream object - * conn_creator is used by this object to construct http_client::connection_base + * conn_creator is used by this object to construct http::connection_base * objects conn_creator can construct an http_connection, https_connection or a * mock * @param name @@ -119,7 +120,7 @@ stream::stream(const std::string& name, const std::shared_ptr& io_context, const std::shared_ptr& logger, const std::shared_ptr& conf, - http_client::client::connection_creator conn_creator) + http::connection_creator conn_creator) : io::stream(name), _io_context(io_context), _logger(logger), @@ -130,7 +131,7 @@ stream::stream(const std::string& name, _metric_stat{{0, 0}, {0, 0}}, _status_stat{{0, 0}, {0, 0}} { _http_client = - http_client::client::load(io_context, logger, conf, conn_creator); + common::http::client::load(io_context, logger, conf, conn_creator); } stream::~stream() {} @@ -324,7 +325,7 @@ void stream::send_request(const request::pointer& request) { _http_client->send(request, [me = shared_from_this(), request]( const boost::beast::error_code& err, const std::string& detail, - const http_client::response_ptr& response) { + const common::http::response_ptr& response) { me->send_handler(err, detail, request, response); }); } @@ -344,7 +345,7 @@ static time_point _epoch = system_clock::from_time_t(0); void stream::send_handler(const boost::beast::error_code& err, const std::string& detail, const request::pointer& request, - const http_client::response_ptr& response) { + const common::http::response_ptr& response) { auto actu_stat_avg = [&]() -> void { if (request->get_connect_time() > _epoch && request->get_send_time() > _epoch) { diff --git a/broker/http_tsdb/test/stream_test.cc b/broker/http_tsdb/test/stream_test.cc index 808650a10d1..c5cee36daaf 100644 --- a/broker/http_tsdb/test/stream_test.cc +++ b/broker/http_tsdb/test/stream_test.cc @@ -1,5 +1,5 @@ /** - * Copyright 2022 Centreon (https://www.centreon.com/) + * Copyright 2024 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,6 +36,7 @@ using duration = system_clock::duration; using namespace com::centreon::exceptions; using namespace com::centreon::broker; +using namespace com::centreon::common; using namespace nlohmann; extern std::shared_ptr g_io_context; @@ -81,8 +82,7 @@ std::atomic_uint request_test::id_gen(0); class stream_test : public http_tsdb::stream { public: stream_test(const std::shared_ptr& conf, - http_client::client::connection_creator conn_creator = - http_client::http_connection::load) + http::connection_creator conn_creator) : http_tsdb::stream("stream_test", g_io_context, log_v2::tcp(), @@ -94,31 +94,37 @@ class stream_test : public http_tsdb::stream { }; TEST_F(http_tsdb_stream_test, NotRead) { - stream_test test(std::make_shared()); + auto conf = std::make_shared(); + http::connection_creator conn_creator = [conf]() { + return http::http_connection::load(g_io_context, log_v2::tcp(), conf); + }; + stream_test test(conf, conn_creator); std::shared_ptr d(std::make_shared(1)); ASSERT_THROW(test.read(d, 0), msg_fmt); } -class connection_send_bagot : public http_client::connection_base { +class connection_send_bagot : public http::connection_base { + asio::ip::tcp::socket _not_used; + public: static std::atomic_uint success; static std::condition_variable success_cond; connection_send_bagot(const std::shared_ptr& io_context, const std::shared_ptr& logger, - const http_client::http_config::pointer& conf) - : connection_base(io_context, logger, conf) {} + const http::http_config::pointer& conf) + : connection_base(io_context, logger, conf), _not_used(*io_context) {} void shutdown() override { _state = e_not_connected; } - void connect(http_client::connect_callback_type&& callback) override { + void connect(http::connect_callback_type&& callback) override { _state = e_idle; _io_context->post([cb = std::move(callback)]() { cb({}, {}); }); } - void send(http_client::request_ptr request, - http_client::send_callback_type&& callback) override { + void send(http::request_ptr request, + http::send_callback_type&& callback) override { if (_state != e_idle) { _io_context->post([cb = std::move(callback)]() { cb(std::make_error_code(std::errc::invalid_argument), "bad state", {}); @@ -147,32 +153,39 @@ class connection_send_bagot : public http_client::connection_base { std::static_pointer_cast(request)->get_request_id(), std::static_pointer_cast(request)->get_nb_data()); _io_context->post([cb = std::move(callback)]() { - auto resp = std::make_shared(); + auto resp = std::make_shared(); resp->keep_alive(false); cb({}, "", resp); }); } } } + + void on_accept(http::connect_callback_type&& callback) override{}; + + void answer(const http::response_ptr& response, + http::answer_callback_type&& callback) override {} + void receive_request(http::request_callback_type&& callback) override {} + + asio::ip::tcp::socket& get_socket() { return _not_used; } }; std::atomic_uint connection_send_bagot::success(0); std::condition_variable connection_send_bagot::success_cond; TEST_F(http_tsdb_stream_test, all_event_sent) { - http_client::http_config conf( + http::http_config conf( asio::ip::tcp::endpoint(asio::ip::address_v4::loopback(), 80), "localhost", false, std::chrono::seconds(10), std::chrono::seconds(10), std::chrono::seconds(10), 30, std::chrono::seconds(1), 100, std::chrono::seconds(1), 5); - std::shared_ptr str(std::make_shared( - std::make_shared(conf, 10), - [](const std::shared_ptr& io_context, - const std::shared_ptr& logger, - const http_client::http_config::pointer& conf) { - auto dummy_conn = - std::make_shared(io_context, logger, conf); + auto tsdb_conf = std::make_shared(conf, 10); + + std::shared_ptr str( + std::make_shared(tsdb_conf, [tsdb_conf]() { + auto dummy_conn = std::make_shared( + g_io_context, log_v2::tcp(), tsdb_conf); return dummy_conn; })); diff --git a/broker/test/CMakeLists.txt b/broker/test/CMakeLists.txt index 9469ce778a3..7e7dd8da3b2 100644 --- a/broker/test/CMakeLists.txt +++ b/broker/test/CMakeLists.txt @@ -43,7 +43,7 @@ include_directories(${PROJECT_SOURCE_DIR}/tls/inc) include_directories(${PROJECT_SOURCE_DIR}/tls2/inc) include_directories(${PROJECT_SOURCE_DIR}/grpc/inc) include_directories(${PROJECT_SOURCE_DIR}/grpc/src) -include_directories(${PROJECT_SOURCE_DIR}/http_client/inc) +include_directories(${CMAKE_SOURCE_DIR}/common/http/inc) include_directories(${PROJECT_SOURCE_DIR}/http_tsdb/inc) include_directories(${PROJECT_SOURCE_DIR}/victoria_metrics/inc) include_directories(${PROJECT_SOURCE_DIR}/test/test_util/inc) diff --git a/broker/victoria_metrics/CMakeLists.txt b/broker/victoria_metrics/CMakeLists.txt index c6aec580555..d208dba2c2e 100644 --- a/broker/victoria_metrics/CMakeLists.txt +++ b/broker/victoria_metrics/CMakeLists.txt @@ -18,11 +18,12 @@ # Global options. set(INC_DIR "${PROJECT_SOURCE_DIR}/victoria_metrics/inc/com/centreon/broker/victoria_metrics") +set(HTTP_INC_DIR "${CMAKE_SOURCE_DIR}/common/http/inc") set(SRC_DIR "${PROJECT_SOURCE_DIR}/victoria_metrics/src") set(TEST_DIR "${PROJECT_SOURCE_DIR}/victoria_metrics/test") include_directories(inc ${PROJECT_SOURCE_DIR}/http_tsdb/inc - ${PROJECT_SOURCE_DIR}/http_client/inc + ${HTTP_INC_DIR} ${PROJECT_SOURCE_DIR}/neb/inc ) @@ -53,7 +54,7 @@ add_library("${VICTORIA_METRICS}" SHARED set_target_properties("${VICTORIA_METRICS}" PROPERTIES PREFIX "") target_link_libraries("${VICTORIA_METRICS}" http_tsdb - http_client + centreon_http bbdo_storage pb_storage_lib spdlog::spdlog) target_precompile_headers(${VICTORIA_METRICS} PRIVATE precomp_inc/precomp.hh) diff --git a/broker/victoria_metrics/inc/com/centreon/broker/victoria_metrics/stream.hh b/broker/victoria_metrics/inc/com/centreon/broker/victoria_metrics/stream.hh index 08e44ac54c1..e6c1b338310 100644 --- a/broker/victoria_metrics/inc/com/centreon/broker/victoria_metrics/stream.hh +++ b/broker/victoria_metrics/inc/com/centreon/broker/victoria_metrics/stream.hh @@ -1,20 +1,21 @@ -/* -** Copyright 2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2024 Centreon (https://www.centreon.com/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCB_VICTORIA_METRICS_STREAM_HH #define CCB_VICTORIA_METRICS_STREAM_HH @@ -42,8 +43,7 @@ class stream : public http_tsdb::stream { stream(const std::shared_ptr& io_context, const std::shared_ptr& conf, const std::string& account_id, - http_client::client::connection_creator conn_creator = - http_client::http_connection::load); + http::connection_creator conn_creator); http_tsdb::request::pointer create_request() const override; @@ -54,14 +54,13 @@ class stream : public http_tsdb::stream { const std::shared_ptr& io_context, const std::shared_ptr& conf, const std::string& account_id, - http_client::client::connection_creator conn_creator = - http_client::http_connection::load); + http::connection_creator conn_creator); const std::string& get_authorization() const { return _authorization; } }; }; // namespace victoria_metrics -} +} // namespace com::centreon::broker #endif // !CCB_VICTORIA_METRICS_STREAM_HH diff --git a/broker/victoria_metrics/src/connector.cc b/broker/victoria_metrics/src/connector.cc index 47bb952138b..a9c06069dab 100644 --- a/broker/victoria_metrics/src/connector.cc +++ b/broker/victoria_metrics/src/connector.cc @@ -1,11 +1,11 @@ /** - * Copyright 2022 Centreon + * Copyright 2024 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -14,11 +14,13 @@ * limitations under the License. * * For more information : contact@centreon.com + * */ #include "com/centreon/broker/victoria_metrics/connector.hh" -#include "com/centreon/broker/http_client/https_connection.hh" +#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/victoria_metrics/stream.hh" +#include "com/centreon/common/http/https_connection.hh" #include "com/centreon/common/pool.hh" using namespace com::centreon::broker; @@ -37,9 +39,18 @@ connector::connector(const std::shared_ptr& conf, std::shared_ptr connector::open() { if (!_conf->is_crypted()) { return stream::load(com::centreon::common::pool::io_context_ptr(), _conf, - _account_id, http_client::http_connection::load); + _account_id, [conf = _conf]() { + return http::http_connection::load( + com::centreon::common::pool::io_context_ptr(), + log_v2::victoria_metrics(), conf); + }); } else { return stream::load(com::centreon::common::pool::io_context_ptr(), _conf, - _account_id, http_client::https_connection::load); + _account_id, [conf = _conf]() { + return http::https_connection::load( + com::centreon::common::pool::io_context_ptr(), + log_v2::victoria_metrics(), conf, + http::https_connection::load_client_certificate); + }); } } \ No newline at end of file diff --git a/broker/victoria_metrics/src/stream.cc b/broker/victoria_metrics/src/stream.cc index d0000f28819..afe84157706 100644 --- a/broker/victoria_metrics/src/stream.cc +++ b/broker/victoria_metrics/src/stream.cc @@ -1,11 +1,11 @@ /** - * Copyright 2022 Centreon + * Copyright 2024 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -14,6 +14,7 @@ * limitations under the License. * * For more information : contact@centreon.com + * */ #include "com/centreon/broker/victoria_metrics/stream.hh" @@ -36,7 +37,7 @@ const std::string stream::allowed_macros = stream::stream(const std::shared_ptr& io_context, const std::shared_ptr& conf, const std::string& account_id, - http_client::client::connection_creator conn_creator) + http::connection_creator conn_creator) : http_tsdb::stream("victoria_metrics", io_context, log_v2::victoria_metrics(), @@ -66,7 +67,7 @@ std::shared_ptr stream::load( const std::shared_ptr& io_context, const std::shared_ptr& conf, const std::string& account_id, - http_client::client::connection_creator conn_creator) { + http::connection_creator conn_creator) { return std::shared_ptr( new stream(io_context, conf, account_id, conn_creator)); } diff --git a/broker/victoria_metrics/test/stream_test.cc b/broker/victoria_metrics/test/stream_test.cc index 01fb79bfba5..76c431167ba 100644 --- a/broker/victoria_metrics/test/stream_test.cc +++ b/broker/victoria_metrics/test/stream_test.cc @@ -1,5 +1,5 @@ /** - * Copyright 2019 Centreon (https://www.centreon.com/) + * Copyright 2024 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,9 +31,12 @@ using duration = system_clock::duration; #include "com/centreon/broker/config/applier/state.hh" #include "com/centreon/broker/file/disk_accessor.hh" +#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/victoria_metrics/stream.hh" +#include "com/centreon/common/pool.hh" using namespace com::centreon::broker; +using namespace com::centreon::common; using namespace com::centreon::broker::victoria_metrics; using namespace nlohmann; @@ -49,11 +52,16 @@ class victoria_stream_test : public ::testing::Test { }; TEST_F(victoria_stream_test, Authorization) { - http_client::http_config dummy; + http::http_config dummy; std::vector dummy2; auto cfg = std::make_shared( dummy, "/write", "Aladdin", "open sesame", 1, dummy2, dummy2); - std::shared_ptr s = stream::load(g_io_context, cfg, "my_account"); + std::shared_ptr s = + stream::load(g_io_context, cfg, "my_account", [cfg]() { + return http::http_connection::load( + com::centreon::common::pool::io_context_ptr(), + log_v2::victoria_metrics(), cfg); + }); ASSERT_EQ(s->get_authorization(), "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="); } diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt index e320764b7b8..5c3de9473bc 100644 --- a/common/CMakeLists.txt +++ b/common/CMakeLists.txt @@ -21,6 +21,7 @@ project("Centreon common" C CXX) # Set directories. set(INCLUDE_DIR "${PROJECT_SOURCE_DIR}/inc/com/centreon/common") +set (HTTP_INCLUDE_DIR "${PROJECT_SOURCE_DIR}/http/inc/com/centreon/common/http") set(SRC_DIR "${PROJECT_SOURCE_DIR}/src") set(TEST_DIR "${PROJECT_SOURCE_DIR}/test") @@ -52,6 +53,7 @@ set(SOURCES # Include directories. include_directories("${INCLUDE_DIR}" + ${HTTP_INCLUDE_DIR} ${VCPKG_INCLUDE_DIR} ) @@ -62,6 +64,8 @@ set_property(TARGET centreon_common PROPERTY POSITION_INDEPENDENT_CODE ON) target_precompile_headers(centreon_common PRIVATE precomp_inc/precomp.hh) +add_subdirectory(http) + if(WITH_TESTING) add_subdirectory(test) endif() diff --git a/broker/http_client/CMakeLists.txt b/common/http/CMakeLists.txt similarity index 62% rename from broker/http_client/CMakeLists.txt rename to common/http/CMakeLists.txt index 3696f05ce85..d57e20e73b0 100644 --- a/broker/http_client/CMakeLists.txt +++ b/common/http/CMakeLists.txt @@ -18,32 +18,25 @@ # Global options. -set(INC_DIR "${PROJECT_SOURCE_DIR}/http_client/inc/com/centreon/broker/http_client") +set(INC_DIR "${PROJECT_SOURCE_DIR}/http/inc/com/centreon/common/http") set(SRC_DIR "src") -set(TEST_DIR "${PROJECT_SOURCE_DIR}/http_client/test") -include_directories(${INC_DIR}) +set(TEST_DIR "${PROJECT_SOURCE_DIR}/http/test") # Sources. set(SOURCES ${SRC_DIR}/http_client.cc ${SRC_DIR}/http_connection.cc ${SRC_DIR}/https_connection.cc + ${SRC_DIR}/http_server.cc ) -# Headers. -set(HEADERS - ${INC_DIR}/http_client.hh - ${INC_DIR}/http_connection.hh - ${INC_DIR}/https_connection.hh - ${INC_DIR}/http_config.hh -) -add_library(http_client STATIC ${SOURCES} ${HEADERS}) -target_include_directories(http_client PRIVATE ${INC_DIR}) +add_library(centreon_http STATIC ${SOURCES} ) +target_include_directories(centreon_http PRIVATE ${INC_DIR}) -target_precompile_headers(http_client PRIVATE precomp_inc/precomp.hh) +target_precompile_headers(centreon_http REUSE_FROM centreon_common) -set_target_properties(http_client PROPERTIES COMPILE_FLAGS "-fPIC") +set_target_properties(centreon_http PROPERTIES COMPILE_FLAGS "-fPIC") # Testing. if(WITH_TESTING) diff --git a/common/http/doc/common-http.md b/common/http/doc/common-http.md new file mode 100644 index 00000000000..500f427c8e3 --- /dev/null +++ b/common/http/doc/common-http.md @@ -0,0 +1,223 @@ +# Centreon Common http library documentation + +## Introduction + +This library relies on low level http library: boost::beast. +The goal of this library is to provide a higher level than boost::beast. +It provides http(s) client and server implementation. +All this library is asynchronous. +In order to use it, you have to provide a shared_ptr yet run outside and a shared_ptr. +All is configured in that bean: http_config. +beast::request and beast::response are body templated. We use the boost::beast::http::string_body version +```c++ +using request_type = boost::beast::http::request; +using response_type = boost::beast::http::response; +``` + + +### Common client/server classes + +#### http_config: a bean that contains all configuration options needed by server and client +Fields passed to constructor: +- endpoint: this endpoint is the connection endpoint in case of client or listen endpoint in case of server +- server_name: (not used by this library), but provided to construct http request + ```c++ + auto ret = std::make_shared( + boost::beast::http::verb::post, _conf->get_server_name(), + "action"); + ``` +- connect_timeout: timeout to connect to server (tcp connection time, not handshake) +- send_timeout: timeout to send request (client) or response (server) +- receive_timeout: + - client: timeout to receive response after have sent request + - server: max time to wait a request after connection success or after last response sent. This parameter is also added to response via the keep-alive header. If this parameter is lower than 1s, no keep-alive is added to the response and connection is closed after response sent +- second_tcp_keep_alive_interval: if not null, tcp keep alive is activated on each connection in order to maintain NATs +- max_retry_interval: when client fails to send request, client retries to send request, delay between two attempts is doubled until it reaches max_retry_interval +- max_send_retry: max client send attempts +- default_http_keepalive_duration: When server answers with keep-alive header, but not delay or when where are in http 1.1, this parameter is used by client to disconnect from the server after this delay +- ssl_method: parameter used to initialize ssl context + - Values allowed: + - tlsv1_client + - tlsv1_server + - sslv23 + - sslv23_client + - sslv23_server + - tlsv11 + - tlsv11_client + - tlsv11_server + - tlsv12 + - tlsv12_client + - tlsv12_server + - tlsv13 + - tlsv13_client + - tlsv13_server + - tls + - tls_client + - tls_server +- certificate_path: path of the file that contains certificate (both client and server) +- key_path: path of the file thant contains key of the certificate (server only) + +#### request_base +It inherits from boost::beast::http::request< boost::beast::http::string_body > and embed some time-points to get statistics + + +#### connection_base +This abstract class is the mother of http_connection and https_connection. +It contains an io_context, logger and the peer endpoint +In order to avoid mistakes, it also contains an atomic _state indicator. + +- abstract methods: + - shutdown: shutdown connection, connection won't be reusable after this call. This method returns immediately but is asynchronous in case of https case. So connection object will be deleted later once ssl shutdown have been done. + - server usage + - on_accept(): first, the server creates an non connected connection, when it's accepted, it calls on_accept and then this connection can live. The implemented method must call on_accept(connect_callback_type&& callback) + - on_accept(connect_callback_type&& callback): do the ssl handshake and initialize tcp keep-alive. callback must call receive_request to wait for request + - receive_request(request_callback_type&& callback): wait for incoming request, it must call answer to send response + - answer(const response_ptr& response, answer_callback_type&& callback): send answer to client, if a receive_timeout is > one second, implementation must call receive_request to read nex requests, otherwise, socket is closed adn nothing have to be done + - get_socket: returns a reference to the transport layer (asio::ip::tcp::socket) + - client usage + - connect(connect_callback_type&& callback): It connects to the server and performs ssl handshake. callback can then call send + - send(request_ptr request, send_callback_type&& callback): send request to the server and pass response to callback. On response, connection is closed if server indicates that there is no keep-alive + +- implemented methods: + - gest_keepalive: (client side) It extracts keep-alive header from response and calculate time-point limit after that connection will be shutdown (returned by get_keep_alive_end()). + - add_keep_alive_to_server_response: (server side) It adds keep-alive header to answer. It uses receive_time out config parameter. + +#### http_connection +- init_keep_alive(): activate tcp keep-alive +- load: this object must be created in an shared_ptr (constructor is protected). This method creates it in a shared_ptr + +#### https_connection +- init_keep_alive(): activate tcp keep-alive +- load: this object must be created in an shared_ptr (constructor is protected). This method creates it in a shared_ptr + +#### http_client +This client uses http_connection or https_connection objects to send request to ONE server.
+Connections are stored in three containers: +- _not_connected_conns: not connected connections +- _keep_alive_conns: connected connections maintained by both client and server after have received a response with http keep-alive activated. These connections are available for next requests. +- _busy_conns: connections active +##### strategy +When we want to send a request, we first try to reuse a connection of _keep_alive_conns.
+If not available, we connect one of _not_connected_conns.
+If not available, request is pushed to queue and will be send as soon as a connection will ba available. +##### retry strategy +In case of failure (transport failure not http error code), request sent is deferred with an asio timer and then repushed in queue. Delay between two attempts is doubled on each send failure. + +#### http_server +The job of this class is to only accept incoming connections. Once a connection is accepted, this connection is not owned by http_server object and continue to leave even if http_server has been shutting down. +In order to use it with both http and https, the most simple is to define a session templated class that can inherit either from http_connection or https_connection. +Then you have to implement functors in charge of create of session. +http_server use this functor to create a not connected session. Once it's accepted, it call on_accept() method of the session object, release it and create another session object. + +Example of implementation: +- session implementation +```c++ +template +class session_test : public connection_class { + + void wait_for_request(); + + void answer(const std::shared_ptr& request); + + public: + session_test(const std::shared_ptr& io_context, + const std::shared_ptr& logger, + const http_config::pointer& conf, + const ssl_ctx_initializer& ssl_initializer) + : connection_class(io_context, logger, conf, ssl_initializer) { + } + + std::shared_ptr shared_from_this() { + return std::static_pointer_cast( + connection_class::shared_from_this()); + } + + void on_accept() override; +}; + +/** + * @brief one tcp connection is accepted, start handshake + * + * @tparam connection_class + */ +template +void session_test::on_accept() { + connection_class::on_accept( + [me = shared_from_this()](const boost::beast::error_code& err, + const std::string&) { + if (!err) + me->wait_for_request(); + }); +} + +/** + * @brief wait incoming request + * + * @tparam connection_class + */ +template +void session_test::wait_for_request() { + connection_class::receive_request( + [me = shared_from_this()](const boost::beast::error_code& err, + const std::string& detail, + const std::shared_ptr& request) { + if (err) { + SPDLOG_LOGGER_DEBUG(me->_logger, + "fail to receive request from {}: {}", me->_peer, + err.what()); + return; + } + me->answer(request); + }); +} + +/** + * @brief called once a request have been received + * Once the response has been sent, it calls wait_for_request + * to manage next incoming request + * + * @tparam connection_class + * @param request + */ +template +void session_test::answer( + const std::shared_ptr& request) { + response_ptr resp(std::make_shared()); + resp->version(request->version()); + resp->body() = request->body(); + resp->content_length(resp->body().length()); + + connection_class::answer( + resp, [me = shared_from_this(), resp](const boost::beast::error_code& err, + const std::string& detail) { + if (err) { + SPDLOG_LOGGER_ERROR(me->_logger, "fail to answer to client {} {}", + err.message(), detail); + return; + } + me->wait_for_request(); + }); +} +``` +- server creation +```c++ +void create_server(const std::shared_ptr & io_ctx, + const std::shared_ptr logger, + const http_config::pointer conf) { + connection_creator server_creator; + if (conf->is_crypted()) { + server_creator = [io_ctx, logger, conf]() { + return std::make_shared>( + io_ctx, logger, conf, https_connection::load_server_certificate); + }; + } + else { + server_creator = [io_ctx, logger, conf]() { + return std::make_shared>( + io_ctx, logger, conf); + }; + } + auto server = http_server::load(io_ctx, logger, conf, + std::move(server_creator)); +} +``` diff --git a/broker/http_client/inc/com/centreon/broker/http_client/http_client.hh b/common/http/inc/com/centreon/common/http/http_client.hh similarity index 78% rename from broker/http_client/inc/com/centreon/broker/http_client/http_client.hh rename to common/http/inc/com/centreon/common/http/http_client.hh index 8ceb626f325..4bbe4a1f6c2 100644 --- a/broker/http_client/inc/com/centreon/broker/http_client/http_client.hh +++ b/common/http/inc/com/centreon/common/http/http_client.hh @@ -1,20 +1,21 @@ -/* -** Copyright 2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2024 Centreon (https://www.centreon.com/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCB_HTTP_CLIENT_CLIENT_HH__ #define CCB_HTTP_CLIENT_CLIENT_HH__ @@ -23,12 +24,10 @@ class client_test; -namespace com::centreon::broker { +namespace com::centreon::common::http { -namespace http_client { /** * @class client - * "broker/http_client/inc/com/centreon/broker/http_client/http_client.hh" * * @brief this class is the heart of the library * it dispatchs requests on connections to the server @@ -48,11 +47,6 @@ namespace http_client { */ class client : public std::enable_shared_from_this { public: - using connection_creator = std::function& io_context, - const std::shared_ptr& logger, - const http_config::pointer& conf)>; - friend client_test; private: @@ -120,7 +114,7 @@ class client : public std::enable_shared_from_this { static pointer load(const std::shared_ptr& io_context, const std::shared_ptr& logger, const http_config::pointer& conf, - connection_creator conn_creator = http_connection::load); + connection_creator conn_creator); template bool send(const request_ptr& request, callback_type&& callback) { @@ -146,9 +140,6 @@ void client::visit_queue(visitor_type& visitor) const { visitor(*cb->request); } } - -} // namespace http_client - -} +} // namespace com::centreon::common::http #endif // CCB_HTTP_CLIENT_CLIENT_HH__ diff --git a/broker/http_client/inc/com/centreon/broker/http_client/http_config.hh b/common/http/inc/com/centreon/common/http/http_config.hh similarity index 81% rename from broker/http_client/inc/com/centreon/broker/http_client/http_config.hh rename to common/http/inc/com/centreon/common/http/http_config.hh index c24c82b2005..90c0bce3aa8 100644 --- a/broker/http_client/inc/com/centreon/broker/http_client/http_config.hh +++ b/common/http/inc/com/centreon/common/http/http_config.hh @@ -1,33 +1,33 @@ -/* -** Copyright 2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2024 Centreon (https://www.centreon.com/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCB_HTTP_CLIENT_CONFIG_HH__ #define CCB_HTTP_CLIENT_CONFIG_HH__ -namespace com::centreon::broker { +namespace com::centreon::common::http { -namespace http_client { /** * @brief this class is a bean that contains all config parameters * */ class http_config { - // destination address + // destination or listen address asio::ip::tcp::endpoint _endpoint; std::string _server_name; bool _crypted; @@ -99,13 +99,11 @@ class http_config { const std::string& get_certificate_path() const { return _certificate_path; } }; -}; // namespace http_client - -} +} // namespace com::centreon::common::http namespace fmt { template <> -struct formatter { +struct formatter { constexpr auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) { return ctx.begin(); } @@ -113,7 +111,7 @@ struct formatter { // Formats the point p using the parsed format specification (presentation) // stored in this formatter. template - auto format(const com::centreon::broker::http_client::http_config& conf, + auto format(const com::centreon::common::http::http_config& conf, FormatContext& ctx) const -> decltype(ctx.out()) { std::ostringstream s; s << conf.get_endpoint(); diff --git a/broker/http_client/inc/com/centreon/broker/http_client/http_connection.hh b/common/http/inc/com/centreon/common/http/http_connection.hh similarity index 61% rename from broker/http_client/inc/com/centreon/broker/http_client/http_connection.hh rename to common/http/inc/com/centreon/common/http/http_connection.hh index 198405214ab..840d5f32c41 100644 --- a/broker/http_client/inc/com/centreon/broker/http_client/http_connection.hh +++ b/common/http/inc/com/centreon/common/http/http_connection.hh @@ -1,29 +1,29 @@ -/* -** Copyright 2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2024 Centreon (https://www.centreon.com/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCB_HTTP_CLIENT_CONNECTION_HH__ #define CCB_HTTP_CLIENT_CONNECTION_HH__ #include "http_config.hh" -namespace com::centreon::broker { +namespace com::centreon::common::http { -namespace http_client { /** * @brief we use a std::string body * @@ -50,6 +50,22 @@ using send_callback_type = std::function; +/** + * @brief called in server mode when response have been sent + * + */ +using answer_callback_type = + std::function; + +/** + * @brief called after a request have been received (server mode) + * + */ +using request_callback_type = + std::function&)>; + /** * @brief this option set the interval in seconds between two keepalive sent * @@ -107,7 +123,9 @@ using request_ptr = std::shared_ptr; */ class connection_base : public std::enable_shared_from_this { protected: - // this atomic uint is used to atomicaly modify object state + asio::ip::tcp::endpoint _peer; + + // this atomic uint is used to atomically modify object state std::atomic_uint _state; // http keepalive expiration time_point _keep_alive_end; @@ -152,20 +170,58 @@ class connection_base : public std::enable_shared_from_this { virtual void connect(connect_callback_type&& callback) = 0; + // client version virtual void send(request_ptr request, send_callback_type&& callback) = 0; + // server version + /** + * @brief to override in accepted session objects + * It has to call on_accept(connect_callback_type&& callback) in order to + * receive + * + */ + virtual void on_accept() {} + + virtual void on_accept(connect_callback_type&& callback) = 0; + + virtual void answer(const response_ptr& response, + answer_callback_type&& callback) = 0; + virtual void receive_request(request_callback_type&& callback) = 0; + e_state get_state() const { return e_state(_state.load()); } time_point get_keep_alive_end() const { return _keep_alive_end; } void gest_keepalive(const response_ptr& response); + + virtual asio::ip::tcp::socket& get_socket() = 0; + + asio::ip::tcp::endpoint& get_peer() { return _peer; } + const asio::ip::tcp::endpoint& get_peer() const { return _peer; } }; +/** + * @brief This initializer is used by https client or server connection to init + * ssl context In order to have the same signature, this parameter is passed to + * http_connection::load with nullptr as default value even if it is not + * used + * + */ +using ssl_ctx_initializer = + std::function; + +/** + * @brief this functor is used by client and server to create needed connection + * this constructor allow server and client to work either with http or https + * + */ +using connection_creator = std::function; + /** * @brief this class manages a tcp connection * it's used by client object to send request * constructor is protected because load is mandatory - * this object musn't be create on stack and must be allocated + * this object mustn't be create on stack and must be allocated * */ class http_connection : public connection_base { @@ -174,11 +230,14 @@ class http_connection : public connection_base { protected: http_connection(const std::shared_ptr& io_context, const std::shared_ptr& logger, - const http_config::pointer& conf); + const http_config::pointer& conf, + const ssl_ctx_initializer& ssl_initializer = nullptr); void on_connect(const boost::beast::error_code& err, const connect_callback_type& callback); + void init_keep_alive(); + void on_sent(const boost::beast::error_code& err, request_ptr request, send_callback_type& callback); @@ -196,7 +255,8 @@ class http_connection : public connection_base { static pointer load(const std::shared_ptr& io_context, const std::shared_ptr& logger, - const http_config::pointer& conf); + const http_config::pointer& conf, + const ssl_ctx_initializer& ssl_initializer = nullptr); ~http_connection(); @@ -205,24 +265,30 @@ class http_connection : public connection_base { void connect(connect_callback_type&& callback) override; void send(request_ptr request, send_callback_type&& callback) override; -}; -} // namespace http_client + void on_accept(connect_callback_type&& callback) override; -} + void answer(const response_ptr& response, + answer_callback_type&& callback) override; + void receive_request(request_callback_type&& callback) override; + + asio::ip::tcp::socket& get_socket() override; +}; + +} // namespace com::centreon::common::http namespace fmt { template <> -struct formatter +struct formatter : ostream_formatter {}; template <> -struct formatter +struct formatter : ostream_formatter {}; template <> -struct formatter +struct formatter : ostream_formatter {}; } // namespace fmt diff --git a/common/http/inc/com/centreon/common/http/http_server.hh b/common/http/inc/com/centreon/common/http/http_server.hh new file mode 100644 index 00000000000..7c9d680083b --- /dev/null +++ b/common/http/inc/com/centreon/common/http/http_server.hh @@ -0,0 +1,68 @@ +/** + * Copyright 2024 Centreon (https://www.centreon.com/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ + +#ifndef CCB_HTTP_SERVER_HH__ +#define CCB_HTTP_SERVER_HH__ + +#include "http_config.hh" +#include "http_connection.hh" + +namespace com::centreon::common::http { + +/** + * @brief This class is an http(s) server + * the difference between http and https server is the connection builder passed + * in constructor parameter + * + */ +class server : public std::enable_shared_from_this { + private: + const std::shared_ptr _io_context; + const std::shared_ptr _logger; + http_config::pointer _conf; + connection_creator _conn_creator; + asio::ip::tcp::acceptor _acceptor; + std::mutex _acceptor_m; + + void start_accept(); + + void on_accept(const boost::beast::error_code& err, + const connection_base::pointer& conn); + + public: + using pointer = std::shared_ptr; + + server(const std::shared_ptr& io_context, + const std::shared_ptr& logger, + const http_config::pointer& conf, + connection_creator&& conn_creator); + + ~server(); + + static pointer load(const std::shared_ptr& io_context, + const std::shared_ptr& logger, + const http_config::pointer& conf, + connection_creator&& conn_creator); + + void shutdown(); +}; + +} // namespace com::centreon::common::http + +#endif diff --git a/broker/http_client/inc/com/centreon/broker/http_client/https_connection.hh b/common/http/inc/com/centreon/common/http/https_connection.hh similarity index 57% rename from broker/http_client/inc/com/centreon/broker/http_client/https_connection.hh rename to common/http/inc/com/centreon/common/http/https_connection.hh index 1fff51f1e09..049b5824735 100644 --- a/broker/http_client/inc/com/centreon/broker/http_client/https_connection.hh +++ b/common/http/inc/com/centreon/common/http/https_connection.hh @@ -1,29 +1,29 @@ -/* -** Copyright 2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2024 Centreon (https://www.centreon.com/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCB_HTTPS_CLIENT_CONNECTION_HH__ #define CCB_HTTPS_CLIENT_CONNECTION_HH__ #include "http_connection.hh" -namespace com::centreon::broker { +namespace com::centreon::common::http { -namespace http_client { /** * @brief https version of http_connection * interface is the same @@ -42,7 +42,8 @@ class https_connection : public connection_base { https_connection(const std::shared_ptr& io_context, const std::shared_ptr& logger, - const http_config::pointer& conf); + const http_config::pointer& conf, + const ssl_ctx_initializer& ssl_init); void on_handshake(const boost::beast::error_code err, const connect_callback_type& callback); @@ -50,6 +51,8 @@ class https_connection : public connection_base { void on_connect(const boost::beast::error_code& err, connect_callback_type& callback); + void init_keep_alive(); + void on_sent(const boost::beast::error_code& err, request_ptr request, send_callback_type& callback); @@ -67,7 +70,9 @@ class https_connection : public connection_base { static pointer load(const std::shared_ptr& io_context, const std::shared_ptr& logger, - const http_config::pointer& conf); + const http_config::pointer& conf, + const ssl_ctx_initializer& ssl_init = + https_connection::load_client_certificate); ~https_connection(); @@ -76,10 +81,19 @@ class https_connection : public connection_base { void connect(connect_callback_type&& callback) override; void send(request_ptr request, send_callback_type&& callback) override; -}; -} // namespace http_client + void on_accept(connect_callback_type&& callback) override; + + void answer(const response_ptr& response, + answer_callback_type&& callback) override; + void receive_request(request_callback_type&& callback) override; + + asio::ip::tcp::socket& get_socket() override; + + static void load_client_certificate(asio::ssl::context& ctx, + const http_config::pointer& conf); +}; -} +} // namespace com::centreon::common::http #endif // CCB_HTTPS_CLIENT_CONNEXION_HH__ diff --git a/broker/http_client/src/http_client.cc b/common/http/src/http_client.cc similarity index 98% rename from broker/http_client/src/http_client.cc rename to common/http/src/http_client.cc index 2fbcbf060b9..fee72c2c674 100644 --- a/broker/http_client/src/http_client.cc +++ b/common/http/src/http_client.cc @@ -1,5 +1,5 @@ /** - * Copyright 2022 Centreon (https://www.centreon.com/) + * Copyright 2024 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,12 +17,11 @@ * */ -#include "com/centreon/common/defer.hh" +#include "defer.hh" #include "http_client.hh" -using namespace com::centreon::broker; -using namespace com::centreon::broker::http_client; +using namespace com::centreon::common::http; using lock_guard = std::lock_guard; @@ -52,7 +51,7 @@ client::client(const std::shared_ptr& io_context, _busy_conns.reserve(conf->get_max_connections()); // create all connection ready to connect for (unsigned cpt = 0; cpt < conf->get_max_connections(); ++cpt) { - _not_connected_conns.insert(conn_creator(io_context, logger, conf)); + _not_connected_conns.insert(conn_creator()); } } diff --git a/broker/http_client/src/http_connection.cc b/common/http/src/http_connection.cc similarity index 69% rename from broker/http_client/src/http_connection.cc rename to common/http/src/http_connection.cc index eabdc412d8a..8f7ce8f6e52 100644 --- a/broker/http_client/src/http_connection.cc +++ b/common/http/src/http_connection.cc @@ -1,5 +1,5 @@ /** - * Copyright 2022 Centreon (https://www.centreon.com/) + * Copyright 2024 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,8 +19,7 @@ #include "http_connection.hh" -using namespace com::centreon::broker; -using namespace com::centreon::broker::http_client; +using namespace com::centreon::common::http; std::string connection_base::state_to_str(unsigned state) { switch (state) { @@ -112,7 +111,8 @@ void connection_base::gest_keepalive(const response_ptr& resp) { http_connection::http_connection( const std::shared_ptr& io_context, const std::shared_ptr& logger, - const http_config::pointer& conf) + const http_config::pointer& conf, + const ssl_ctx_initializer&) : connection_base(io_context, logger, conf), _socket(boost::beast::net::make_strand(*io_context)) { SPDLOG_LOGGER_DEBUG(_logger, "create http_connection {:p} to {}", @@ -136,7 +136,8 @@ http_connection::~http_connection() { http_connection::pointer http_connection::load( const std::shared_ptr& io_context, const std::shared_ptr& logger, - const http_config::pointer& conf) { + const http_config::pointer& conf, + const ssl_ctx_initializer&) { return pointer(new http_connection(io_context, logger, conf)); } @@ -173,6 +174,7 @@ void http_connection::connect(connect_callback_type&& callback) { /** * @brief connect handler + * in case of success, it initializes tcp keepalive * * @param err * @param callback @@ -193,34 +195,63 @@ void http_connection::on_connect(const boost::beast::error_code& err, BAD_CONNECT_STATE_ERROR("on_connect to {}, bad state {}"); } + { + std::lock_guard l(_socket_m); + boost::system::error_code ec; + _peer = _socket.socket().remote_endpoint(ec); + init_keep_alive(); + } + SPDLOG_LOGGER_DEBUG(_logger, "{:p} connected to {}", static_cast(this), + _peer); + + callback(err, {}); +} + +/** + * @brief to call in case of we are an http server + * it initialize http keepalive + * callback is useless in this case but is mandatory to have the same interface + * than https_connection + * + * @param callback called via io_context::post + */ +void http_connection::on_accept(connect_callback_type&& callback) { + unsigned expected = e_not_connected; + if (!_state.compare_exchange_strong(expected, e_idle)) { + BAD_CONNECT_STATE_ERROR("on_tcp_connect to {}, bad state {}"); + } + + std::lock_guard l(_socket_m); + init_keep_alive(); + + SPDLOG_LOGGER_DEBUG(_logger, "{:p} accepted from {}", + static_cast(this), _peer); + + _io_context->post([cb = std::move(callback)]() { cb({}, ""); }); +} + +void http_connection::init_keep_alive() { // we put first keepalive option and then keepalive intervals // system default interval are 7200s witch is too long to maintain a NAT boost::system::error_code err_keep_alive; asio::socket_base::keep_alive opt1(true); - { - std::lock_guard l(_socket_m); - _socket.socket().set_option(opt1, err_keep_alive); + _socket.socket().set_option(opt1, err_keep_alive); + if (err_keep_alive) { + SPDLOG_LOGGER_ERROR(_logger, "fail to activate keep alive for {}", *_conf); + } else { + tcp_keep_alive_interval opt2(_conf->get_second_tcp_keep_alive_interval()); + _socket.socket().set_option(opt2, err_keep_alive); if (err_keep_alive) { - SPDLOG_LOGGER_ERROR(_logger, "fail to activate keep alive for {}", + SPDLOG_LOGGER_ERROR(_logger, "fail to modify keep alive interval for {}", *_conf); - } else { - tcp_keep_alive_interval opt2(_conf->get_second_tcp_keep_alive_interval()); - _socket.socket().set_option(opt2, err_keep_alive); - if (err_keep_alive) { - SPDLOG_LOGGER_ERROR( - _logger, "fail to modify keep alive interval for {}", *_conf); - } - tcp_keep_alive_idle opt3(_conf->get_second_tcp_keep_alive_interval()); - _socket.socket().set_option(opt3, err_keep_alive); - if (err_keep_alive) { - SPDLOG_LOGGER_ERROR( - _logger, "fail to modify first keep alive delay for {}", *_conf); - } } - SPDLOG_LOGGER_DEBUG(_logger, "{:p} connected to {}", - static_cast(this), _conf->get_endpoint()); + tcp_keep_alive_idle opt3(_conf->get_second_tcp_keep_alive_interval()); + _socket.socket().set_option(opt3, err_keep_alive); + if (err_keep_alive) { + SPDLOG_LOGGER_ERROR( + _logger, "fail to modify first keep alive delay for {}", *_conf); + } } - callback(err, {}); } #define BAD_SEND_STATE_ERROR(error_string) \ @@ -248,12 +279,12 @@ void http_connection::send(request_ptr request, send_callback_type&& callback) { request->_send = system_clock::now(); if (_logger->level() == spdlog::level::trace) { - SPDLOG_LOGGER_TRACE( - _logger, "{:p} send request {} to {}", static_cast(this), - static_cast(*request), _conf->get_endpoint()); + SPDLOG_LOGGER_TRACE(_logger, "{:p} send request {} to {}", + static_cast(this), + static_cast(*request), _peer); } else { SPDLOG_LOGGER_DEBUG(_logger, "{:p} send request to {}", - static_cast(this), _conf->get_endpoint()); + static_cast(this), _peer); } std::lock_guard l(_socket_m); _socket.expires_after(_conf->get_send_timeout()); @@ -353,6 +384,80 @@ void http_connection::on_read(const boost::beast::error_code& err, callback(err, {}, resp); } +void http_connection::answer(const response_ptr& response, + answer_callback_type&& callback) { + unsigned expected = e_idle; + if (!_state.compare_exchange_strong(expected, e_send)) { + std::string detail = fmt::format( + "{:p}" + "answer to {}, bad state {}", + static_cast(this), _peer, state_to_str(expected)); + SPDLOG_LOGGER_ERROR(_logger, detail); + _io_context->post([cb = std::move(callback), detail]() { + cb(std::make_error_code(std::errc::invalid_argument), detail); + }); + return; + } + + std::lock_guard l(_socket_m); + _socket.expires_after(_conf->get_send_timeout()); + boost::beast::http::async_write( + _socket, *response, + [me = shared_from_this(), response, cb = std::move(callback)]( + const boost::beast::error_code& ec, size_t) mutable { + if (ec) { + SPDLOG_LOGGER_ERROR(me->_logger, + "{:p} fail to send response {} to {}: {}", + static_cast(me.get()), *response, + me->get_peer(), ec.message()); + me->shutdown(); + } else { + unsigned expected = e_send; + me->_state.compare_exchange_strong(expected, e_idle); + } + SPDLOG_LOGGER_TRACE(me->_logger, "{:p} response sent: {}", + static_cast(me.get()), *response); + cb(ec, ""); + }); +} + +void http_connection::receive_request(request_callback_type&& callback) { + unsigned expected = e_idle; + if (!_state.compare_exchange_strong(expected, e_receive)) { + std::string detail = fmt::format( + "{:p}" + "receive_request from {}, bad state {}", + static_cast(this), _peer, state_to_str(expected)); + SPDLOG_LOGGER_ERROR(_logger, detail); + _io_context->post([cb = std::move(callback), detail]() { + cb(std::make_error_code(std::errc::invalid_argument), detail, + std::shared_ptr()); + }); + return; + } + + std::lock_guard l(_socket_m); + _socket.expires_after(_conf->get_receive_timeout()); + auto req = std::make_shared(); + boost::beast::http::async_read( + _socket, _recv_buffer, *req, + [me = shared_from_this(), req, cb = std::move(callback)]( + const boost::beast::error_code& ec, std::size_t) mutable { + if (ec) { + SPDLOG_LOGGER_ERROR( + me->_logger, "{:p} fail to receive request from {}: {}", + static_cast(me.get()), me->get_peer(), ec.message()); + me->shutdown(); + } else { + unsigned expected = e_receive; + me->_state.compare_exchange_strong(expected, e_idle); + } + SPDLOG_LOGGER_TRACE(me->_logger, "{:p} receive: {}", + static_cast(me.get()), *req); + cb(ec, "", req); + }); +} + /** * @brief shutdown socket and close * @@ -366,3 +471,12 @@ void http_connection::shutdown() { _socket.socket().shutdown(boost::asio::socket_base::shutdown_both, err); _socket.close(); } + +/** + * @brief get underlay socket + * + * @return asio::ip::tcp::socket& + */ +asio::ip::tcp::socket& http_connection::get_socket() { + return _socket.socket(); +} diff --git a/common/http/src/http_server.cc b/common/http/src/http_server.cc new file mode 100644 index 00000000000..16bfa336d36 --- /dev/null +++ b/common/http/src/http_server.cc @@ -0,0 +1,95 @@ +/** + * Copyright 2024 Centreon (https://www.centreon.com/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ + +#include "http_server.hh" + +using namespace com::centreon::common::http; + +server::server(const std::shared_ptr& io_context, + const std::shared_ptr& logger, + const http_config::pointer& conf, + connection_creator&& conn_creator) + : _io_context(io_context), + _logger(logger), + _conf(conf), + _conn_creator(conn_creator), + _acceptor(*io_context) { + _acceptor.open(_conf->get_endpoint().protocol()); + _acceptor.set_option(asio::ip::tcp::socket::reuse_address(true)); + + // Bind to the server address + _acceptor.bind(_conf->get_endpoint()); + // Start listening for connections + _acceptor.listen(asio::ip::tcp::socket::max_listen_connections); +} + +server::~server() { + shutdown(); +} + +server::pointer server::load( + const std::shared_ptr& io_context, + const std::shared_ptr& logger, + const http_config::pointer& conf, + connection_creator&& conn_creator) { + std::shared_ptr ret = std::make_shared( + io_context, logger, conf, std::move(conn_creator)); + + ret->start_accept(); + + SPDLOG_LOGGER_INFO(logger, "server listen on {}", conf->get_endpoint()); + + return ret; +} + +void server::start_accept() { + connection_base::pointer future_conn = _conn_creator(); + std::lock_guard l(_acceptor_m); + _acceptor.async_accept(future_conn->get_socket(), future_conn->get_peer(), + [future_conn, me = shared_from_this()]( + const boost::beast::error_code& err) { + me->on_accept(err, future_conn); + }); +} + +void server::on_accept(const boost::beast::error_code& err, + const connection_base::pointer& conn) { + if (err) { + SPDLOG_LOGGER_ERROR(_logger, "fail accept connection on {}: {}", + _conf->get_endpoint(), err.message()); + return; + } + SPDLOG_LOGGER_DEBUG(_logger, "connection accepted from {} to {}", + conn->get_peer(), _conf->get_endpoint()); + conn->on_accept(); + + start_accept(); +} + +void server::shutdown() { + std::lock_guard l(_acceptor_m); + boost::system::error_code ec; + _acceptor.close(ec); + if (ec) { + SPDLOG_LOGGER_ERROR(_logger, "error at server shutdown on {}: {}", + _conf->get_endpoint(), ec.message()); + } else { + SPDLOG_LOGGER_INFO(_logger, "server shutdown {}", _conf->get_endpoint()); + } +} diff --git a/broker/http_client/src/https_connection.cc b/common/http/src/https_connection.cc similarity index 65% rename from broker/http_client/src/https_connection.cc rename to common/http/src/https_connection.cc index b6928f6f07a..7e2e68e59d3 100644 --- a/broker/http_client/src/https_connection.cc +++ b/common/http/src/https_connection.cc @@ -1,5 +1,5 @@ /** - * Copyright 2022 Centreon (https://www.centreon.com/) + * Copyright 2024 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,15 +23,13 @@ #include "https_connection.hh" -using namespace com::centreon::broker; using namespace com::centreon::exceptions; -using namespace com::centreon::broker::http_client; +using namespace com::centreon::common::http; namespace beast = boost::beast; -namespace com::centreon::broker { +namespace com::centreon::common::http::detail { -namespace http_client::detail { /** * @brief to avoid read certificate on each request, this singleton do the job * it maintains a certificate cache @@ -119,9 +117,7 @@ void certificate_cache::clean() { } } -}; // namespace http_client::detail - -} // namespace com::centreon::broker +} // namespace com::centreon::common::http::detail /** * @brief Construct a new https connection::https connection object @@ -134,23 +130,20 @@ void certificate_cache::clean() { https_connection::https_connection( const std::shared_ptr& io_context, const std::shared_ptr& logger, - const http_config::pointer& conf) + const http_config::pointer& conf, + const ssl_ctx_initializer& ssl_init) : connection_base(io_context, logger, conf), - _sslcontext(conf->get_ssl_method()), - _stream(std::make_unique(beast::net::make_strand(*io_context), - _sslcontext)) { - if (!_conf->get_certificate_path().empty()) { - std::shared_ptr cert_content = - detail::certificate_cache::get_mutable_instance().get_certificate( - _conf->get_certificate_path()); - _sslcontext.add_certificate_authority( - asio::buffer(cert_content->c_str(), cert_content->length())); - } - SPDLOG_LOGGER_DEBUG(_logger, "create https_connection to {}", *conf); + _sslcontext(conf->get_ssl_method()) { + ssl_init(_sslcontext, conf); + _stream = std::make_unique(beast::net::make_strand(*io_context), + _sslcontext); + SPDLOG_LOGGER_DEBUG(_logger, "create https_connection {:p} to {}", + static_cast(this), *conf); } https_connection::~https_connection() { - SPDLOG_LOGGER_DEBUG(_logger, "delete https_connection to {}", *_conf); + SPDLOG_LOGGER_DEBUG(_logger, "delete https_connection {:p} to {}", + static_cast(this), *_conf); } /** @@ -164,8 +157,9 @@ https_connection::~https_connection() { https_connection::pointer https_connection::load( const std::shared_ptr& io_context, const std::shared_ptr& logger, - const http_config::pointer& conf) { - return pointer(new https_connection(io_context, logger, conf)); + const http_config::pointer& conf, + const ssl_ctx_initializer& ssl_init) { + return pointer(new https_connection(io_context, logger, conf, ssl_init)); } #define BAD_CONNECT_STATE_ERROR(error_string) \ @@ -188,7 +182,8 @@ void https_connection::connect(connect_callback_type&& callback) { BAD_CONNECT_STATE_ERROR("can connect to {}, bad state {}"); } - SPDLOG_LOGGER_DEBUG(_logger, "connect to {}", *_conf); + SPDLOG_LOGGER_DEBUG(_logger, "{:p} connect to {}", static_cast(this), + *_conf); std::lock_guard l(_socket_m); beast::get_lowest_layer(*_stream).expires_after(_conf->get_connect_timeout()); beast::get_lowest_layer(*_stream).async_connect( @@ -219,6 +214,22 @@ void https_connection::on_connect(const beast::error_code& err, } std::lock_guard l(_socket_m); + + boost::system::error_code ec; + _peer = beast::get_lowest_layer(*_stream).socket().remote_endpoint(ec); + + init_keep_alive(); + SPDLOG_LOGGER_DEBUG(_logger, "{:p} connected to {}", static_cast(this), + _peer); + + // Perform the SSL handshake + _stream->async_handshake( + asio::ssl::stream_base::client, + [me = shared_from_this(), cb = std::move(callback)]( + const beast::error_code& err) { me->on_handshake(err, cb); }); +} + +void https_connection::init_keep_alive() { boost::system::error_code err_keep_alive; asio::socket_base::keep_alive opt1(true); beast::get_lowest_layer(*_stream).socket().set_option(opt1, err_keep_alive); @@ -238,11 +249,27 @@ void https_connection::on_connect(const beast::error_code& err, _logger, "fail to modify first keep alive delay for {}", *_conf); } } - SPDLOG_LOGGER_DEBUG(_logger, "connected to {}", _conf->get_endpoint()); +} + +/** + * @brief to call in case of we are an http server + * it initialize http keepalive and launch ssl handshake + * + * @param callback + */ +void https_connection::on_accept(connect_callback_type&& callback) { + unsigned expected = e_not_connected; + if (!_state.compare_exchange_strong(expected, e_handshake)) { + BAD_CONNECT_STATE_ERROR("on_tcp_connect to {}, bad state {}"); + } + SPDLOG_LOGGER_DEBUG(_logger, "{:p} accepted from {}", + static_cast(this), _peer); + std::lock_guard l(_socket_m); + init_keep_alive(); // Perform the SSL handshake _stream->async_handshake( - asio::ssl::stream_base::client, + asio::ssl::stream_base::server, [me = shared_from_this(), cb = std::move(callback)]( const beast::error_code& err) { me->on_handshake(err, cb); }); } @@ -256,8 +283,8 @@ void https_connection::on_connect(const beast::error_code& err, void https_connection::on_handshake(const beast::error_code err, const connect_callback_type& callback) { if (err) { - std::string detail = fmt::format("fail handshake to {}: {}", - _conf->get_endpoint(), err.message()); + std::string detail = + fmt::format("fail handshake with {}: {}", _peer, err.message()); SPDLOG_LOGGER_ERROR(_logger, detail); callback(err, detail); shutdown(); @@ -266,9 +293,10 @@ void https_connection::on_handshake(const beast::error_code err, unsigned expected = e_handshake; if (!_state.compare_exchange_strong(expected, e_idle)) { - BAD_CONNECT_STATE_ERROR("on_handshake to {}, bad state {}"); + BAD_CONNECT_STATE_ERROR("on_handshake with {}, bad state {}"); } - SPDLOG_LOGGER_DEBUG(_logger, "handshake done to {}", _conf->get_endpoint()); + SPDLOG_LOGGER_DEBUG(_logger, "{:p} handshake done with {}", + static_cast(this), _peer); callback(err, {}); } @@ -297,11 +325,12 @@ void https_connection::send(request_ptr request, request->_send = system_clock::now(); if (_logger->level() == spdlog::level::trace) { - SPDLOG_LOGGER_TRACE(_logger, "send request {} to {}", - static_cast(*request), - _conf->get_endpoint()); + SPDLOG_LOGGER_TRACE(_logger, "{:p} send request {} to {}", + static_cast(this), + static_cast(*request), _peer); } else { - SPDLOG_LOGGER_DEBUG(_logger, "send request to {}", _conf->get_endpoint()); + SPDLOG_LOGGER_DEBUG(_logger, "{:p} send request to {}", + static_cast(this), _peer); } std::lock_guard l(_socket_m); @@ -388,13 +417,88 @@ void https_connection::on_read(const beast::error_code& err, SPDLOG_LOGGER_ERROR(_logger, "err response for {} \n\n {}", static_cast(*request), *resp); } else { - SPDLOG_LOGGER_DEBUG(_logger, "recv response from {} {}", *_conf, *resp); + SPDLOG_LOGGER_DEBUG(_logger, "{:p} recv response from {} {}", + static_cast(this), *_conf, *resp); } gest_keepalive(resp); callback(err, {}, resp); } +void https_connection::answer(const response_ptr& response, + answer_callback_type&& callback) { + unsigned expected = e_idle; + if (!_state.compare_exchange_strong(expected, e_send)) { + std::string detail = fmt::format( + "{:p}" + "answer to {}, bad state {}", + static_cast(this), _peer, state_to_str(expected)); + SPDLOG_LOGGER_ERROR(_logger, detail); + _io_context->post([cb = std::move(callback), detail]() { + cb(std::make_error_code(std::errc::invalid_argument), detail); + }); + return; + } + + std::lock_guard l(_socket_m); + beast::get_lowest_layer(*_stream).expires_after(_conf->get_send_timeout()); + beast::http::async_write( + *_stream, *response, + [me = shared_from_this(), response, cb = std::move(callback)]( + const boost::beast::error_code& ec, size_t) mutable { + if (ec) { + SPDLOG_LOGGER_ERROR(me->_logger, + "{:p} fail to send response {} to {}: {}", + static_cast(me.get()), *response, + me->get_peer(), ec.message()); + me->shutdown(); + } else { + unsigned expected = e_send; + me->_state.compare_exchange_strong(expected, e_idle); + } + SPDLOG_LOGGER_TRACE(me->_logger, "{:p} response sent: {}", + static_cast(me.get()), *response); + cb(ec, ""); + }); +} + +void https_connection::receive_request(request_callback_type&& callback) { + unsigned expected = e_idle; + if (!_state.compare_exchange_strong(expected, e_receive)) { + std::string detail = fmt::format( + "{:p}" + "receive_request from {}, bad state {}", + static_cast(this), _peer, state_to_str(expected)); + SPDLOG_LOGGER_ERROR(_logger, detail); + _io_context->post([cb = std::move(callback), detail]() { + cb(std::make_error_code(std::errc::invalid_argument), detail, + std::shared_ptr()); + }); + return; + } + + std::lock_guard l(_socket_m); + beast::get_lowest_layer(*_stream).expires_after(_conf->get_receive_timeout()); + auto req = std::make_shared(); + beast::http::async_read( + *_stream, _recv_buffer, *req, + [me = shared_from_this(), req, cb = std::move(callback)]( + const boost::beast::error_code& ec, std::size_t) mutable { + if (ec) { + SPDLOG_LOGGER_ERROR( + me->_logger, "{:p} fail to receive request from {}: {}", + static_cast(me.get()), me->get_peer(), ec.message()); + me->shutdown(); + } else { + unsigned expected = e_receive; + me->_state.compare_exchange_strong(expected, e_idle); + } + SPDLOG_LOGGER_TRACE(me->_logger, "{:p} receive: {}", + static_cast(me.get()), *req); + cb(ec, "", req); + }); +} + /** * @brief perform an async shutdown * unlike http_connection synchronous shutdown can't be done @@ -403,7 +507,8 @@ void https_connection::on_read(const beast::error_code& err, void https_connection::shutdown() { unsigned old_state = _state.exchange(e_shutdown); if (old_state != e_shutdown) { - SPDLOG_LOGGER_DEBUG(_logger, "begin shutdown {}", *_conf); + SPDLOG_LOGGER_DEBUG(_logger, "{:p} begin shutdown {}", + static_cast(this), *_conf); _state = e_shutdown; std::lock_guard l(_socket_m); _stream->async_shutdown( @@ -423,3 +528,39 @@ void https_connection::shutdown() { }); } } + +/** + * @brief get underlay socket + * + * @return asio::ip::tcp::socket& + */ +asio::ip::tcp::socket& https_connection::get_socket() { + return beast::get_lowest_layer(*_stream).socket(); +} + +/** + * @brief This helper can be passed to https_connection constructor fourth param + * when implementing https client as: + * @code {.c++} + * auto conn = https_connection::load(g_io_context, logger, + * conf,[conf](asio::ssl::context& ctx) { + * https_connection::load_client_certificate(ctx, conf); + * }); + * + * @endcode + * + * + * @param ctx + * @param conf + */ +void https_connection::load_client_certificate( + asio::ssl::context& ctx, + const http_config::pointer& conf) { + if (!conf->get_certificate_path().empty()) { + std::shared_ptr cert_content = + detail::certificate_cache::get_mutable_instance().get_certificate( + conf->get_certificate_path()); + ctx.add_certificate_authority( + asio::buffer(cert_content->c_str(), cert_content->length())); + } +} diff --git a/broker/http_client/test/http_client_test.cc b/common/http/test/http_client_test.cc similarity index 80% rename from broker/http_client/test/http_client_test.cc rename to common/http/test/http_client_test.cc index 4c04506558d..280d03f3571 100644 --- a/broker/http_client/test/http_client_test.cc +++ b/common/http/test/http_client_test.cc @@ -1,5 +1,5 @@ /** - * Copyright 2022 Centreon (https://www.centreon.com/) + * Copyright 2024 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,40 +15,35 @@ * * For more information : contact@centreon.com * - * */ -#include -#include -#include -#include -#include -#include +#include +#include -#include "com/centreon/broker/log_v2.hh" -#include "com/centreon/common/defer.hh" -#include "com/centreon/common/pool.hh" +#include "defer.hh" using system_clock = std::chrono::system_clock; using time_point = system_clock::time_point; using duration = system_clock::duration; -#include "com/centreon/broker/http_client/http_client.hh" +#include "http_client.hh" -using namespace com::centreon::broker; using namespace com::centreon::common; -using namespace com::centreon::broker::http_client; +using namespace com::centreon::common::http; extern std::shared_ptr g_io_context; const asio::ip::tcp::endpoint test_endpoint(asio::ip::make_address("127.0.0.1"), 1234); +static std::shared_ptr logger = + spdlog::stdout_color_mt("http_client_test"); + class http_client_test : public ::testing::Test { public: static void SetUpTestSuite() { srand(time(nullptr)); - log_v2::tcp()->set_level(spdlog::level::debug); + logger->set_level(spdlog::level::debug); }; }; @@ -56,13 +51,16 @@ class connection_ok : public connection_base { unsigned _connect_counter; unsigned _request_counter; + asio::ip::tcp::socket _useless; + public: connection_ok(const std::shared_ptr& io_context, const std::shared_ptr& logger, const http_config::pointer& conf) : connection_base(io_context, logger, conf), _connect_counter(0), - _request_counter(0) {} + _request_counter(0), + _useless(*io_context) {} unsigned get_connect_counter() const { return _connect_counter; } unsigned get_request_counter() const { return _request_counter; } @@ -95,21 +93,27 @@ class connection_ok : public connection_base { } ++_request_counter; } + + void on_accept(connect_callback_type&& callback) override {} + + void answer(const response_ptr& response, + answer_callback_type&& callback) override {} + void receive_request(request_callback_type&& callback) override {} + + asio::ip::tcp::socket& get_socket() override { return _useless; } }; TEST_F(http_client_test, many_request_use_all_connection) { std::vector> conns; + http_config::pointer client_conf = + std::make_shared(test_endpoint, "localhost"); client::pointer clt = - client::load(g_io_context, log_v2::tcp(), - std::make_shared(test_endpoint, "localhost"), - [&conns](const std::shared_ptr& io_context, - const std::shared_ptr& logger, - const http_config::pointer& conf) { - auto dummy_conn = std::make_shared( - io_context, logger, conf); - conns.push_back(dummy_conn); - return dummy_conn; - }); + client::load(g_io_context, logger, client_conf, [&conns, client_conf]() { + auto dummy_conn = + std::make_shared(g_io_context, logger, client_conf); + conns.push_back(dummy_conn); + return dummy_conn; + }); request_ptr request(std::make_shared()); @@ -145,15 +149,12 @@ TEST_F(http_client_test, recycle_connection) { std::vector> conns; auto conf = std::make_shared(test_endpoint, "localhost"); client::pointer clt = - client::load(g_io_context, log_v2::tcp(), conf, - [&conns](const std::shared_ptr& io_context, - const std::shared_ptr& logger, - const http_config::pointer& conf) { - auto dummy_conn = std::make_shared( - io_context, logger, conf); - conns.push_back(dummy_conn); - return dummy_conn; - }); + client::load(g_io_context, logger, conf, [&conns, conf]() { + auto dummy_conn = + std::make_shared(g_io_context, logger, conf); + conns.push_back(dummy_conn); + return dummy_conn; + }); struct sender { request_ptr request = std::make_shared(); @@ -201,6 +202,8 @@ TEST_F(http_client_test, recycle_connection) { *************************************************************************/ class connection_bagot : public connection_base { + asio::ip::tcp::socket _useless; + public: enum fail_stage { no_fail = 0, fail_connect, fail_send }; @@ -211,7 +214,7 @@ class connection_bagot : public connection_base { connection_bagot(const std::shared_ptr& io_context, const std::shared_ptr& logger, const http_config::pointer& conf) - : connection_base(io_context, logger, conf) {} + : connection_base(io_context, logger, conf), _useless(*io_context) {} fail_stage get_fail_stage() const { return _fail_stage; } @@ -262,28 +265,33 @@ class connection_bagot : public connection_base { } } } + + void on_accept(connect_callback_type&& callback) override {} + + void answer(const response_ptr& response, + answer_callback_type&& callback) override {} + void receive_request(request_callback_type&& callback) override {} + + asio::ip::tcp::socket& get_socket() override { return _useless; } }; -class client_test : public http_client::client { +class client_test : public client { public: client_test(const std::shared_ptr& io_context, const std::shared_ptr& logger, - const http_client::http_config::pointer& conf, - http_client::client::connection_creator conn_creator) - : http_client::client(io_context, logger, conf, conn_creator) { + const http_config::pointer& conf, + connection_creator conn_creator) + : client(io_context, logger, conf, conn_creator) { _retry_unit = std::chrono::milliseconds(1); } }; TEST_F(http_client_test, all_handler_called) { + auto client_conf = std::make_shared(test_endpoint, "localhost"); client::pointer clt = std::make_shared( - g_io_context, log_v2::tcp(), - std::make_shared(test_endpoint, "localhost"), - [](const std::shared_ptr& io_context, - const std::shared_ptr& logger, - const http_config::pointer& conf) { - auto dummy_conn = - std::make_shared(io_context, logger, conf); + g_io_context, logger, client_conf, [client_conf]() { + auto dummy_conn = std::make_shared( + g_io_context, logger, client_conf); return dummy_conn; }); @@ -312,8 +320,8 @@ TEST_F(http_client_test, all_handler_called) { return error_handler_cpt + success_handler_cpt == 1000; }); - SPDLOG_LOGGER_INFO(log_v2::tcp(), "success:{}, failed:{}", - success_handler_cpt, error_handler_cpt); + SPDLOG_LOGGER_INFO(logger, "success:{}, failed:{}", success_handler_cpt, + error_handler_cpt); ASSERT_NE(error_handler_cpt, 0); ASSERT_NE(success_handler_cpt, 0); ASSERT_EQ(error_handler_cpt + success_handler_cpt, 1000); @@ -369,13 +377,10 @@ unsigned connection_retry::failed_before_success; TEST_F(http_client_test, retry_until_success) { connection_retry::nb_failed_per_request.clear(); auto conf = std::make_shared(test_endpoint, "localhost"); - client::pointer clt = std::make_shared( - g_io_context, log_v2::tcp(), conf, - [](const std::shared_ptr& io_context, - const std::shared_ptr& logger, - const http_config::pointer& conf) { + client::pointer clt = + std::make_shared(g_io_context, logger, conf, [conf]() { auto dummy_conn = - std::make_shared(io_context, logger, conf); + std::make_shared(g_io_context, logger, conf); return dummy_conn; }); diff --git a/broker/http_client/test/http_connection_test.cc b/common/http/test/http_connection_test.cc similarity index 63% rename from broker/http_client/test/http_connection_test.cc rename to common/http/test/http_connection_test.cc index 9cf757f64d6..fdcb820e9bd 100644 --- a/broker/http_client/test/http_connection_test.cc +++ b/common/http/test/http_connection_test.cc @@ -1,5 +1,5 @@ /** - * Copyright 2022 Centreon (https://www.centreon.com/) + * Copyright 2024 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,24 +15,21 @@ * * For more information : contact@centreon.com * - * */ + #include -#include -#include -#include -#include "com/centreon/broker/log_v2.hh" +#include using system_clock = std::chrono::system_clock; using time_point = system_clock::time_point; using duration = system_clock::duration; -#include "com/centreon/broker/http_client/http_connection.hh" -#include "com/centreon/broker/http_client/https_connection.hh" +#include "http_connection.hh" +#include "http_server.hh" +#include "https_connection.hh" -using namespace com::centreon::broker; -using namespace com::centreon::broker::http_client; +using namespace com::centreon::common::http; namespace beast = boost::beast; extern std::shared_ptr g_io_context; @@ -42,6 +39,9 @@ constexpr unsigned port = 5796; const asio::ip::tcp::endpoint test_endpoint(asio::ip::make_address("127.0.0.1"), port); +const asio::ip::tcp::endpoint listen_endpoint(asio::ip::make_address("0.0.0.0"), + port); + static void create_client_certificate(const std::string& path) { ::remove(path.c_str()); std::ofstream f(path); @@ -93,7 +93,8 @@ static void create_client_certificate(const std::string& path) { "\n"; } -static void load_server_certificate(boost::asio::ssl::context& ctx) { +static void load_server_certificate(boost::asio::ssl::context& ctx, + const http_config::pointer&) { /* The certificate was generated from bash on Ubuntu (OpenSSL 1.1.1f) using: @@ -183,28 +184,40 @@ static void load_server_certificate(boost::asio::ssl::context& ctx) { ctx.use_tmp_dh(boost::asio::buffer(dh.data(), dh.size())); } +static std::shared_ptr logger = + spdlog::stdout_color_mt("http_connection_test"); + /********************************************************************* * http keepalive test *********************************************************************/ class dummy_connection : public connection_base { + asio::ip::tcp::socket _useless; + public: void set_state(int state) { _state = state; } dummy_connection(const std::shared_ptr& io_context, const std::shared_ptr& logger, const http_config::pointer& conf) - : connection_base(io_context, logger, conf) {} + : connection_base(io_context, logger, conf), _useless(*io_context) {} void shutdown() override { _state = e_not_connected; } void connect(connect_callback_type&& callback) override {} void send(request_ptr request, send_callback_type&& callback) override {} + + void on_accept(connect_callback_type&& callback) override{}; + void answer(const response_ptr& response, + answer_callback_type&& callback) override{}; + void receive_request(request_callback_type&& callback) override{}; + + asio::ip::tcp::socket& get_socket() override { return _useless; } }; TEST(http_keepalive_test, ConnectionClose) { dummy_connection conn( - g_io_context, log_v2::tcp(), + g_io_context, logger, std::make_shared(test_endpoint, "localhost")); response_ptr resp(std::make_shared()); resp->keep_alive(false); @@ -215,7 +228,7 @@ TEST(http_keepalive_test, ConnectionClose) { TEST(http_keepalive_test, KeepAliveWithoutTimeout) { auto conf = std::make_shared(test_endpoint, "localhost"); - dummy_connection conn(g_io_context, log_v2::tcp(), conf); + dummy_connection conn(g_io_context, logger, conf); response_ptr resp(std::make_shared()); resp->keep_alive(true); conn.set_state(connection_base::e_idle); @@ -231,7 +244,7 @@ TEST(http_keepalive_test, KeepAliveWithoutTimeout) { TEST(http_keepalive_test, KeepAliveWithTimeout) { auto conf = std::make_shared(test_endpoint, "localhost"); - dummy_connection conn(g_io_context, log_v2::tcp(), conf); + dummy_connection conn(g_io_context, logger, conf); response_ptr resp(std::make_shared()); resp->keep_alive(true); resp->set(beast::http::field::keep_alive, "timeout=5, max=1000"); @@ -250,195 +263,6 @@ TEST(http_keepalive_test, KeepAliveWithTimeout) { * connection test *********************************************************************/ -class session_base : public std::enable_shared_from_this { - protected: - std::shared_ptr _logger; - - public: - using pointer = std::shared_ptr; - - session_base() : _logger(log_v2::tcp()) {} - virtual ~session_base() { SPDLOG_LOGGER_TRACE(_logger, "end session"); } - - virtual void on_receive(const beast::error_code& err, - const request_ptr& request) = 0; - - virtual void send_response(const response_ptr&) = 0; - virtual void shutdown() = 0; - virtual void start() = 0; -}; - -using creator_fct = std::function& /*null if no crypted*/)>; - -static creator_fct creator; - -class http_session : public session_base { - boost::beast::tcp_stream _stream; - boost::beast::flat_buffer _buffer; - - void start_recv() { - request_ptr request(std::make_shared()); - beast::http::async_read( - _stream, _buffer, *request, - [me = shared_from_this(), request](const beast::error_code& err, - std::size_t bytes_received) { - if (err) { - SPDLOG_LOGGER_ERROR(me->_logger, "fail recv {}", err.message()); - me->shutdown(); - } else { - SPDLOG_LOGGER_TRACE(me->_logger, "recv {} bytes", bytes_received); - me->on_receive(err, request); - me->start_recv(); - } - }); - } - - public: - http_session(asio::ip::tcp::socket&& socket, - const std::shared_ptr&) - : _stream(std::move(socket)) {} - - std::shared_ptr shared_from_this() { - return std::static_pointer_cast( - session_base::shared_from_this()); - } - - void start() override { - SPDLOG_LOGGER_TRACE(_logger, "start a session"); - start_recv(); - } - - void send_response(const response_ptr& resp) override { - SPDLOG_LOGGER_TRACE(_logger, "send response"); - beast::http::async_write( - _stream, *resp, - [me = shared_from_this(), resp](const beast::error_code& err, - std::size_t bytes_sent) { - if (err) { - SPDLOG_LOGGER_ERROR(me->_logger, "fail send response"); - me->shutdown(); - } - }); - } - - void shutdown() override { - _stream.socket().shutdown(asio::ip::tcp::socket::shutdown_both); - _stream.close(); - } -}; - -class https_session : public session_base { - beast::ssl_stream _stream; - beast::flat_buffer _buffer; - - void start_recv() { - request_ptr request(std::make_shared()); - beast::http::async_read( - _stream, _buffer, *request, - [me = shared_from_this(), request](const beast::error_code& err, - std::size_t bytes_received) { - if (err) { - SPDLOG_LOGGER_ERROR(me->_logger, "fail recv {}", err.message()); - me->shutdown(); - } else { - SPDLOG_LOGGER_TRACE(me->_logger, "recv {} bytes", bytes_received); - me->on_receive(err, request); - me->start_recv(); - } - }); - } - - public: - https_session(asio::ip::tcp::socket&& socket, - const std::shared_ptr& ctx) - : _stream(std::move(socket), *ctx) {} - - std::shared_ptr shared_from_this() { - return std::static_pointer_cast( - session_base::shared_from_this()); - } - - void start() override { - SPDLOG_LOGGER_TRACE(_logger, "start a session"); - _stream.async_handshake( - asio::ssl::stream_base::server, - [me = shared_from_this()](const beast::error_code& err) { - me->on_handshake(err); - }); - } - - void on_handshake(const beast::error_code& err) { - if (err) { - SPDLOG_LOGGER_TRACE(_logger, "{} fail handshake {}", __FUNCTION__, - err.message()); - shutdown(); - return; - } - SPDLOG_LOGGER_TRACE(_logger, "handshake done"); - start_recv(); - } - - void send_response(const response_ptr& resp) override { - SPDLOG_LOGGER_TRACE(_logger, "send response"); - beast::http::async_write( - _stream, *resp, - [me = shared_from_this(), resp](const beast::error_code& err, - std::size_t bytes_sent) { - if (err) { - SPDLOG_LOGGER_ERROR(me->_logger, "fail send response"); - me->shutdown(); - } - }); - } - - void shutdown() override { - _stream.async_shutdown( - [me = shared_from_this()](const beast::error_code&) {}); - } -}; - -class listener : public std::enable_shared_from_this { - protected: - std::shared_ptr _ssl_context; - asio::ip::tcp::acceptor _acceptor; - std::shared_ptr _logger; - - void do_accept() { - // The new connection gets its own strand - _acceptor.async_accept( - asio::make_strand(*g_io_context), - beast::bind_front_handler(&listener::on_accept, shared_from_this())); - } - - void on_accept(const beast::error_code& ec, asio::ip::tcp::socket socket) { - if (ec) { - SPDLOG_LOGGER_ERROR(_logger, "fail accept"); - return; - } - SPDLOG_LOGGER_DEBUG(_logger, "accept a connection"); - auto session = creator(std::move(socket), _ssl_context); - session->start(); - do_accept(); - } - - public: - using pointer = std::shared_ptr; - - listener(unsigned port) - : _ssl_context(std::make_shared( - asio::ssl::context::sslv23_server)), - _acceptor(*g_io_context, test_endpoint, true), - _logger(log_v2::tcp()) { - load_server_certificate(*_ssl_context); - } - - void start() { do_accept(); } - - void shutdown() { _acceptor.close(); } -}; - const char* client_cert_path = "/tmp/client_test.cert"; /** @@ -446,20 +270,11 @@ const char* client_cert_path = "/tmp/client_test.cert"; * */ class http_test : public ::testing::TestWithParam { - protected: - static listener::pointer _listener; - public: static void SetUpTestSuite() { create_client_certificate(client_cert_path); - log_v2::tcp()->set_level(spdlog::level::info); - _listener = std::make_shared(port); - _listener->start(); + logger->set_level(spdlog::level::debug); }; - static void TearDownTestSuite() { - _listener->shutdown(); - _listener.reset(); - } void SetUp() override {} void TearDown() override {} @@ -476,54 +291,78 @@ class http_test : public ::testing::TestWithParam { return std::make_shared(test_endpoint, "localhost", false); } } -}; + http_config::pointer create_server_conf() { + if (GetParam()) { + return std::make_shared( + listen_endpoint, "localhost", true, std::chrono::seconds(10), + std::chrono::seconds(10), std::chrono::seconds(10), 30, + std::chrono::seconds(10), 5, std::chrono::hours(1), 10, + asio::ssl::context_base::sslv23_server); -listener::pointer http_test::_listener; + } else { + return std::make_shared( + listen_endpoint, "localhost", false, std::chrono::seconds(10), + std::chrono::seconds(10), std::chrono::seconds(10), 30, + std::chrono::seconds(10), 5, std::chrono::hours(1), 10); + } + } +}; -// simple exchange with no keepalive template class answer_no_keep_alive : public base_class { public: - answer_no_keep_alive(asio::ip::tcp::socket&& socket, - const std::shared_ptr& ssl_context) - : base_class(std::move(socket), ssl_context) {} - - void on_receive(const beast::error_code& err, const request_ptr& request) { - if (!err) { - ASSERT_EQ(request->body(), "hello server"); - response_ptr resp(std::make_shared(beast::http::status::ok, - request->version())); - resp->keep_alive(false); - resp->body() = "hello client"; - resp->content_length(resp->body().length()); - base_class::send_response(resp); - } + using my_type = answer_no_keep_alive; + + answer_no_keep_alive(const std::shared_ptr& io_context, + const std::shared_ptr& logger, + const http_config::pointer& conf, + const ssl_ctx_initializer& ssl_initializer) + : base_class(io_context, logger, conf, ssl_initializer) {} + + void on_accept() override { + base_class::on_accept([me = base_class::shared_from_this()]( + const boost::beast::error_code ec, + const std::string&) { + ASSERT_FALSE(ec); + me->receive_request([me](const boost::beast::error_code ec, + const std::string&, + const std::shared_ptr& request) { + ASSERT_FALSE(ec); + ASSERT_EQ(request->body(), "hello server"); + response_ptr resp(std::make_shared( + beast::http::status::ok, request->version())); + resp->keep_alive(false); + resp->body() = "hello client"; + resp->content_length(resp->body().length()); + me->answer(resp, [](const boost::beast::error_code ec, + const std::string&) { ASSERT_FALSE(ec); }); + }); + }); } }; TEST_P(http_test, connect_send_answer_without_keepalive) { std::shared_ptr conn; - http_config::pointer conf = create_conf(); + http_config::pointer client_conf = create_conf(); + http_config::pointer server_conf = create_server_conf(); + + connection_creator server_creator; if (GetParam()) { // crypted - creator = [](asio::ip::tcp::socket&& socket, - const std::shared_ptr& ctx) - -> session_base::pointer { - return std::make_shared>( - std::move(socket), ctx); + server_creator = [server_conf]() { + return std::make_shared>( + g_io_context, logger, server_conf, load_server_certificate); }; } else { - creator = [](asio::ip::tcp::socket&& socket, - const std::shared_ptr& ctx) - -> session_base::pointer { - return std::make_shared>( - std::move(socket), ctx); + server_creator = [server_conf]() { + return std::make_shared>( + g_io_context, logger, server_conf, nullptr); }; } auto client = GetParam() - ? https_connection::load(g_io_context, log_v2::tcp(), conf) - : http_connection::load(g_io_context, log_v2::tcp(), conf); + ? https_connection::load(g_io_context, logger, client_conf) + : http_connection::load(g_io_context, logger, client_conf); request_ptr request(std::make_shared()); request->method(beast::http::verb::put); request->target("/"); @@ -533,6 +372,9 @@ TEST_P(http_test, connect_send_answer_without_keepalive) { auto f(p.get_future()); time_point send_begin = system_clock::now(); + auto serv = server::load(g_io_context, logger, server_conf, + std::move(server_creator)); + client->connect([&p, client, request](const beast::error_code& err, const std::string& detail) { if (err) { @@ -548,13 +390,17 @@ TEST_P(http_test, connect_send_answer_without_keepalive) { auto completion = f.get(); time_point send_end = system_clock::now(); - ASSERT_LT((send_end - send_begin), std::chrono::milliseconds(100)); + ASSERT_LT(std::chrono::duration_cast(send_end - + send_begin), + std::chrono::milliseconds(200)); ASSERT_FALSE(std::get<0>(completion)); ASSERT_TRUE(std::get<1>(completion).empty()); ASSERT_EQ(std::get<2>(completion)->body(), "hello client"); ASSERT_EQ(std::get<2>(completion)->keep_alive(), false); std::this_thread::sleep_for(std::chrono::seconds(1)); ASSERT_EQ(client->get_state(), connection_base::e_not_connected); + + serv->shutdown(); } // simple exchange with keepalive @@ -563,46 +409,77 @@ class answer_keep_alive : public base_class { unsigned _counter; public: - answer_keep_alive(asio::ip::tcp::socket&& socket, - const std::shared_ptr& ssl_context) - : base_class(std::move(socket), ssl_context), _counter(0) {} - - void on_receive(const beast::error_code& err, const request_ptr& request) { - if (!err) { - ASSERT_EQ(request->body(), "hello server"); - response_ptr resp(std::make_shared(beast::http::status::ok, - request->version())); - resp->keep_alive(true); - resp->body() = fmt::format("hello client {}", _counter++); - resp->content_length(resp->body().length()); - base_class::send_response(resp); - } + using my_type = answer_keep_alive; + + answer_keep_alive(const std::shared_ptr& io_context, + const std::shared_ptr& logger, + const http_config::pointer& conf, + const ssl_ctx_initializer& ssl_initializer) + : base_class(io_context, logger, conf, ssl_initializer), _counter(0) {} + + void on_accept() override { + base_class::on_accept([me = base_class::shared_from_this()]( + const boost::beast::error_code ec, + const std::string&) { + ASSERT_FALSE(ec); + me->receive_request([me](const boost::beast::error_code ec, + const std::string&, + const std::shared_ptr& request) { + ASSERT_FALSE(ec); + ASSERT_EQ(request->body(), "hello server"); + SPDLOG_LOGGER_DEBUG(logger, "request receiver => answer"); + std::static_pointer_cast(me)->answer(request); + }); + }); + } + + void answer(const std::shared_ptr& request) { + response_ptr resp(std::make_shared(beast::http::status::ok, + request->version())); + resp->keep_alive(true); + resp->body() = fmt::format("hello client {}", _counter++); + resp->content_length(resp->body().length()); + SPDLOG_LOGGER_DEBUG(logger, "answer to client"); + base_class::answer( + resp, [me = base_class::shared_from_this()]( + const boost::beast::error_code ec, const std::string&) { + ASSERT_FALSE(ec); + me->receive_request( + [me](const boost::beast::error_code ec, const std::string&, + const std::shared_ptr& request) { + if (ec) { + return; + } + ASSERT_EQ(request->body(), "hello server"); + SPDLOG_LOGGER_DEBUG(logger, "request receiver => answer"); + std::static_pointer_cast(me)->answer(request); + }); + }); } }; TEST_P(http_test, connect_send_answer_with_keepalive) { std::shared_ptr conn; - http_config::pointer conf = create_conf(); + http_config::pointer client_conf = create_conf(); + http_config::pointer server_conf = create_server_conf(); + + connection_creator server_creator; if (GetParam()) { // crypted - creator = [](asio::ip::tcp::socket&& socket, - const std::shared_ptr& ctx) - -> session_base::pointer { - return std::make_shared>( - std::move(socket), ctx); + server_creator = [server_conf]() { + return std::make_shared>( + g_io_context, logger, server_conf, load_server_certificate); }; } else { - creator = [](asio::ip::tcp::socket&& socket, - const std::shared_ptr& ctx) - -> session_base::pointer { - return std::make_shared>( - std::move(socket), ctx); + server_creator = [server_conf]() { + return std::make_shared>( + g_io_context, logger, server_conf, nullptr); }; } auto client = GetParam() - ? https_connection::load(g_io_context, log_v2::tcp(), conf) - : http_connection::load(g_io_context, log_v2::tcp(), conf); + ? https_connection::load(g_io_context, logger, client_conf) + : http_connection::load(g_io_context, logger, client_conf); request_ptr request(std::make_shared()); request->method(beast::http::verb::put); request->target("/"); @@ -612,6 +489,9 @@ TEST_P(http_test, connect_send_answer_with_keepalive) { auto f(p.get_future()); time_point send_begin = system_clock::now(); + auto serv = server::load(g_io_context, logger, server_conf, + std::move(server_creator)); + client->connect([&p, client, request](const beast::error_code& err, const std::string& detail) { if (err) { @@ -627,7 +507,9 @@ TEST_P(http_test, connect_send_answer_with_keepalive) { auto completion = f.get(); time_point send_end = system_clock::now(); - ASSERT_LT((send_end - send_begin), std::chrono::milliseconds(100)); + ASSERT_LT(std::chrono::duration_cast(send_end - + send_begin), + std::chrono::milliseconds(200)); ASSERT_FALSE(std::get<0>(completion)); ASSERT_TRUE(std::get<1>(completion).empty()); ASSERT_EQ(std::get<2>(completion)->body(), "hello client 0"); @@ -650,6 +532,8 @@ TEST_P(http_test, connect_send_answer_with_keepalive) { ASSERT_EQ(std::get<2>(completion2)->keep_alive(), true); std::this_thread::sleep_for(std::chrono::milliseconds(10)); ASSERT_EQ(client->get_state(), connection_base::e_idle); + + serv->shutdown(); } INSTANTIATE_TEST_SUITE_P(http_connection, diff --git a/common/inc/com/centreon/common/hex_dump.hh b/common/inc/com/centreon/common/hex_dump.hh index 1782c8f6ac8..73b570a8605 100644 --- a/common/inc/com/centreon/common/hex_dump.hh +++ b/common/inc/com/centreon/common/hex_dump.hh @@ -1,11 +1,11 @@ /** - * Copyright 2023 Centreon + * Copyright 2024 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -14,15 +14,16 @@ * limitations under the License. * * For more information : contact@centreon.com + * */ #ifndef CCCM_HEX_DUMP_HH #define CCCM_HEX_DUMP_HH - namespace com::centreon::common { -std::string hex_dump(const unsigned char* buffer, size_t buff_len, +std::string hex_dump(const unsigned char* buffer, + size_t buff_len, uint32_t nb_char_per_line); inline std::string hex_dump(const std::string& buffer, diff --git a/common/precomp_inc/precomp.hh b/common/precomp_inc/precomp.hh index 6af5512cfee..07853c4edab 100644 --- a/common/precomp_inc/precomp.hh +++ b/common/precomp_inc/precomp.hh @@ -1,5 +1,5 @@ -/* - * Copyright 2022 Centreon (https://www.centreon.com/) +/** + * Copyright 2024 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,6 +48,9 @@ #include "com/centreon/exceptions/msg_fmt.hh" +using system_clock = std::chrono::system_clock; +using time_point = system_clock::time_point; +using duration = system_clock::duration; namespace asio = boost::asio; diff --git a/common/src/process_stat.cc b/common/src/process_stat.cc index 7ae145d0d94..fa784d68ffa 100644 --- a/common/src/process_stat.cc +++ b/common/src/process_stat.cc @@ -1,21 +1,21 @@ /** -* Copyright 2023 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ - + * Copyright 2024 Centreon (https://www.centreon.com/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include #include diff --git a/common/test/CMakeLists.txt b/common/test/CMakeLists.txt index 18fafc9fbb5..08b61a4a9be 100644 --- a/common/test/CMakeLists.txt +++ b/common/test/CMakeLists.txt @@ -16,26 +16,21 @@ # For more information : contact@centreon.com # -add_executable(ut_common - process_stat_test.cc - hex_dump_test.cc - node_allocator_test.cc - rapidjson_helper_test.cc -) -add_test(NAME tests COMMAND ut_common) +add_executable(ut_common + process_stat_test.cc + hex_dump_test.cc + node_allocator_test.cc + rapidjson_helper_test.cc + test_main.cc + ${TESTS_SOURCES}) -set_target_properties( - ut_common - PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/tests - RUNTIME_OUTPUT_DIRECTORY_DEBUG ${CMAKE_BINARY_DIR}/tests - RUNTIME_OUTPUT_DIRECTORY_RELEASE ${CMAKE_BINARY_DIR}/tests - RUNTIME_OUTPUT_DIRECTORY_RELWITHDEBINFO ${CMAKE_BINARY_DIR}/tests - RUNTIME_OUTPUT_DIRECTORY_MINSIZEREL ${CMAKE_BINARY_DIR}/tests) +add_test(NAME tests COMMAND ut_common) target_link_libraries(ut_common PRIVATE centreon_common + centreon_http crypto ssl GTest::gtest @@ -48,9 +43,17 @@ target_link_libraries(ut_common PRIVATE absl::bits fmt::fmt pthread) -add_dependencies(ut_common centreon_common) +add_dependencies(ut_common centreon_common centreon_http) set_property(TARGET ut_common PROPERTY POSITION_INDEPENDENT_CODE ON) target_precompile_headers(ut_common PRIVATE ${PROJECT_SOURCE_DIR}/precomp_inc/precomp.hh) +set_target_properties( + ut_common + PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/tests + RUNTIME_OUTPUT_DIRECTORY_DEBUG ${CMAKE_BINARY_DIR}/tests + RUNTIME_OUTPUT_DIRECTORY_RELEASE ${CMAKE_BINARY_DIR}/tests + RUNTIME_OUTPUT_DIRECTORY_RELWITHDEBINFO ${CMAKE_BINARY_DIR}/tests + RUNTIME_OUTPUT_DIRECTORY_MINSIZEREL ${CMAKE_BINARY_DIR}/tests) + diff --git a/common/test/process_stat_test.cc b/common/test/process_stat_test.cc index 79cd1bc4a9f..401ccf777c5 100644 --- a/common/test/process_stat_test.cc +++ b/common/test/process_stat_test.cc @@ -1,20 +1,21 @@ /** -* Copyright 2023 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2024 Centreon (https://www.centreon.com/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include diff --git a/common/test/test_main.cc b/common/test/test_main.cc new file mode 100644 index 00000000000..995392ef7a4 --- /dev/null +++ b/common/test/test_main.cc @@ -0,0 +1,62 @@ +/** + * Copyright 2024 Centreon (https://www.centreon.com/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ + +#include +#include "pool.hh" + +std::shared_ptr g_io_context( + std::make_shared()); + +class CentreonEngineEnvironment : public testing::Environment { + public: + void SetUp() override { + setenv("TZ", ":Europe/Paris", 1); + return; + } + + void TearDown() override { return; } +}; + +std::shared_ptr pool_logger = + std::make_shared("pool_logger"); + +/** + * Tester entry point. + * + * @param[in] argc Argument count. + * @param[in] argv Argument values. + * + * @return 0 on success, any other value on failure. + */ +int main(int argc, char* argv[]) { + // GTest initialization. + testing::InitGoogleTest(&argc, argv); + + // Set specific environment. + testing::AddGlobalTestEnvironment(new CentreonEngineEnvironment()); + + com::centreon::common::pool::load(g_io_context, pool_logger); + com::centreon::common::pool::set_pool_size(0); + // Run all tests. + int ret = RUN_ALL_TESTS(); + g_io_context->stop(); + com::centreon::common::pool::unload(); + spdlog::shutdown(); + return ret; +} From fb5bbce2b4f40e836f2f13b2b409a6fc8eb705bc Mon Sep 17 00:00:00 2001 From: tuntoja <58987095+tuntoja@users.noreply.github.com> Date: Mon, 20 May 2024 14:25:14 +0200 Subject: [PATCH 09/60] feat(ci): add a dispatch job to manually trigger cloud packages builds (#1337) * feat(ci): add a dispatch job to manually trigger cloud packages builds * fix linting yaml * Apply sugestions from code review * fix release runs url * Update release-trigger-builds.yml --- .github/workflows/release-trigger-builds.yml | 75 ++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 .github/workflows/release-trigger-builds.yml diff --git a/.github/workflows/release-trigger-builds.yml b/.github/workflows/release-trigger-builds.yml new file mode 100644 index 00000000000..658d42d70d2 --- /dev/null +++ b/.github/workflows/release-trigger-builds.yml @@ -0,0 +1,75 @@ +--- +name: release-trigger-builds + +on: + workflow_dispatch: + inputs: + dispatch_target_release_branch: + description: "Cloud release branch to trigger" + required: true + dispatch_content: + description: "Regular (only centreon named components) or Full (every component, including php and extra libs)" + required: true + type: choice + options: + - REGULAR + - FULL + +jobs: + release-trigger-builds: + runs-on: ubuntu-22.04 + steps: + - name: Install Github CLI + run: | + set -eux + if ! command -v gh &> /dev/null; then + echo "Installing GH CLI." + type -p curl >/dev/null || (sudo apt-get update && sudo apt-get install curl -y) + curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | sudo dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg + sudo chmod go+r /usr/share/keyrings/githubcli-archive-keyring.gpg + echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" | sudo tee /etc/apt/sources.list.d/github-cli.list > /dev/null + sudo apt-get update + sudo apt-get install gh -y + else + echo "GH CLI is already installed." + fi + shell: bash + + - name: Trigger selected branches + run: | + set -eux + + # VARS + # names defined in workflow files per components + #COMPONENTS_OSS=("awie" "dsm" "gorgone" "ha" "open-tickets" "web") + #COMPONENTS_OSS_FULL=("awie" "dsm" "gorgone" "ha" "open-tickets" "web") + #COMPONENTS_MODULES=("anomaly-detection" "autodiscovery" "bam" "cloud-business-extensions" "cloud-extensions" "it-edition-extensions" "lm" "map" "mbi" "ppm") + #COMPONENTS_MODULES_FULL=("anomaly-detection" "autodiscovery" "bam" "cloud-business-extensions" "cloud-extensions" "it-edition-extensions" "lm" "map" "mbi" "ppm" "php-pecl-gnupg" "sourceguardian-loader") + COMPONENTS_COLLECT=("Centreon collect") + COMPONENTS_COLLECT_FULL=("Centreon collect") + RUNS_URL="" + + if [[ ${{ inputs.dispatch_target_release_branch }} =~ ^release-2[0-9]\.[0-9]+-next$ ]];then + echo "Using ${{ inputs.dispatch_target_release_branch }} as release branch to build testing packages." + RUNS_URL="https://github.com/centreon/centreon-collect/actions?query=branch%3A${{ inputs.dispatch_target_release_branch }}" + else + echo "::error::Invalid release branch name, please check the release branch name." + exit 1 + fi + + if [[ "${{ inputs.dispatch_content }}" == "FULL" ]]; then + echo "Requested ${{ inputs.dispatch_content }} content, triggering all component workflows." + for COMPONENT in ${COMPONENTS_COLLECT_FULL[@]}; do + gh workflow run $COMPONENT -r ${{ inputs.dispatch_target_release_branch }} + done + else + echo "Requested ${{ inputs.dispatch_content }} content, triggering centreon named components only." + for COMPONENT in ${COMPONENTS_COLLECT[@]}; do + gh workflow run $COMPONENT -r ${{ inputs.dispatch_target_release_branch }} + done + fi + + echo "Dispatch was successfully triggered. Runs can be found at ${RUNS_URL}" + shell: bash + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} From 879d2aaae1f0be81eee74f5a695fd974aa56e5f1 Mon Sep 17 00:00:00 2001 From: tuntoja <58987095+tuntoja@users.noreply.github.com> Date: Mon, 20 May 2024 16:36:50 +0200 Subject: [PATCH 10/60] fix(ci): missing checkout on release-trigger-workflows (#1345) --- .github/workflows/release-trigger-builds.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/release-trigger-builds.yml b/.github/workflows/release-trigger-builds.yml index 658d42d70d2..3398c2a0844 100644 --- a/.github/workflows/release-trigger-builds.yml +++ b/.github/workflows/release-trigger-builds.yml @@ -19,6 +19,8 @@ jobs: release-trigger-builds: runs-on: ubuntu-22.04 steps: + - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + - name: Install Github CLI run: | set -eux From a04fa549a140e6d1f30d491c3cd5beba45e978f3 Mon Sep 17 00:00:00 2001 From: tuntoja <58987095+tuntoja@users.noreply.github.com> Date: Tue, 21 May 2024 11:03:17 +0200 Subject: [PATCH 11/60] fix(ci): minor fixes to promote and release actions (#1339) * fix(ci): minor fixes to promote and release actions * sync delivery release and promote --- .github/actions/delivery/action.yml | 7 ------- .github/actions/promote-to-stable/action.yml | 16 ++++++++-------- .github/actions/release/action.yml | 13 ++++++++----- 3 files changed, 16 insertions(+), 20 deletions(-) diff --git a/.github/actions/delivery/action.yml b/.github/actions/delivery/action.yml index 10e6e9460b0..f762844e143 100644 --- a/.github/actions/delivery/action.yml +++ b/.github/actions/delivery/action.yml @@ -73,13 +73,6 @@ runs: exit 1 fi - # DEBUG - echo "[DEBUG] - Version: ${{ inputs.version }}" - echo "[DEBUG] - Distrib: ${{ inputs.distrib }}" - echo "[DEBUG] - module_name: ${{ inputs.module_name }}" - echo "[DEBUG] - release_cloud: ${{ inputs.release_cloud }}" - echo "[DEBUG] - release_type: ${{ inputs.release_type }}" - # Create ARCH dirs mkdir noarch x86_64 diff --git a/.github/actions/promote-to-stable/action.yml b/.github/actions/promote-to-stable/action.yml index 0798b3959af..0b7ce45c45b 100644 --- a/.github/actions/promote-to-stable/action.yml +++ b/.github/actions/promote-to-stable/action.yml @@ -116,8 +116,13 @@ runs: echo "[DEBUG] - Minor version: ${{ inputs.minor_version }}" echo "[DEBUG] - Distrib: ${{ inputs.distrib }}" + # Define ROOT_REPO_PATH for debian + # There is no cloud ROOT_REPO_PATH for debian, only onprem + # Should there be a need to deploy debian to cloud repositories, please use the same condition as RPM promotion + ROOT_REPO_PATH="apt-standard-${{ inputs.major_version }}" + echo "[DEBUG] - Get path of testing DEB packages to promote to stable." - SRC_PATHS=$(jf rt search --include-dirs apt-standard-${{ inputs.major_version }}-testing/pool/${{ inputs.module_name }}/*${{ inputs.major_version }}.${{ inputs.minor_version }}*${{ inputs.distrib }}*.deb | jq -r '.[].path') + SRC_PATHS=$(jf rt search --include-dirs "$ROOT_REPO_PATH-testing/pool/${{ inputs.module_name }}/*${{ inputs.distrib }}*.deb | jq -r '.[].path') if [[ ${SRC_PATHS[@]} ]]; then for SRC_PATH in ${SRC_PATHS[@]}; do @@ -129,7 +134,7 @@ runs: fi echo "[DEBUG] - Build target path." - TARGET_PATH="apt-standard-${{ inputs.major_version }}-${{ inputs.stability }}/pool/${{ inputs.module_name }}/" + TARGET_PATH="$ROOT_REPO_PATH-${{ inputs.stability }}/pool/${{ inputs.module_name }}/" echo "[DEBUG] - Target path: $TARGET_PATH" echo "[DEBUG] - Promoting DEB testing artifacts to stable." @@ -138,13 +143,8 @@ runs: jf rt download $ARTIFACT --flat done - for ARTIFACT_DL in $(dir|grep -E "*.deb"); do + for ARTIFACT_DL in $(dir -1|grep -E ".+${{ inputs.distrib }}.+\.deb"); do ARCH=$(echo $ARTIFACT_DL | cut -d '_' -f3 | cut -d '.' -f1) - DISTRIB=$(echo $ARTIFACT_DL | cut -d '_' -f2 | cut -d '-' -f2) - if [[ "${{ inputs.distrib }}" != "$DISTRIB" ]]; then - echo "::error::Distrib [$DISTRIB] from package does not match distrib [${{ inputs.distrib }}] from input, abort promotion." - exit 1 - fi echo "[DEBUG] - Promoting (upload) $ARTIFACT_DL to stable $TARGET_PATH." jf rt upload "$ARTIFACT_DL" "$TARGET_PATH" --deb "${{ inputs.distrib }}/main/$ARCH" --flat done diff --git a/.github/actions/release/action.yml b/.github/actions/release/action.yml index 55411f84994..f527522462f 100644 --- a/.github/actions/release/action.yml +++ b/.github/actions/release/action.yml @@ -38,14 +38,17 @@ runs: declare -a PREVIOUS_STABLE_TAGS=() SCOPE_VERSION="COLLECT" MINOR_VERSION_FILE_PATH=".version" + RELEASE_CLOUD=0 # Get current stable branch name # If MASTER, use root .version # Else use branch name if [[ "${{ inputs.github_ref_name }}" == "master" ]]; then CURRENT_STABLE_BRANCH_MAJOR_VERSION=$(grep -E "MAJOR" .version | cut -d '=' -f2) + RELEASE_CLOUD=1 else CURRENT_STABLE_BRANCH_MAJOR_VERSION=$(echo ${{ inputs.github_ref_name }} | cut -d '.' -f1,2) + RELEASE_CLOUD=0 fi echo "Current stable branch major version: $CURRENT_STABLE_BRANCH_MAJOR_VERSION" @@ -54,7 +57,11 @@ runs: MAJOR_VERSION=$(grep -E "MAJOR" .version | cut -d '=' -f2) MINOR_VERSION=$(grep -E "MINOR" .version | cut -d '=' -f2) # Previous stable tags array - PREVIOUS_STABLE_TAGS+=($(git tag -l --sort=-version:refname "$component-$CURRENT_STABLE_BRANCH_MAJOR_VERSION*" | head -n 1)) + if [[ $RELEASE_CLOUD -eq 1 ]]; then + PREVIOUS_STABLE_TAGS+=($(git tag -l --sort=-version:refname "$component-$CURRENT_STABLE_BRANCH_MAJOR_VERSION.*-*" | head -n 1)) + else + PREVIOUS_STABLE_TAGS+=($(git tag -l --sort=-version:refname "$component-$CURRENT_STABLE_BRANCH_MAJOR_VERSION.*" | grep -E "$component-$CURRENT_STABLE_BRANCH_MAJOR_VERSION.[0-9]+$" | head -n 1)) + fi # New stable tags array TMP_STABLE_TAGS+=("$component-$MAJOR_VERSION.$MINOR_VERSION") done @@ -159,10 +166,6 @@ runs: # Webhook url JIRA_INCOMING_WEBHOOK="${{ inputs.jira_webhook_url }}" - # Call JIRA to provide new jira versions to create - # Webhook url - JIRA_INCOMING_WEBHOOK="${{ inputs.jira_webhook_url }}" - # Rebuild NEW_STABLE_TAGS as an array for i in ${NEW_STABLE_TAGS[@]}; do NEW_RELEASE_TAGS+=("$i") From a56113cfc2e9f676089b023fa2dce627ef452d2c Mon Sep 17 00:00:00 2001 From: May <110405507+mushroomempires@users.noreply.github.com> Date: Mon, 27 May 2024 15:14:53 +0200 Subject: [PATCH 12/60] fix promote action on debian (#1363) --- .github/actions/promote-to-stable/action.yml | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/.github/actions/promote-to-stable/action.yml b/.github/actions/promote-to-stable/action.yml index 0b7ce45c45b..45cb675a025 100644 --- a/.github/actions/promote-to-stable/action.yml +++ b/.github/actions/promote-to-stable/action.yml @@ -122,7 +122,13 @@ runs: ROOT_REPO_PATH="apt-standard-${{ inputs.major_version }}" echo "[DEBUG] - Get path of testing DEB packages to promote to stable." - SRC_PATHS=$(jf rt search --include-dirs "$ROOT_REPO_PATH-testing/pool/${{ inputs.module_name }}/*${{ inputs.distrib }}*.deb | jq -r '.[].path') + + case "${{ inputs.major_version }}" in + "22.10"|"23.04"|"23.10") + SRC_PATHS=$(jf rt search --include-dirs $ROOT_REPO_PATH-testing/pool/${{ inputs.module_name }}/*.deb | jq -r '.[].path') + *) + SRC_PATHS=$(jf rt search --include-dirs $ROOT_REPO_PATH-testing/pool/${{ inputs.module_name }}/*${{ inputs.distrib }}*.deb | jq -r '.[].path') + esac if [[ ${SRC_PATHS[@]} ]]; then for SRC_PATH in ${SRC_PATHS[@]}; do @@ -143,7 +149,14 @@ runs: jf rt download $ARTIFACT --flat done - for ARTIFACT_DL in $(dir -1|grep -E ".+${{ inputs.distrib }}.+\.deb"); do + case "${{ inputs.major_version }}" in + "22.10"|"23.04"|"23.10") + ARTIFACT_SEARCH_PATTERN=".+\.deb" + *) + ARTIFACT_SEARCH_PATTERN=".+${{ inputs.distrib }}.+\.deb" + esac + + for ARTIFACT_DL in $(dir -1|grep -E $ARTIFACT_SEARCH_PATTERN); do ARCH=$(echo $ARTIFACT_DL | cut -d '_' -f3 | cut -d '.' -f1) echo "[DEBUG] - Promoting (upload) $ARTIFACT_DL to stable $TARGET_PATH." jf rt upload "$ARTIFACT_DL" "$TARGET_PATH" --deb "${{ inputs.distrib }}/main/$ARCH" --flat From 24b8d168218c9bdf42d4a5048b04acbb4d2aff35 Mon Sep 17 00:00:00 2001 From: May <110405507+mushroomempires@users.noreply.github.com> Date: Tue, 28 May 2024 10:18:05 +0200 Subject: [PATCH 13/60] fix(ci): add missing semicolons in debian promote action (#1371) --- .github/actions/promote-to-stable/action.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/actions/promote-to-stable/action.yml b/.github/actions/promote-to-stable/action.yml index 45cb675a025..df267f5acfc 100644 --- a/.github/actions/promote-to-stable/action.yml +++ b/.github/actions/promote-to-stable/action.yml @@ -126,8 +126,10 @@ runs: case "${{ inputs.major_version }}" in "22.10"|"23.04"|"23.10") SRC_PATHS=$(jf rt search --include-dirs $ROOT_REPO_PATH-testing/pool/${{ inputs.module_name }}/*.deb | jq -r '.[].path') + ;; *) SRC_PATHS=$(jf rt search --include-dirs $ROOT_REPO_PATH-testing/pool/${{ inputs.module_name }}/*${{ inputs.distrib }}*.deb | jq -r '.[].path') + ;; esac if [[ ${SRC_PATHS[@]} ]]; then @@ -152,8 +154,10 @@ runs: case "${{ inputs.major_version }}" in "22.10"|"23.04"|"23.10") ARTIFACT_SEARCH_PATTERN=".+\.deb" + ;; *) ARTIFACT_SEARCH_PATTERN=".+${{ inputs.distrib }}.+\.deb" + ;; esac for ARTIFACT_DL in $(dir -1|grep -E $ARTIFACT_SEARCH_PATTERN); do From 974ca8ba8b2fd5dfbb280af6572fc3e96f9eaf66 Mon Sep 17 00:00:00 2001 From: David Boucher Date: Tue, 28 May 2024 11:53:29 +0200 Subject: [PATCH 14/60] enh(collect): engine and broker share the same logger library. * enh(common): new log library in common/log_v2. * enh(common/tests): tests directory renamed to 'tests' * doc(broke): update on muxer/processing * fix(broker): stop event is handled by the sql streams now. * fix(broker): engine simplified * doc(broker): engine doc is growing up * fix(broker/muxer) * enh(broker/muxer_filter): filter improved in muxers. There are two filters now, one mandatory and one forbidden. * fix(broker): stats center is embedded by its users now * enh(tests): two new benchs with reversed connections * fix(broker/tests): if hostname fqdn fails, we replace hostname by localhost REFS: MON-21266 --- .gitignore | 5 +- bbdo/bbdo.proto | 3 +- bbdo/events.hh | 21 +- broker/CMakeLists.txt | 41 +- .../broker/bam/availability_builder.hh | 45 +- .../broker/bam/availability_thread.hh | 47 +- broker/bam/inc/com/centreon/broker/bam/ba.hh | 13 +- .../inc/com/centreon/broker/bam/ba_best.hh | 3 +- .../inc/com/centreon/broker/bam/ba_impact.hh | 3 +- .../centreon/broker/bam/ba_ratio_number.hh | 3 +- .../centreon/broker/bam/ba_ratio_percent.hh | 3 +- .../com/centreon/broker/bam/ba_svc_mapping.hh | 43 +- .../inc/com/centreon/broker/bam/ba_worst.hh | 3 +- .../inc/com/centreon/broker/bam/bool_and.hh | 15 +- .../broker/bam/bool_binary_operator.hh | 11 +- .../inc/com/centreon/broker/bam/bool_call.hh | 15 +- .../com/centreon/broker/bam/bool_constant.hh | 8 +- .../inc/com/centreon/broker/bam/bool_equal.hh | 11 +- .../centreon/broker/bam/bool_expression.hh | 12 +- .../com/centreon/broker/bam/bool_less_than.hh | 12 +- .../com/centreon/broker/bam/bool_more_than.hh | 10 +- .../inc/com/centreon/broker/bam/bool_not.hh | 10 +- .../com/centreon/broker/bam/bool_not_equal.hh | 11 +- .../com/centreon/broker/bam/bool_operation.hh | 11 +- .../inc/com/centreon/broker/bam/bool_or.hh | 11 +- .../com/centreon/broker/bam/bool_service.hh | 16 +- .../inc/com/centreon/broker/bam/bool_value.hh | 11 +- .../inc/com/centreon/broker/bam/bool_xor.hh | 15 +- .../inc/com/centreon/broker/bam/computable.hh | 11 +- .../broker/bam/configuration/applier/ba.hh | 15 +- .../configuration/applier/bool_expression.hh | 46 +- .../broker/bam/configuration/applier/kpi.hh | 71 +- .../broker/bam/configuration/applier/state.hh | 21 +- .../centreon/broker/bam/configuration/ba.hh | 36 +- .../bam/configuration/bool_expression.hh | 37 +- .../centreon/broker/bam/configuration/kpi.hh | 36 +- .../bam/configuration/reader_exception.hh | 36 +- .../broker/bam/configuration/reader_v2.hh | 57 +- .../broker/bam/configuration/state.hh | 39 +- .../inc/com/centreon/broker/bam/connector.hh | 13 +- .../broker/bam/event_cache_visitor.hh | 48 +- .../com/centreon/broker/bam/exp_builder.hh | 46 +- .../inc/com/centreon/broker/bam/exp_parser.hh | 45 +- .../com/centreon/broker/bam/exp_tokenizer.hh | 43 +- .../inc/com/centreon/broker/bam/factory.hh | 8 +- .../centreon/broker/bam/hst_svc_mapping.hh | 48 +- .../com/centreon/broker/bam/impact_values.hh | 10 +- .../inc/com/centreon/broker/bam/internal.hh | 1 + broker/bam/inc/com/centreon/broker/bam/kpi.hh | 13 +- .../bam/inc/com/centreon/broker/bam/kpi_ba.hh | 14 +- .../com/centreon/broker/bam/kpi_boolexp.hh | 13 +- .../com/centreon/broker/bam/kpi_service.hh | 11 +- .../centreon/broker/bam/monitoring_stream.hh | 11 +- .../centreon/broker/bam/reporting_stream.hh | 43 +- .../com/centreon/broker/bam/service_book.hh | 4 +- .../com/centreon/broker/bam/timeperiod_map.hh | 42 +- broker/bam/src/availability_builder.cc | 49 +- broker/bam/src/availability_thread.cc | 97 ++- broker/bam/src/ba.cc | 64 +- broker/bam/src/ba_best.cc | 10 +- broker/bam/src/ba_impact.cc | 12 +- broker/bam/src/ba_ratio_number.cc | 12 +- broker/bam/src/ba_ratio_percent.cc | 19 +- broker/bam/src/ba_worst.cc | 12 +- broker/bam/src/bool_and.cc | 14 +- broker/bam/src/bool_binary_operator.cc | 25 +- broker/bam/src/bool_call.cc | 9 +- broker/bam/src/bool_constant.cc | 9 +- broker/bam/src/bool_equal.cc | 1 - broker/bam/src/bool_expression.cc | 12 +- broker/bam/src/bool_less_than.cc | 5 +- broker/bam/src/bool_more_than.cc | 8 +- broker/bam/src/bool_not.cc | 7 +- broker/bam/src/bool_operation.cc | 10 +- broker/bam/src/bool_or.cc | 16 +- broker/bam/src/bool_service.cc | 40 +- broker/bam/src/bool_value.cc | 32 +- broker/bam/src/computable.cc | 4 +- broker/bam/src/configuration/applier/ba.cc | 53 +- .../configuration/applier/bool_expression.cc | 47 +- broker/bam/src/configuration/applier/kpi.cc | 92 ++- broker/bam/src/configuration/applier/state.cc | 27 +- broker/bam/src/configuration/reader_v2.cc | 42 +- broker/bam/src/connector.cc | 31 +- broker/bam/src/exp_builder.cc | 68 +- broker/bam/src/exp_parser.cc | 39 +- broker/bam/src/hst_svc_mapping.cc | 41 +- broker/bam/src/kpi.cc | 10 +- broker/bam/src/kpi_ba.cc | 26 +- broker/bam/src/kpi_boolexp.cc | 21 +- broker/bam/src/kpi_service.cc | 109 +-- broker/bam/src/main.cc | 8 +- broker/bam/src/monitoring_stream.cc | 125 +-- broker/bam/src/reporting_stream.cc | 211 +++-- broker/bam/src/service_book.cc | 9 +- broker/bam/src/service_listener.cc | 50 +- broker/bam/src/timeperiod_map.cc | 6 +- broker/bam/test/ba/kpi_ba.cc | 128 +-- broker/bam/test/ba/kpi_service.cc | 215 ++--- .../bam/test/configuration/applier-boolexp.cc | 7 +- .../test/exp_builder/availability_builder.cc | 41 +- broker/bam/test/exp_builder/exp_builder.cc | 225 +++--- broker/bam/test/monitoring_stream.cc | 32 +- .../inc/com/centreon/broker/bbdo/internal.hh | 19 +- .../inc/com/centreon/broker/bbdo/stream.hh | 26 +- .../com/centreon/broker/cache/global_cache.hh | 39 +- .../broker/cache/global_cache_data.hh | 40 +- .../com/centreon/broker/compression/stream.hh | 37 +- .../broker/config/applier/endpoint.hh | 36 +- .../centreon/broker/config/applier/modules.hh | 37 +- .../centreon/broker/config/applier/state.hh | 2 +- .../inc/com/centreon/broker/config/state.hh | 54 +- .../inc/com/centreon/broker/file/stream.hh | 8 +- .../inc/com/centreon/broker/io/endpoint.hh | 34 +- .../com/centreon/broker/io/limit_endpoint.hh | 57 +- .../inc/com/centreon/broker/io/protobuf.hh | 4 +- broker/core/inc/com/centreon/broker/log_v2.hh | 158 ---- .../com/centreon/broker/misc/diagnostic.hh | 45 +- .../core/inc/com/centreon/broker/misc/misc.hh | 7 +- .../inc/com/centreon/broker/modules/handle.hh | 3 +- .../com/centreon/broker/persistent_cache.hh | 15 +- .../centreon/broker/processing/failover.hh | 39 +- .../com/centreon/broker/processing/feeder.hh | 40 +- .../inc/com/centreon/broker/stats/center.hh | 129 ++- broker/core/multiplexing/CMakeLists.txt | 12 +- .../centreon/broker/multiplexing/engine.hh | 45 +- .../com/centreon/broker/multiplexing/muxer.hh | 91 ++- .../broker/multiplexing/muxer_filter.hh | 85 +- broker/core/multiplexing/src/engine.cc | 228 +++--- broker/core/multiplexing/src/muxer.cc | 312 ++++---- .../multiplexing/test/engine/start_stop.cc | 7 +- broker/core/multiplexing/test/muxer/read.cc | 6 +- .../core/multiplexing/test/publisher/write.cc | 5 +- .../centreon/broker/sql/database_config.hh | 37 +- .../sql/inc/com/centreon/broker/sql/mysql.hh | 61 +- .../inc/com/centreon/broker/sql/mysql_bind.hh | 9 +- .../centreon/broker/sql/mysql_bind_base.hh | 6 +- .../centreon/broker/sql/mysql_bind_result.hh | 41 +- .../centreon/broker/sql/mysql_bulk_bind.hh | 47 +- .../centreon/broker/sql/mysql_bulk_stmt.hh | 36 +- .../com/centreon/broker/sql/mysql_column.hh | 34 +- .../centreon/broker/sql/mysql_connection.hh | 46 +- .../com/centreon/broker/sql/mysql_error.hh | 37 +- .../com/centreon/broker/sql/mysql_manager.hh | 40 +- .../centreon/broker/sql/mysql_multi_insert.hh | 6 +- .../com/centreon/broker/sql/mysql_result.hh | 36 +- .../inc/com/centreon/broker/sql/mysql_stmt.hh | 36 +- .../centreon/broker/sql/mysql_stmt_base.hh | 47 +- .../inc/com/centreon/broker/sql/mysql_task.hh | 36 +- .../centreon/broker/sql/query_preparator.hh | 38 +- .../sql/inc/com/centreon/broker/sql/stats.hh | 36 +- broker/core/sql/src/database_config.cc | 81 +- broker/core/sql/src/mysql.cc | 61 +- broker/core/sql/src/mysql_bind.cc | 5 +- broker/core/sql/src/mysql_bind_base.cc | 36 +- broker/core/sql/src/mysql_bind_result.cc | 71 +- broker/core/sql/src/mysql_bulk_bind.cc | 8 +- broker/core/sql/src/mysql_bulk_stmt.cc | 70 +- broker/core/sql/src/mysql_column.cc | 67 +- broker/core/sql/src/mysql_connection.cc | 159 ++-- broker/core/sql/src/mysql_manager.cc | 65 +- broker/core/sql/src/mysql_stmt.cc | 44 +- broker/core/sql/src/mysql_stmt_base.cc | 142 ++-- broker/core/sql/src/query_preparator.cc | 54 +- broker/core/src/bbdo/acceptor.cc | 6 +- broker/core/src/bbdo/connector.cc | 7 +- broker/core/src/bbdo/factory.cc | 64 +- broker/core/src/bbdo/internal.cc | 35 +- broker/core/src/bbdo/stream.cc | 298 +++---- broker/core/src/broker_impl.cc | 82 +- broker/core/src/cache/global_cache.cc | 60 +- broker/core/src/cache/global_cache_data.cc | 25 +- broker/core/src/compression/factory.cc | 75 +- broker/core/src/compression/opener.cc | 34 +- broker/core/src/compression/stream.cc | 74 +- broker/core/src/compression/zlib.cc | 39 +- broker/core/src/config/applier/endpoint.cc | 177 ++-- broker/core/src/config/applier/init.cc | 22 +- broker/core/src/config/applier/modules.cc | 74 +- broker/core/src/config/applier/state.cc | 70 +- broker/core/src/config/endpoint.cc | 33 +- broker/core/src/config/parser.cc | 98 +-- broker/core/src/config/state.cc | 56 +- broker/core/src/file/directory_watcher.cc | 13 +- broker/core/src/file/disk_accessor.cc | 53 +- broker/core/src/file/fifo.cc | 39 +- broker/core/src/file/opener.cc | 40 +- broker/core/src/file/splitter.cc | 38 +- broker/core/src/file/stream.cc | 65 +- broker/core/src/io/endpoint.cc | 51 +- broker/core/src/io/factory.cc | 35 +- broker/core/src/io/protocols.cc | 51 +- broker/core/src/io/raw.cc | 26 +- broker/core/src/io/stream.cc | 58 +- broker/core/src/log_v2.cc | 373 --------- broker/core/src/main.cc | 94 ++- broker/core/src/misc/diagnostic.cc | 95 +-- broker/core/src/misc/filesystem.cc | 41 +- broker/core/src/misc/parse_perfdata.cc | 58 +- broker/core/src/modules/handle.cc | 66 +- broker/core/src/persistent_cache.cc | 29 +- broker/core/src/persistent_file.cc | 43 +- broker/core/src/processing/acceptor.cc | 39 +- broker/core/src/processing/failover.cc | 126 ++- broker/core/src/processing/feeder.cc | 181 ++--- broker/core/src/stats/center.cc | 179 +---- broker/core/src/time/timerange.cc | 54 +- broker/core/test/bbdo/output.cc | 30 +- broker/core/test/cache/global_cache_test.cc | 15 +- broker/core/test/config/parser.cc | 20 +- broker/core/test/main.cc | 9 +- broker/core/test/misc/perfdata.cc | 33 +- broker/core/test/modules/module.cc | 10 +- broker/core/test/processing/acceptor.cc | 5 +- broker/core/test/processing/feeder.cc | 2 +- .../test/processing/temporary_endpoint.hh | 9 +- broker/core/test/rpc/brokerrpc.cc | 6 +- broker/doc/broker-doc.md | 88 +- .../com/centreon/broker/graphite/connector.hh | 41 +- .../com/centreon/broker/graphite/factory.hh | 39 +- .../com/centreon/broker/graphite/internal.hh | 40 +- .../centreon/broker/graphite/macro_cache.hh | 43 +- .../inc/com/centreon/broker/graphite/query.hh | 40 +- .../com/centreon/broker/graphite/stream.hh | 45 +- broker/graphite/src/connector.cc | 39 +- broker/graphite/src/macro_cache.cc | 37 +- broker/graphite/src/main.cc | 40 +- broker/graphite/src/query.cc | 56 +- broker/graphite/src/stream.cc | 50 +- broker/graphite/test/query.cc | 12 +- broker/grpc/CMakeLists.txt | 2 +- broker/grpc/generate_proto.py | 16 +- .../inc/com/centreon/broker/grpc/acceptor.hh | 34 +- .../inc/com/centreon/broker/grpc/connector.hh | 34 +- .../inc/com/centreon/broker/grpc/factory.hh | 36 +- .../com/centreon/broker/grpc/grpc_bridge.hh | 42 +- .../com/centreon/broker/grpc/grpc_config.hh | 36 +- .../inc/com/centreon/broker/grpc/stream.hh | 37 +- broker/grpc/precomp_inc/precomp.hh | 1 - broker/grpc/src/acceptor.cc | 36 +- broker/grpc/src/connector.cc | 33 +- broker/grpc/src/factory.cc | 137 ++-- broker/grpc/src/main.cc | 6 +- broker/grpc/src/stream.cc | 50 +- broker/grpc/test/acceptor.cc | 5 +- broker/grpc/test/grpc_test_include.hh | 2 - broker/grpc/test/stream_test.cc | 74 +- .../com/centreon/broker/http_tsdb/column.hh | 37 +- .../com/centreon/broker/http_tsdb/factory.hh | 36 +- .../com/centreon/broker/http_tsdb/internal.hh | 36 +- .../broker/http_tsdb/line_protocol_query.hh | 52 +- broker/http_tsdb/src/line_protocol_query.cc | 82 +- broker/http_tsdb/src/stream.cc | 2 - broker/http_tsdb/test/factory_test.cc | 3 +- broker/http_tsdb/test/stream_test.cc | 31 +- .../com/centreon/broker/influxdb/column.hh | 41 +- .../com/centreon/broker/influxdb/connector.hh | 40 +- .../com/centreon/broker/influxdb/factory.hh | 40 +- .../com/centreon/broker/influxdb/influxdb.hh | 36 +- .../com/centreon/broker/influxdb/internal.hh | 41 +- .../broker/influxdb/line_protocol_query.hh | 40 +- .../centreon/broker/influxdb/macro_cache.hh | 43 +- .../com/centreon/broker/influxdb/stream.hh | 55 +- broker/influxdb/src/connector.cc | 45 +- broker/influxdb/src/influxdb.cc | 57 +- broker/influxdb/src/line_protocol_query.cc | 54 +- broker/influxdb/src/macro_cache.cc | 35 +- broker/influxdb/src/main.cc | 42 +- broker/influxdb/src/stream.cc | 64 +- broker/influxdb/test/influxdb.cc | 21 +- broker/influxdb/test/line_protocol_query.cc | 16 +- .../com/centreon/broker/lua/broker_cache.hh | 40 +- .../com/centreon/broker/lua/broker_event.hh | 40 +- .../inc/com/centreon/broker/lua/broker_log.hh | 41 +- .../com/centreon/broker/lua/broker_socket.hh | 41 +- .../com/centreon/broker/lua/broker_utils.hh | 41 +- .../inc/com/centreon/broker/lua/connector.hh | 40 +- .../inc/com/centreon/broker/lua/factory.hh | 40 +- .../inc/com/centreon/broker/lua/internal.hh | 41 +- .../inc/com/centreon/broker/lua/luabinding.hh | 11 +- .../com/centreon/broker/lua/macro_cache.hh | 11 +- .../lua/inc/com/centreon/broker/lua/stream.hh | 49 +- broker/lua/src/broker_cache.cc | 32 +- broker/lua/src/broker_log.cc | 53 +- broker/lua/src/broker_utils.cc | 9 +- broker/lua/src/connector.cc | 40 +- broker/lua/src/luabinding.cc | 64 +- broker/lua/src/macro_cache.cc | 95 +-- broker/lua/src/main.cc | 39 +- broker/lua/src/stream.cc | 47 +- broker/lua/test/lua.cc | 136 ++-- broker/neb/CMakeLists.txt | 43 +- .../inc/com/centreon/broker/neb/callbacks.hh | 9 +- .../inc/com/centreon/broker/neb/internal.hh | 34 +- broker/neb/precomp_inc/precomp.hpp | 34 +- broker/neb/src/broker.cc | 8 +- broker/neb/src/callbacks.cc | 366 +++++---- broker/neb/src/initial.cc | 70 +- broker/neb/src/neb.cc | 36 +- broker/neb/src/set_log_data.cc | 74 +- .../inc/com/centreon/broker/rrd/backend.hh | 44 +- .../rrd/inc/com/centreon/broker/rrd/cached.hh | 63 +- .../inc/com/centreon/broker/rrd/connector.hh | 59 +- .../inc/com/centreon/broker/rrd/creator.hh | 64 +- .../inc/com/centreon/broker/rrd/factory.hh | 36 +- .../inc/com/centreon/broker/rrd/internal.hh | 36 +- broker/rrd/inc/com/centreon/broker/rrd/lib.hh | 36 +- .../rrd/inc/com/centreon/broker/rrd/output.hh | 39 +- broker/rrd/src/connector.cc | 64 +- broker/rrd/src/creator.cc | 48 +- broker/rrd/src/factory.cc | 59 +- broker/rrd/src/lib.cc | 62 +- broker/rrd/src/main.cc | 43 +- broker/rrd/src/output.cc | 117 ++- .../inc/com/centreon/broker/simu/connector.hh | 36 +- .../inc/com/centreon/broker/simu/factory.hh | 36 +- .../com/centreon/broker/simu/luabinding.hh | 46 +- .../inc/com/centreon/broker/simu/stream.hh | 50 +- broker/simu/src/connector.cc | 45 +- broker/simu/src/luabinding.cc | 46 +- broker/simu/src/main.cc | 40 +- broker/simu/src/stream.cc | 39 +- broker/simu/test/simu.cc | 32 +- .../inc/com/centreon/broker/sql/cleanup.hh | 37 +- .../inc/com/centreon/broker/sql/connector.hh | 36 +- .../inc/com/centreon/broker/sql/factory.hh | 36 +- .../sql/inc/com/centreon/broker/sql/stream.hh | 38 +- broker/sql/src/connector.cc | 46 +- broker/sql/src/factory.cc | 69 +- broker/sql/src/main.cc | 39 +- broker/sql/src/stream.cc | 23 +- .../inc/com/centreon/broker/stats/builder.hh | 4 +- .../inc/com/centreon/broker/stats/parser.hh | 5 +- broker/stats/src/main.cc | 14 +- broker/stats/src/worker.cc | 13 +- broker/stats/src/worker_pool.cc | 10 +- broker/stats/test/stats.cc | 7 +- .../broker/stats_exporter/exporter.hh | 5 +- .../broker/stats_exporter/exporter_grpc.hh | 4 +- .../broker/stats_exporter/exporter_http.hh | 4 +- broker/stats_exporter/src/exporter.cc | 75 +- broker/stats_exporter/src/main.cc | 13 +- .../broker/storage/conflict_manager.hh | 42 +- .../com/centreon/broker/storage/connector.hh | 36 +- .../com/centreon/broker/storage/factory.hh | 36 +- .../com/centreon/broker/storage/internal.hh | 41 +- .../com/centreon/broker/storage/rebuilder.hh | 35 +- .../broker/storage/stored_timestamp.hh | 36 +- .../inc/com/centreon/broker/storage/stream.hh | 43 +- broker/storage/src/conflict_manager.cc | 172 ++-- broker/storage/src/conflict_manager_sql.cc | 197 +++-- .../storage/src/conflict_manager_storage.cc | 47 +- broker/storage/src/connector.cc | 39 +- broker/storage/src/factory.cc | 68 +- broker/storage/src/main.cc | 44 +- broker/storage/src/rebuilder.cc | 31 +- broker/storage/src/stream.cc | 64 +- broker/storage/test/conflict_manager.cc | 32 +- broker/storage/test/status-entry.cc | 43 +- .../inc/com/centreon/broker/tcp/acceptor.hh | 34 +- .../inc/com/centreon/broker/tcp/connector.hh | 38 +- .../inc/com/centreon/broker/tcp/factory.hh | 36 +- .../tcp/inc/com/centreon/broker/tcp/stream.hh | 37 +- .../inc/com/centreon/broker/tcp/tcp_async.hh | 39 +- .../com/centreon/broker/tcp/tcp_connection.hh | 46 +- broker/tcp/src/acceptor.cc | 20 +- broker/tcp/src/connector.cc | 28 +- broker/tcp/src/factory.cc | 45 +- broker/tcp/src/main.cc | 7 +- broker/tcp/src/stream.cc | 52 +- broker/tcp/src/tcp_async.cc | 101 ++- broker/tcp/src/tcp_connection.cc | 47 +- broker/tcp/test/acceptor.cc | 11 +- broker/test/CMakeLists.txt | 57 +- .../inc/com/centreon/broker/tls/acceptor.hh | 40 +- .../inc/com/centreon/broker/tls/connector.hh | 36 +- .../inc/com/centreon/broker/tls/factory.hh | 36 +- .../inc/com/centreon/broker/tls/internal.hh | 36 +- .../tls/inc/com/centreon/broker/tls/params.hh | 34 +- .../tls/inc/com/centreon/broker/tls/stream.hh | 35 +- broker/tls/src/acceptor.cc | 17 +- broker/tls/src/connector.cc | 15 +- broker/tls/src/factory.cc | 45 +- broker/tls/src/internal.cc | 37 +- broker/tls/src/main.cc | 39 +- broker/tls/src/params.cc | 87 +- broker/tls/src/stream.cc | 40 +- broker/tls/test/acceptor.cc | 6 +- .../centreon/broker/unified_sql/bulk_bind.hh | 40 +- .../broker/unified_sql/bulk_queries.hh | 41 +- .../centreon/broker/unified_sql/internal.hh | 41 +- .../com/centreon/broker/unified_sql/stream.hh | 29 +- broker/unified_sql/src/bulk_bind.cc | 57 +- broker/unified_sql/src/bulk_queries.cc | 47 +- broker/unified_sql/src/connector.cc | 37 +- broker/unified_sql/src/factory.cc | 56 +- broker/unified_sql/src/main.cc | 47 +- broker/unified_sql/src/rebuilder.cc | 41 +- broker/unified_sql/src/stream.cc | 243 ++++-- broker/unified_sql/src/stream_sql.cc | 756 +++++++++--------- broker/unified_sql/src/stream_storage.cc | 121 ++- broker/unified_sql/test/rebuild_message.cc | 17 +- broker/unified_sql/test/status-entry.cc | 43 +- .../broker/victoria_metrics/connector.hh | 36 +- .../broker/victoria_metrics/factory.hh | 36 +- .../broker/victoria_metrics/request.hh | 38 +- .../broker/victoria_metrics/stream.hh | 5 +- .../victoria_metrics/precomp_inc/precomp.hh | 35 +- broker/victoria_metrics/src/connector.cc | 19 +- broker/victoria_metrics/src/factory.cc | 4 +- broker/victoria_metrics/src/main.cc | 8 +- broker/victoria_metrics/src/request.cc | 38 +- broker/victoria_metrics/src/stream.cc | 15 +- broker/victoria_metrics/test/request_test.cc | 31 +- broker/victoria_metrics/test/stream_test.cc | 5 +- cmake-vcpkg.sh | 2 +- common/CMakeLists.txt | 13 +- common/http/test/http_client_test.cc | 13 +- common/http/test/http_connection_test.cc | 4 + common/log_v2/CMakeLists.txt | 31 + common/log_v2/config.hh | 136 ++++ common/log_v2/log_v2.cc | 428 ++++++++++ common/log_v2/log_v2.hh | 128 +++ common/{test => tests}/CMakeLists.txt | 125 +-- common/{test => tests}/hex_dump_test.cc | 32 +- common/tests/log_v2/log_v2.cc | 154 ++++ common/{test => tests}/node_allocator_test.cc | 32 +- common/{test => tests}/process_stat_test.cc | 2 +- .../{test => tests}/rapidjson_helper_test.cc | 0 engine/CMakeLists.txt | 31 +- engine/enginerpc/engine.proto | 19 +- engine/enginerpc/engine_impl.cc | 161 ++-- .../engine/configuration/applier/state.hh | 39 +- .../centreon/engine/configuration/state.hh | 3 +- .../engine/configuration/whitelist.hh | 6 +- engine/inc/com/centreon/engine/diagnostic.hh | 38 +- engine/inc/com/centreon/engine/globals.hh | 22 +- engine/inc/com/centreon/engine/log_v2.hh | 125 --- engine/inc/com/centreon/engine/log_v2_base.hh | 63 -- engine/modules/external_commands/src/main.cc | 54 +- engine/modules/external_commands/src/utils.cc | 65 +- engine/src/anomalydetection.cc | 103 ++- engine/src/broker/handle.cc | 40 +- engine/src/broker/loader.cc | 55 +- engine/src/checkable.cc | 6 +- engine/src/checks/checker.cc | 63 +- engine/src/command_manager.cc | 7 +- engine/src/commands/command.cc | 7 +- engine/src/commands/commands.cc | 90 +-- engine/src/commands/connector.cc | 112 ++- engine/src/commands/processing.cc | 89 +-- engine/src/commands/raw.cc | 67 +- engine/src/compatibility/logging.cc | 47 +- engine/src/config.cc | 47 +- engine/src/configuration/CMakeLists.txt | 23 +- engine/src/configuration/anomalydetection.cc | 154 ++-- .../configuration/applier/anomalydetection.cc | 43 +- engine/src/configuration/applier/command.cc | 41 +- engine/src/configuration/applier/connector.cc | 41 +- engine/src/configuration/applier/contact.cc | 11 +- .../src/configuration/applier/contactgroup.cc | 54 +- engine/src/configuration/applier/host.cc | 43 +- .../configuration/applier/hostdependency.cc | 36 +- .../configuration/applier/hostescalation.cc | 50 +- engine/src/configuration/applier/hostgroup.cc | 47 +- engine/src/configuration/applier/scheduler.cc | 105 ++- engine/src/configuration/applier/service.cc | 51 +- .../applier/servicedependency.cc | 41 +- .../applier/serviceescalation.cc | 70 +- .../src/configuration/applier/servicegroup.cc | 52 +- engine/src/configuration/applier/severity.cc | 19 +- engine/src/configuration/applier/state.cc | 191 +++-- engine/src/configuration/applier/tag.cc | 21 +- .../src/configuration/applier/timeperiod.cc | 45 +- engine/src/configuration/extended_conf.cc | 11 +- engine/src/configuration/host.cc | 49 +- engine/src/configuration/hostdependency.cc | 39 +- engine/src/configuration/hostgroup.cc | 52 +- engine/src/configuration/parser.cc | 42 +- engine/src/configuration/service.cc | 154 ++-- engine/src/configuration/servicedependency.cc | 41 +- engine/src/configuration/serviceescalation.cc | 60 +- engine/src/configuration/state.cc | 110 ++- engine/src/configuration/whitelist.cc | 40 +- engine/src/contact.cc | 66 +- engine/src/contactgroup.cc | 45 +- engine/src/dependency.cc | 40 +- engine/src/diagnostic.cc | 35 +- engine/src/downtimes/downtime_manager.cc | 48 +- engine/src/downtimes/host_downtime.cc | 22 +- engine/src/downtimes/service_downtime.cc | 34 +- engine/src/escalation.cc | 40 +- engine/src/events/loop.cc | 85 +- engine/src/events/sched_info.cc | 41 +- engine/src/events/timed_event.cc | 94 ++- engine/src/flapping.cc | 41 +- engine/src/globals.cc | 72 +- engine/src/host.cc | 330 ++++---- engine/src/hostdependency.cc | 43 +- engine/src/hostescalation.cc | 41 +- engine/src/hostgroup.cc | 45 +- engine/src/log_v2.cc | 250 ------ engine/src/macros.cc | 53 +- engine/src/macros/grab_host.cc | 42 +- engine/src/macros/grab_service.cc | 42 +- engine/src/macros/grab_value.cc | 54 +- engine/src/macros/process.cc | 60 +- engine/src/main.cc | 42 +- engine/src/nebmods.cc | 99 ++- engine/src/notification.cc | 6 +- engine/src/notifier.cc | 180 ++--- engine/src/retention/applier/downtime.cc | 37 +- engine/src/retention/applier/service.cc | 34 +- engine/src/retention/dump.cc | 45 +- engine/src/retention/host.cc | 42 +- engine/src/retention/service.cc | 46 +- engine/src/sehandlers.cc | 126 ++- engine/src/service.cc | 270 +++---- engine/src/servicedependency.cc | 43 +- engine/src/serviceescalation.cc | 41 +- engine/src/servicegroup.cc | 43 +- engine/src/timeperiod.cc | 65 +- engine/src/timerange.cc | 43 +- engine/src/utils.cc | 51 +- engine/src/xpddefault.cc | 116 ++- engine/src/xsddefault.cc | 58 +- engine/tests/CMakeLists.txt | 50 +- engine/tests/checks/anomalydetection.cc | 6 +- engine/tests/commands/simple-command.cc | 10 +- engine/tests/configuration/whitelist-test.cc | 11 +- engine/tests/helper.cc | 20 +- engine/tests/main.cc | 10 +- .../notifications/host_normal_notification.cc | 4 +- .../service_downtime_notification_test.cc | 1 - init.sh | 14 +- tests/bench.py | 20 +- tests/broker-engine/bench.robot | 173 +++- tests/broker-engine/delete-poller.robot | 17 +- tests/broker-engine/external-commands2.robot | 16 +- tests/broker-engine/log-v2_engine.robot | 38 +- tests/broker-engine/muxer_filter.robot | 95 ++- .../broker-engine/retention-duplicates.robot | 54 +- tests/broker-engine/reverse-connection.robot | 5 +- tests/broker-engine/services.robot | 28 +- tests/broker-engine/start-stop.robot | 154 ++-- .../broker/bbdo-server-client-reversed.robot | 2 + tests/broker/command-line.robot | 2 +- tests/engine/extended_conf.robot | 4 +- tests/migration/migration.robot | 4 +- tests/resources/Broker.py | 2 +- tests/resources/Common.py | 32 +- tests/resources/Engine.py | 2 +- tests/resources/resources.resource | 3 +- tests/resources/specific-duplication.py | 76 +- 554 files changed, 14047 insertions(+), 13093 deletions(-) delete mode 100644 broker/core/inc/com/centreon/broker/log_v2.hh delete mode 100644 broker/core/src/log_v2.cc create mode 100644 common/log_v2/CMakeLists.txt create mode 100644 common/log_v2/config.hh create mode 100644 common/log_v2/log_v2.cc create mode 100644 common/log_v2/log_v2.hh rename common/{test => tests}/CMakeLists.txt (63%) rename common/{test => tests}/hex_dump_test.cc (57%) create mode 100644 common/tests/log_v2/log_v2.cc rename common/{test => tests}/node_allocator_test.cc (77%) rename common/{test => tests}/process_stat_test.cc (95%) rename common/{test => tests}/rapidjson_helper_test.cc (100%) delete mode 100644 engine/inc/com/centreon/engine/log_v2.hh delete mode 100644 engine/inc/com/centreon/engine/log_v2_base.hh delete mode 100644 engine/src/log_v2.cc mode change 100644 => 100755 tests/bench.py diff --git a/.gitignore b/.gitignore index 08c9069036d..8243275dd6e 100644 --- a/.gitignore +++ b/.gitignore @@ -137,5 +137,6 @@ test/python/*.crt test/python/*.key tests/logs/* tests/bench.unqlite -tests/resources/process_stat_pb2.py -tests/resources/process_stat_pb2_grpc.py +tests/resources/*_pb2.py +tests/resources/*_pb2_grpc.py +tests/resources/grpc_stream.proto diff --git a/bbdo/bbdo.proto b/bbdo/bbdo.proto index cc4aa5f6553..a9823ccaf81 100644 --- a/bbdo/bbdo.proto +++ b/bbdo/bbdo.proto @@ -42,4 +42,5 @@ message Ack { /*io::bbdo, bbdo::de_pb_stop*/ message Stop { -} \ No newline at end of file + uint64 poller_id = 1; +} diff --git a/bbdo/events.hh b/bbdo/events.hh index d43972d4cab..f9431348003 100644 --- a/bbdo/events.hh +++ b/bbdo/events.hh @@ -22,9 +22,7 @@ #include #include -namespace com { -namespace centreon { -namespace broker { +namespace com::centreon::broker { namespace io { enum data_category { none = 0, @@ -35,7 +33,8 @@ enum data_category { bam = 6, extcmd = 7, generator = 8, - max_data_category = 9, + local = 9, + max_data_category = 10, internal = 65535 }; constexpr uint16_t category_id(const char* name) { @@ -55,6 +54,8 @@ constexpr uint16_t category_id(const char* name) { return dumper; if (std::string_view("generator", 9) == name) return generator; + if (std::string_view("local", 5) == name) + return local; return none; } constexpr const char* category_name(data_category cat) { @@ -75,6 +76,8 @@ constexpr const char* category_name(data_category cat) { return "generator"; case internal: return "internal"; + case local: + return "local"; default: return "unknown category"; } @@ -208,6 +211,12 @@ namespace extcmd { enum data_element { de_pb_bench = 1, de_ba_info = 2 }; } +namespace local { +enum data_element { + de_pb_stop = 1, +}; +} + constexpr uint32_t make_type(io::data_category cat, uint32_t elem) { return (cat << 16) | elem; } @@ -217,8 +226,6 @@ constexpr uint16_t category_of_type(uint32_t type) { constexpr uint16_t element_of_type(uint32_t type) { return static_cast(type); } -} // namespace broker -} // namespace centreon -} // namespace com +} // namespace com::centreon::broker #endif /* !CC_BROKER_EVENTS_HH */ diff --git a/broker/CMakeLists.txt b/broker/CMakeLists.txt index af3a9ac809c..3464996b05e 100644 --- a/broker/CMakeLists.txt +++ b/broker/CMakeLists.txt @@ -94,9 +94,9 @@ add_custom_command( OUTPUT ${SRC_DIR}/broker.grpc.pb.cc ${SRC_DIR}/broker.grpc.pb.h COMMAND ${Protobuf_PROTOC_EXECUTABLE} ARGS - --plugin=protoc-gen-grpc=${GRPC_CPP_PLUGIN} - --proto_path=${SRC_DIR} --proto_path=${CMAKE_SOURCE_DIR}/common/src - --grpc_out="${SRC_DIR}" ${SRC_DIR}/broker.proto + --plugin=protoc-gen-grpc=${GRPC_CPP_PLUGIN} --proto_path=${SRC_DIR} + --proto_path=${CMAKE_SOURCE_DIR}/common/src --grpc_out="${SRC_DIR}" + ${SRC_DIR}/broker.proto DEPENDS ${SRC_DIR}/broker.proto COMMENT "Generating interface files of the proto file (protobuf)" OUTPUT ${SRC_DIR}/broker.pb.cc ${SRC_DIR}/broker.pb.h @@ -104,7 +104,7 @@ add_custom_command( ${Protobuf_PROTOC_EXECUTABLE} ARGS --cpp_out="${SRC_DIR}" --proto_path=${SRC_DIR} --proto_path=${CMAKE_SOURCE_DIR}/common/src ${SRC_DIR}/broker.proto - WORKING_DIRECTORY ${CMAKE_BINARY_DIR}) + WORKING_DIRECTORY ${CMAKE_BINARY_DIR}) add_custom_target("target_broker_message" DEPENDS "${SRC_DIR}/broker.pb.cc" "${SRC_DIR}/broker.pb.h") @@ -436,15 +436,10 @@ set(LIBROKER_SOURCES ${INC_DIR}/version.hh) # Static libraries. -add_library(rokerlog STATIC ${SRC_DIR}/log_v2.cc) -set_target_properties(rokerlog PROPERTIES COMPILE_FLAGS "-fPIC") -target_precompile_headers(rokerlog REUSE_FROM multiplexing) -target_link_libraries(rokerlog spdlog::spdlog) - add_library(rokerbase STATIC ${LIBROKER_SOURCES}) set_target_properties(rokerbase PROPERTIES COMPILE_FLAGS "-fPIC") target_precompile_headers(rokerbase REUSE_FROM multiplexing) -add_dependencies(rokerbase berpc target_bbdo) +add_dependencies(rokerbase berpc target_bbdo target_extcmd) target_link_libraries( rokerbase sql @@ -454,14 +449,23 @@ target_link_libraries( berpc z spdlog::spdlog - crypto ssl + crypto + ssl pthread dl) add_library(roker STATIC ${SRC_DIR}/config/applier/init.cc) -target_link_libraries(roker rokerbase crypto ssl - gRPC::gpr gRPC::grpc gRPC::grpc++ gRPC::grpc++_alts - pthread dl) +target_link_libraries( + roker + rokerbase + crypto + ssl + gRPC::gpr + gRPC::grpc + gRPC::grpc++ + gRPC::grpc++_alts + pthread + dl) # Standalone binary. add_executable(cbd ${SRC_DIR}/main.cc) @@ -471,8 +475,8 @@ add_dependencies(cbd multiplexing centreon_common) target_link_libraries( cbd "-rdynamic" - rokerlog "-Wl,--whole-archive" + log_v2 sql rokerbase roker @@ -487,8 +491,11 @@ target_link_libraries( protobuf "-Wl,--no-whole-archive" stdc++fs - spdlog::spdlog - gRPC::gpr gRPC::grpc gRPC::grpc++ gRPC::grpc++_alts) + # spdlog::spdlog + gRPC::gpr + gRPC::grpc + gRPC::grpc++ + gRPC::grpc++_alts) # Centreon Broker Watchdog option(WITH_CBWD "Build centreon broker watchdog." ON) diff --git a/broker/bam/inc/com/centreon/broker/bam/availability_builder.hh b/broker/bam/inc/com/centreon/broker/bam/availability_builder.hh index 6105d32547d..221918611aa 100644 --- a/broker/bam/inc/com/centreon/broker/bam/availability_builder.hh +++ b/broker/bam/inc/com/centreon/broker/bam/availability_builder.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2014 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2014, 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_BAM_AVAILABILITY_BUILDER_HH #define CCB_BAM_AVAILABILITY_BUILDER_HH @@ -22,9 +22,7 @@ #include "com/centreon/broker/time/timeperiod.hh" #include "com/centreon/broker/timestamp.hh" -namespace com::centreon::broker { - -namespace bam { +namespace com::centreon::broker::bam { /** * @class availability_builder availability_builder.hh * "com/centreon/broker/bam/availability_builder.hh" @@ -56,7 +54,8 @@ class availability_builder { time_t start, time_t end, bool was_in_downtime, - time::timeperiod::ptr const& tp); + time::timeperiod::ptr const& tp, + const std::shared_ptr& logger); int get_available() const; int get_unavailable() const; @@ -86,8 +85,6 @@ class availability_builder { bool _timeperiods_is_default; }; -} // namespace bam - -} +} // namespace com::centreon::broker::bam #endif // !CCB_BAM_AVAILABILITY_BUILDER_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/availability_thread.hh b/broker/bam/inc/com/centreon/broker/bam/availability_thread.hh index 71a31f7371a..c44b9d4a07a 100644 --- a/broker/bam/inc/com/centreon/broker/bam/availability_thread.hh +++ b/broker/bam/inc/com/centreon/broker/bam/availability_thread.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2014 - 2021 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2014 - 2021-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_BAM_AVAILABILITY_THREAD_HH #define CCB_BAM_AVAILABILITY_THREAD_HH @@ -41,11 +41,11 @@ namespace bam { class availability_thread final { public: availability_thread(database_config const& db_cfg, - timeperiod_map& shared_map); + timeperiod_map& shared_map, + const std::shared_ptr& logger); ~availability_thread(); - availability_thread(availability_thread const& other) = delete; - availability_thread& operator=(availability_thread const& other) const = - delete; + availability_thread(availability_thread const&) = delete; + availability_thread& operator=(availability_thread const&) const = delete; virtual void run(); void terminate(); @@ -87,9 +87,12 @@ class availability_thread final { bool _should_rebuild_all; std::string _bas_to_rebuild; std::condition_variable _wait; + + /* Logger */ + std::shared_ptr _logger; }; } // namespace bam -} +} // namespace com::centreon::broker #endif // !CCB_BAM_AVAILABILITY_THREAD_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/ba.hh b/broker/bam/inc/com/centreon/broker/bam/ba.hh index 1f1a74d0e57..fc93a848a88 100644 --- a/broker/bam/inc/com/centreon/broker/bam/ba.hh +++ b/broker/bam/inc/com/centreon/broker/bam/ba.hh @@ -1,5 +1,5 @@ /** - * Copyright 2014-2015, 2021-2023 Centreon + * Copyright 2014-2015, 2021-2024 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,9 +30,7 @@ #include "com/centreon/broker/io/stream.hh" #include "com/centreon/broker/persistent_cache.hh" -namespace com::centreon::broker { - -namespace bam { +namespace com::centreon::broker::bam { // Forward declaration. class kpi; @@ -112,7 +110,8 @@ class ba : public computable, public service_listener { uint32_t host_id, uint32_t service_id, configuration::ba::state_source source, - bool generate_virtual_status = true); + bool generate_virtual_status, + const std::shared_ptr& logger); ba(const ba&) = delete; virtual ~ba() noexcept = default; ba& operator=(ba const& other) = delete; @@ -154,8 +153,6 @@ class ba : public computable, public service_listener { void dump(const std::string& filename) const; void dump(std::ofstream& output) const override; }; -} // namespace bam - -} // namespace com::centreon::broker +} // namespace com::centreon::broker::bam #endif // !CCB_BAM_BA_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/ba_best.hh b/broker/bam/inc/com/centreon/broker/bam/ba_best.hh index 1cd0360088d..e5f5f75ca25 100644 --- a/broker/bam/inc/com/centreon/broker/bam/ba_best.hh +++ b/broker/bam/inc/com/centreon/broker/bam/ba_best.hh @@ -57,7 +57,8 @@ class ba_best : public ba { ba_best(uint32_t id, uint32_t host_id, uint32_t service_id, - bool generate_virtual_status = true); + bool generate_virtual_status, + const std::shared_ptr& logger); state get_state_hard() const override; state get_state_soft() const override; std::string get_output() const override; diff --git a/broker/bam/inc/com/centreon/broker/bam/ba_impact.hh b/broker/bam/inc/com/centreon/broker/bam/ba_impact.hh index b044c21a7db..7bdc012dea5 100644 --- a/broker/bam/inc/com/centreon/broker/bam/ba_impact.hh +++ b/broker/bam/inc/com/centreon/broker/bam/ba_impact.hh @@ -57,7 +57,8 @@ class ba_impact : public ba { ba_impact(uint32_t id, uint32_t host_id, uint32_t service_id, - bool generate_virtual_status = true); + bool generate_virtual_status, + const std::shared_ptr& logger); state get_state_hard() const override; state get_state_soft() const override; double get_ack_impact_hard() override; diff --git a/broker/bam/inc/com/centreon/broker/bam/ba_ratio_number.hh b/broker/bam/inc/com/centreon/broker/bam/ba_ratio_number.hh index 2ef730e62da..aacf1f5669a 100644 --- a/broker/bam/inc/com/centreon/broker/bam/ba_ratio_number.hh +++ b/broker/bam/inc/com/centreon/broker/bam/ba_ratio_number.hh @@ -48,7 +48,8 @@ class ba_ratio_number : public ba { ba_ratio_number(uint32_t id, uint32_t host_id, uint32_t service_id, - bool generate_virtual_status = true); + bool generate_virtual_status, + const std::shared_ptr& logger); state get_state_hard() const override; state get_state_soft() const override; std::string get_output() const override; diff --git a/broker/bam/inc/com/centreon/broker/bam/ba_ratio_percent.hh b/broker/bam/inc/com/centreon/broker/bam/ba_ratio_percent.hh index 3ae544c4229..6f0d59c6a07 100644 --- a/broker/bam/inc/com/centreon/broker/bam/ba_ratio_percent.hh +++ b/broker/bam/inc/com/centreon/broker/bam/ba_ratio_percent.hh @@ -48,7 +48,8 @@ class ba_ratio_percent : public ba { ba_ratio_percent(uint32_t id, uint32_t host_id, uint32_t service_id, - bool generate_virtual_status = true); + bool generate_virtual_status, + const std::shared_ptr& logger); state get_state_hard() const override; state get_state_soft() const override; std::string get_output() const override; diff --git a/broker/bam/inc/com/centreon/broker/bam/ba_svc_mapping.hh b/broker/bam/inc/com/centreon/broker/bam/ba_svc_mapping.hh index b252a460b0b..557883c4e4a 100644 --- a/broker/bam/inc/com/centreon/broker/bam/ba_svc_mapping.hh +++ b/broker/bam/inc/com/centreon/broker/bam/ba_svc_mapping.hh @@ -1,28 +1,25 @@ -/* -** Copyright 2014 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2014, 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_BAM_BA_SVC_MAPPING_HH #define CCB_BAM_BA_SVC_MAPPING_HH - -namespace com::centreon::broker { - -namespace bam { +namespace com::centreon::broker::bam { /** * @class ba_svc_mapping ba_svc_mapping.hh * "com/centreon/broker/bam/ba_svc_mapping.hh" @@ -42,8 +39,6 @@ class ba_svc_mapping { std::pair get_service(uint32_t ba_id); void set(uint32_t ba_id, const std::string& hst, const std::string& svc); }; -} // namespace bam - -} +} // namespace com::centreon::broker::bam #endif // !CCB_BAM_BA_SVC_MAPPING_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/ba_worst.hh b/broker/bam/inc/com/centreon/broker/bam/ba_worst.hh index 0e1dc2c52b7..dd3dd98fed5 100644 --- a/broker/bam/inc/com/centreon/broker/bam/ba_worst.hh +++ b/broker/bam/inc/com/centreon/broker/bam/ba_worst.hh @@ -57,7 +57,8 @@ class ba_worst : public ba { ba_worst(uint32_t id, uint32_t host_id, uint32_t service_id, - bool generate_virtual_status = true); + bool generate_virtual_status, + const std::shared_ptr& logger); state get_state_hard() const override; state get_state_soft() const override; std::string get_output() const override; diff --git a/broker/bam/inc/com/centreon/broker/bam/bool_and.hh b/broker/bam/inc/com/centreon/broker/bam/bool_and.hh index 527a8407ba0..62d9829c651 100644 --- a/broker/bam/inc/com/centreon/broker/bam/bool_and.hh +++ b/broker/bam/inc/com/centreon/broker/bam/bool_and.hh @@ -1,5 +1,5 @@ -/* - * Copyright 2014, 2021, 2023 Centreon +/** + * Copyright 2014, 2021, 2023-2024 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,9 +21,7 @@ #include "com/centreon/broker/bam/bool_binary_operator.hh" -namespace com::centreon::broker { - -namespace bam { +namespace com::centreon::broker::bam { /** * @class bool_and bool_and.hh "com/centreon/broker/bam/bool_and.hh" * @brief AND operator. @@ -38,7 +36,8 @@ class bool_and : public bool_binary_operator { virtual void _update_state() override; public: - bool_and() = default; + bool_and(const std::shared_ptr& logger) + : bool_binary_operator(logger) {} ~bool_and() noexcept override = default; bool_and(const bool_and&) = delete; bool_and& operator=(const bool_and&) = delete; @@ -46,8 +45,6 @@ class bool_and : public bool_binary_operator { bool boolean_value() const override; std::string object_info() const override; }; -} // namespace bam - -} // namespace com::centreon::broker +} // namespace com::centreon::broker::bam #endif // !CCB_BAM_BOOL_AND_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/bool_binary_operator.hh b/broker/bam/inc/com/centreon/broker/bam/bool_binary_operator.hh index b4ae59d3f54..6c74f3f7325 100644 --- a/broker/bam/inc/com/centreon/broker/bam/bool_binary_operator.hh +++ b/broker/bam/inc/com/centreon/broker/bam/bool_binary_operator.hh @@ -24,9 +24,7 @@ #define COMPARE_EPSILON 0.0001 -namespace com::centreon::broker { - -namespace bam { +namespace com::centreon::broker::bam { /** * @class bool_binary_operator bool_binary_operator.hh * "com/centreon/broker/bam/bool_binary_operator.hh" @@ -48,7 +46,8 @@ class bool_binary_operator : public bool_value { public: typedef std::shared_ptr ptr; - bool_binary_operator() = default; + bool_binary_operator(const std::shared_ptr& logger) + : bool_value(logger) {} bool_binary_operator(bool_binary_operator const&) = delete; ~bool_binary_operator() noexcept override = default; bool_binary_operator& operator=(const bool_binary_operator&) = delete; @@ -59,8 +58,6 @@ class bool_binary_operator : public bool_value { void update_from(computable* child, io::stream* visitor) override; void dump(std::ofstream& output) const override; }; -} // namespace bam - -} +} // namespace com::centreon::broker::bam #endif // !CCB_BAM_BOOL_BINARY_OPERATOR_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/bool_call.hh b/broker/bam/inc/com/centreon/broker/bam/bool_call.hh index 1924840ba42..2a0fcb25c04 100644 --- a/broker/bam/inc/com/centreon/broker/bam/bool_call.hh +++ b/broker/bam/inc/com/centreon/broker/bam/bool_call.hh @@ -1,5 +1,5 @@ -/* - * Copyright 2014, 2023 Centreon +/** + * Copyright 2014, 2023-2024 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,9 +22,7 @@ #include "com/centreon/broker/bam/bool_expression.hh" #include "com/centreon/broker/bam/bool_value.hh" -namespace com::centreon::broker { - -namespace bam { +namespace com::centreon::broker::bam { /** * @class bool_call bool_call.hh "com/centreon/broker/bam/bool_call.hh" * @brief Bool Call. @@ -39,7 +37,8 @@ class bool_call : public bool_value { public: typedef std::shared_ptr ptr; - bool_call(std::string const& name); + bool_call(std::string const& name, + const std::shared_ptr& logger); ~bool_call() noexcept override = default; bool_call(const bool_call&) = delete; bool_call& operator=(const bool_call&) = delete; @@ -50,8 +49,6 @@ class bool_call : public bool_value { void set_expression(std::shared_ptr expression); void update_from(computable* child, io::stream* visitor) override; }; -} // namespace bam - -} // namespace com::centreon::broker +} // namespace com::centreon::broker::bam #endif // !CCB_BAM_BOOL_CALL_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/bool_constant.hh b/broker/bam/inc/com/centreon/broker/bam/bool_constant.hh index bbf6356da09..34f0e7cef35 100644 --- a/broker/bam/inc/com/centreon/broker/bam/bool_constant.hh +++ b/broker/bam/inc/com/centreon/broker/bam/bool_constant.hh @@ -21,9 +21,8 @@ #include "com/centreon/broker/bam/bool_value.hh" -namespace com::centreon::broker { +namespace com::centreon::broker::bam { -namespace bam { /** * @class bool_and bool_and.hh "com/centreon/broker/bam/bool_and.hh" * @brief AND operator. @@ -37,7 +36,7 @@ class bool_constant : public bool_value { const bool _boolean_value; public: - bool_constant(double value); + bool_constant(double value, const std::shared_ptr& logger); ~bool_constant() noexcept override = default; bool_constant(const bool_constant&) = delete; bool_constant& operator=(const bool_constant&) = delete; @@ -48,8 +47,7 @@ class bool_constant : public bool_value { std::string object_info() const override; void dump(std::ofstream& output) const override; }; -} // namespace bam -} // namespace com::centreon::broker +} // namespace com::centreon::broker::bam #endif // !CCB_BAM_BOOL_CONSTANT_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/bool_equal.hh b/broker/bam/inc/com/centreon/broker/bam/bool_equal.hh index 536dfc735ad..19b465944a8 100644 --- a/broker/bam/inc/com/centreon/broker/bam/bool_equal.hh +++ b/broker/bam/inc/com/centreon/broker/bam/bool_equal.hh @@ -21,9 +21,7 @@ #include "com/centreon/broker/bam/bool_binary_operator.hh" -namespace com::centreon::broker { - -namespace bam { +namespace com::centreon::broker::bam { /** * @class bool_or bool_or.hh "com/centreon/broker/bam/bool_or.hh" * @brief OR operator. @@ -33,7 +31,8 @@ namespace bam { */ class bool_equal : public bool_binary_operator { public: - bool_equal() = default; + bool_equal(const std::shared_ptr& logger) + : bool_binary_operator(logger) {} ~bool_equal() noexcept override = default; bool_equal(const bool_equal&) = delete; bool_equal& operator=(const bool_equal&) = delete; @@ -41,8 +40,6 @@ class bool_equal : public bool_binary_operator { bool boolean_value() const override; std::string object_info() const override; }; -} // namespace bam - -} // namespace com::centreon::broker +} // namespace com::centreon::broker::bam #endif // !CCB_BAM_BOOL_EQUAL_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/bool_expression.hh b/broker/bam/inc/com/centreon/broker/bam/bool_expression.hh index 3cb37f5fcc2..5d86b17f21e 100644 --- a/broker/bam/inc/com/centreon/broker/bam/bool_expression.hh +++ b/broker/bam/inc/com/centreon/broker/bam/bool_expression.hh @@ -24,9 +24,7 @@ #include "com/centreon/broker/bam/computable.hh" #include "impact_values.hh" -namespace com::centreon::broker { - -namespace bam { +namespace com::centreon::broker::bam { // Forward declaration. class bool_value; @@ -44,7 +42,9 @@ class bool_expression : public computable { std::shared_ptr _expression; public: - bool_expression(uint32_t id, bool impact_if); + bool_expression(uint32_t id, + bool impact_if, + const std::shared_ptr& logger); bool_expression(const bool_expression&) = delete; ~bool_expression() noexcept override = default; bool_expression& operator=(const bool_expression&) = delete; @@ -58,8 +58,6 @@ class bool_expression : public computable { std::string object_info() const override; void dump(std::ofstream& output) const override; }; -} // namespace bam - -} // namespace com::centreon::broker +} // namespace com::centreon::broker::bam #endif // !CCB_BAM_BOOL_EXPRESSION_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/bool_less_than.hh b/broker/bam/inc/com/centreon/broker/bam/bool_less_than.hh index 6397f645b2c..3233da63352 100644 --- a/broker/bam/inc/com/centreon/broker/bam/bool_less_than.hh +++ b/broker/bam/inc/com/centreon/broker/bam/bool_less_than.hh @@ -1,5 +1,5 @@ /* - * Copyright 2014, 2021-2023 Centreon + * Copyright 2014, 2021-2024 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,9 +21,7 @@ #include "com/centreon/broker/bam/bool_binary_operator.hh" -namespace com::centreon::broker { - -namespace bam { +namespace com::centreon::broker::bam { /** * @class bool_less_than bool_less_than.hh * "com/centreon/broker/bam/bool_less_than.hh" @@ -36,7 +34,7 @@ class bool_less_than : public bool_binary_operator { const bool _strict; public: - bool_less_than(bool strict = false); + bool_less_than(bool strict, const std::shared_ptr& logger); ~bool_less_than() noexcept = default; bool_less_than(const bool_less_than&) = delete; bool_less_than& operator=(const bool_less_than&) = delete; @@ -44,8 +42,6 @@ class bool_less_than : public bool_binary_operator { bool boolean_value() const override; std::string object_info() const override; }; -} // namespace bam - -} // namespace com::centreon::broker +} // namespace com::centreon::broker::bam #endif // !CCB_BAM_BOOL_LESS_THAN_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/bool_more_than.hh b/broker/bam/inc/com/centreon/broker/bam/bool_more_than.hh index 32faa982226..e5dfacea3e7 100644 --- a/broker/bam/inc/com/centreon/broker/bam/bool_more_than.hh +++ b/broker/bam/inc/com/centreon/broker/bam/bool_more_than.hh @@ -21,9 +21,7 @@ #include "com/centreon/broker/bam/bool_binary_operator.hh" -namespace com::centreon::broker { - -namespace bam { +namespace com::centreon::broker::bam { /** * @class bool_or bool_or.hh "com/centreon/broker/bam/bool_or.hh" * @brief OR operator. @@ -35,7 +33,7 @@ class bool_more_than : public bool_binary_operator { const bool _strict; public: - bool_more_than(bool strict = false); + bool_more_than(bool strict, const std::shared_ptr& logger); bool_more_than(const bool_more_than&) = delete; ~bool_more_than() noexcept = default; bool_more_than& operator=(const bool_more_than&) = delete; @@ -43,8 +41,6 @@ class bool_more_than : public bool_binary_operator { bool boolean_value() const override; std::string object_info() const override; }; -} // namespace bam - -} // namespace com::centreon::broker +} // namespace com::centreon::broker::bam #endif // !CCB_BAM_BOOL_MORE_THAN_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/bool_not.hh b/broker/bam/inc/com/centreon/broker/bam/bool_not.hh index 9e475eb20f5..a53f8094ecd 100644 --- a/broker/bam/inc/com/centreon/broker/bam/bool_not.hh +++ b/broker/bam/inc/com/centreon/broker/bam/bool_not.hh @@ -22,9 +22,7 @@ #include "com/centreon/broker/bam/bool_value.hh" #include "com/centreon/broker/io/stream.hh" -namespace com::centreon::broker { - -namespace bam { +namespace com::centreon::broker::bam { // Forward declaration. class bool_value; @@ -39,7 +37,7 @@ class bool_not : public bool_value { bool_value::ptr _value; public: - bool_not(bool_value::ptr val = bool_value::ptr()); + bool_not(bool_value::ptr val, const std::shared_ptr& logger); bool_not(const bool_not&) = delete; ~bool_not() noexcept = default; bool_not& operator=(const bool_not&) = delete; @@ -53,8 +51,6 @@ class bool_not : public bool_value { std::string object_info() const override; void dump(std::ofstream& output) const override; }; -} // namespace bam - -} // namespace com::centreon::broker +} // namespace com::centreon::broker::bam #endif // !CCB_BAM_BOOL_NOT_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/bool_not_equal.hh b/broker/bam/inc/com/centreon/broker/bam/bool_not_equal.hh index 0f7515c56a7..d4fa1f1ced9 100644 --- a/broker/bam/inc/com/centreon/broker/bam/bool_not_equal.hh +++ b/broker/bam/inc/com/centreon/broker/bam/bool_not_equal.hh @@ -21,9 +21,7 @@ #include "com/centreon/broker/bam/bool_binary_operator.hh" -namespace com::centreon::broker { - -namespace bam { +namespace com::centreon::broker::bam { /** * @class bool_not_equal bool_not_equal.hh * "com/centreon/broker/bam/bool_not_equal.hh" @@ -34,7 +32,8 @@ namespace bam { */ class bool_not_equal : public bool_binary_operator { public: - bool_not_equal() = default; + bool_not_equal(const std::shared_ptr& logger) + : bool_binary_operator(logger) {} bool_not_equal(const bool_not_equal&) = delete; ~bool_not_equal() noexcept override = default; bool_not_equal& operator=(const bool_not_equal&) = delete; @@ -42,8 +41,6 @@ class bool_not_equal : public bool_binary_operator { bool boolean_value() const override; std::string object_info() const override; }; -} // namespace bam - -} // namespace com::centreon::broker +} // namespace com::centreon::broker::bam #endif // !CCB_BAM_BOOL_NOT_EQUAL_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/bool_operation.hh b/broker/bam/inc/com/centreon/broker/bam/bool_operation.hh index 53dc75b75b2..eef9371db3e 100644 --- a/broker/bam/inc/com/centreon/broker/bam/bool_operation.hh +++ b/broker/bam/inc/com/centreon/broker/bam/bool_operation.hh @@ -21,9 +21,7 @@ #include "com/centreon/broker/bam/bool_binary_operator.hh" -namespace com::centreon::broker { - -namespace bam { +namespace com::centreon::broker::bam { /** * @class bool_operation bool_operation.hh * "com/centreon/broker/bam/bool_operation.hh" @@ -43,7 +41,8 @@ class bool_operation : public bool_binary_operator { const operation_type _type; public: - bool_operation(std::string const& op); + bool_operation(const std::string& op, + const std::shared_ptr& logger); ~bool_operation() noexcept override = default; bool_operation(const bool_operation&) = delete; bool_operation& operator=(const bool_operation&) = delete; @@ -52,8 +51,6 @@ class bool_operation : public bool_binary_operator { bool state_known() const override; std::string object_info() const override; }; -} // namespace bam - -} // namespace com::centreon::broker +} // namespace com::centreon::broker::bam #endif // !CCB_BAM_BOOL_OR_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/bool_or.hh b/broker/bam/inc/com/centreon/broker/bam/bool_or.hh index 8a19fcf1791..1ca91253ffe 100644 --- a/broker/bam/inc/com/centreon/broker/bam/bool_or.hh +++ b/broker/bam/inc/com/centreon/broker/bam/bool_or.hh @@ -21,9 +21,8 @@ #include "com/centreon/broker/bam/bool_binary_operator.hh" -namespace com::centreon::broker { +namespace com::centreon::broker::bam { -namespace bam { /** * @class bool_or bool_or.hh "com/centreon/broker/bam/bool_or.hh" * @brief OR operator. @@ -35,10 +34,11 @@ class bool_or : public bool_binary_operator { bool _boolean_value = false; protected: - virtual void _update_state() override; + void _update_state() override; public: - bool_or() = default; + bool_or(const std::shared_ptr& logger) + : bool_binary_operator(logger) {} ~bool_or() noexcept override = default; bool_or(const bool_or&) = delete; bool_or& operator=(const bool_or&) = delete; @@ -46,8 +46,7 @@ class bool_or : public bool_binary_operator { bool boolean_value() const override; std::string object_info() const override; }; -} // namespace bam -} // namespace com::centreon::broker +} // namespace com::centreon::broker::bam #endif // !CCB_BAM_BOOL_OR_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/bool_service.hh b/broker/bam/inc/com/centreon/broker/bam/bool_service.hh index 3981b24aa56..03d3c13053b 100644 --- a/broker/bam/inc/com/centreon/broker/bam/bool_service.hh +++ b/broker/bam/inc/com/centreon/broker/bam/bool_service.hh @@ -1,5 +1,5 @@ -/* - * Copyright 2014, 2021-2023 Centreon +/** + * Copyright 2014, 2021-2024 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,9 +24,7 @@ #include "com/centreon/broker/io/stream.hh" #include "com/centreon/broker/neb/internal.hh" -namespace com::centreon::broker { - -namespace bam { +namespace com::centreon::broker::bam { /** * @class bool_service bool_service.hh * "com/centreon/broker/bam/bool_service.hh" @@ -45,7 +43,9 @@ class bool_service : public bool_value, public service_listener { public: typedef std::shared_ptr ptr; - bool_service(uint32_t host_id, uint32_t service_id); + bool_service(uint32_t host_id, + uint32_t service_id, + const std::shared_ptr& logger); ~bool_service() noexcept = default; bool_service(const bool_service&) = delete; bool_service& operator=(const bool_service&) = delete; @@ -66,8 +66,6 @@ class bool_service : public bool_value, public service_listener { std::string object_info() const override; void dump(std::ofstream& output) const override; }; -} // namespace bam - -} // namespace com::centreon::broker +} // namespace com::centreon::broker::bam #endif // !CCB_BAM_BOOL_SERVICE_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/bool_value.hh b/broker/bam/inc/com/centreon/broker/bam/bool_value.hh index 6403b7dcbc6..111d267b4e7 100644 --- a/broker/bam/inc/com/centreon/broker/bam/bool_value.hh +++ b/broker/bam/inc/com/centreon/broker/bam/bool_value.hh @@ -21,9 +21,7 @@ #include "com/centreon/broker/bam/computable.hh" -namespace com::centreon::broker { - -namespace bam { +namespace com::centreon::broker::bam { /** * @class bool_value bool_value.hh "com/centreon/broker/bam/bool_value.hh" * @brief Computable boolean value. @@ -34,7 +32,8 @@ class bool_value : public computable { public: typedef std::shared_ptr ptr; - bool_value() = default; + bool_value(const std::shared_ptr& logger) + : computable(logger) {} ~bool_value() noexcept override = default; bool_value(const bool_value&) = delete; bool_value& operator=(const bool_value&) = delete; @@ -43,8 +42,6 @@ class bool_value : public computable { virtual bool state_known() const = 0; virtual bool in_downtime() const; }; -} // namespace bam - -} // namespace com::centreon::broker +} // namespace com::centreon::broker::bam #endif // !CCB_BAM_BOOL_VALUE_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/bool_xor.hh b/broker/bam/inc/com/centreon/broker/bam/bool_xor.hh index 12025584c15..54c0ec4407f 100644 --- a/broker/bam/inc/com/centreon/broker/bam/bool_xor.hh +++ b/broker/bam/inc/com/centreon/broker/bam/bool_xor.hh @@ -1,5 +1,5 @@ -/* - * Copyright 2014, 2021 Centreon +/** + * Copyright 2014, 2021-2024 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,9 +21,7 @@ #include "com/centreon/broker/bam/bool_binary_operator.hh" -namespace com::centreon::broker { - -namespace bam { +namespace com::centreon::broker::bam { /** * @class bool_xor bool_xor.hh "com/centreon/broker/bam/bool_xor.hh" * @brief XOR operator. @@ -33,7 +31,8 @@ namespace bam { */ class bool_xor : public bool_binary_operator { public: - bool_xor() = default; + bool_xor(const std::shared_ptr& logger) + : bool_binary_operator(logger) {} ~bool_xor() noexcept = default; bool_xor(const bool_xor&) = delete; bool_xor& operator=(const bool_xor&) = delete; @@ -41,8 +40,6 @@ class bool_xor : public bool_binary_operator { bool boolean_value() const override; std::string object_info() const override; }; -} // namespace bam - -} // namespace com::centreon::broker +} // namespace com::centreon::broker::bam #endif // !CCB_BAM_BOOL_XOR_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/computable.hh b/broker/bam/inc/com/centreon/broker/bam/computable.hh index cbee3ebca03..389f83e796f 100644 --- a/broker/bam/inc/com/centreon/broker/bam/computable.hh +++ b/broker/bam/inc/com/centreon/broker/bam/computable.hh @@ -21,9 +21,7 @@ #include "com/centreon/broker/persistent_cache.hh" -namespace com::centreon::broker { - -namespace bam { +namespace com::centreon::broker::bam { /** * @class computable computable.hh "com/centreon/broker/bam/computable.hh" * @brief Object that get computed by the BAM engine. @@ -34,9 +32,10 @@ namespace bam { class computable { protected: std::list> _parents; + std::shared_ptr _logger; public: - computable() = default; + computable(const std::shared_ptr& logger) : _logger(logger) {} computable(const computable&) = delete; virtual ~computable() noexcept = default; computable& operator=(const computable&) = delete; @@ -69,8 +68,6 @@ class computable { virtual void dump(std::ofstream& output) const = 0; void dump_parents(std::ofstream& output) const; }; -} // namespace bam - -} // namespace com::centreon::broker +} // namespace com::centreon::broker::bam #endif // !CCB_BAM_COMPUTABLE_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/configuration/applier/ba.hh b/broker/bam/inc/com/centreon/broker/bam/configuration/applier/ba.hh index 7785f86197a..537eb2d7a09 100644 --- a/broker/bam/inc/com/centreon/broker/bam/configuration/applier/ba.hh +++ b/broker/bam/inc/com/centreon/broker/bam/configuration/applier/ba.hh @@ -1,5 +1,5 @@ -/* - * Copyright 2014-2015 Centreon +/** + * Copyright 2014-2015, 2022-2024 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,9 +34,7 @@ class host; class service; } // namespace neb -namespace bam { -namespace configuration { -namespace applier { +namespace bam::configuration::applier { /** * @class ba ba.hh "com/centreon/broker/bam/configuration/applier/ba.hh" * @brief Apply BA configuration. @@ -44,6 +42,7 @@ namespace applier { * Take the configuration of BAs and apply it. */ class ba { + std::shared_ptr _logger; struct applied { configuration::ba cfg; std::shared_ptr obj; @@ -65,7 +64,7 @@ class ba { service_book& book); public: - ba(); + ba(const std::shared_ptr& logger); ba(const ba& other); ~ba(); ba& operator=(ba const& other); @@ -76,9 +75,7 @@ class ba { void apply_inherited_downtime(const inherited_downtime& dwn); void apply_inherited_downtime(const pb_inherited_downtime& dwn); }; -} // namespace applier -} // namespace configuration -} // namespace bam +} // namespace bam::configuration::applier } // namespace com::centreon::broker diff --git a/broker/bam/inc/com/centreon/broker/bam/configuration/applier/bool_expression.hh b/broker/bam/inc/com/centreon/broker/bam/configuration/applier/bool_expression.hh index d351229cc3c..f28b6cc5313 100644 --- a/broker/bam/inc/com/centreon/broker/bam/configuration/applier/bool_expression.hh +++ b/broker/bam/inc/com/centreon/broker/bam/configuration/applier/bool_expression.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2014 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2014, 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_BAM_CONFIGURATION_APPLIER_BOOL_EXPRESSION_HH #define CCB_BAM_CONFIGURATION_APPLIER_BOOL_EXPRESSION_HH @@ -22,6 +22,10 @@ #include "com/centreon/broker/bam/configuration/bool_expression.hh" #include "com/centreon/broker/bam/configuration/state.hh" +#include "common/log_v2/log_v2.hh" + +using log_v2 = com::centreon::common::log_v2::log_v2; + namespace com::centreon::broker { namespace bam { @@ -53,12 +57,16 @@ class bool_expression { std::map _applied; + /* Logger */ + std::shared_ptr _logger; + std::shared_ptr _new_bool_exp( configuration::bool_expression const& cfg); void _resolve_expression_calls(); public: - bool_expression() = default; + bool_expression(const std::shared_ptr& logger) + : _logger{logger} {} bool_expression(const bool_expression&) = delete; ~bool_expression() noexcept = default; bool_expression& operator=(const bool_expression&) = delete; @@ -71,6 +79,6 @@ class bool_expression { } // namespace configuration } // namespace bam -} +} // namespace com::centreon::broker #endif // !CCB_BAM_CONFIGURATION_APPLIER_BOOL_EXPRESSION_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/configuration/applier/kpi.hh b/broker/bam/inc/com/centreon/broker/bam/configuration/applier/kpi.hh index 4328ec82308..fc4b18c3d91 100644 --- a/broker/bam/inc/com/centreon/broker/bam/configuration/applier/kpi.hh +++ b/broker/bam/inc/com/centreon/broker/bam/configuration/applier/kpi.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2014-2015 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2014-2015, 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_BAM_CONFIGURATION_APPLIER_KPI_HH #define CCB_BAM_CONFIGURATION_APPLIER_KPI_HH @@ -43,23 +43,16 @@ class bool_expression; * Take the configuration of KPIs and apply it. */ class kpi { - public: - kpi(); - kpi(kpi const& other); - ~kpi() noexcept = default; - kpi& operator=(kpi const& other); - void apply(configuration::state::kpis const& my_kpis, - hst_svc_mapping const& mapping, - ba& my_bas, - bool_expression& my_boolexps, - service_book& book); - void visit(io::stream* visitor); - - private: + std::shared_ptr _logger; struct applied { configuration::kpi cfg; std::shared_ptr obj; }; + std::map _applied; + ba* _bas; + service_book* _book; + bool_expression* _boolexps; + hst_svc_mapping const* _mapping; void _internal_copy(kpi const& other); std::shared_ptr _new_kpi(configuration::kpi const& cfg); @@ -69,16 +62,22 @@ class kpi { void _resolve_kpi(configuration::kpi const& cfg, const std::shared_ptr&); - std::map _applied; - ba* _bas; - service_book* _book; - bool_expression* _boolexps; - hst_svc_mapping const* _mapping; + public: + kpi(const std::shared_ptr& logger); + kpi(kpi const& other); + ~kpi() noexcept = default; + kpi& operator=(kpi const& other); + void apply(configuration::state::kpis const& my_kpis, + hst_svc_mapping const& mapping, + ba& my_bas, + bool_expression& my_boolexps, + service_book& book); + void visit(io::stream* visitor); }; } // namespace applier } // namespace configuration } // namespace bam -} +} // namespace com::centreon::broker #endif // !CCB_BAM_CONFIGURATION_APPLIER_KPI_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/configuration/applier/state.hh b/broker/bam/inc/com/centreon/broker/bam/configuration/applier/state.hh index d71e1e6397e..221c4404d08 100644 --- a/broker/bam/inc/com/centreon/broker/bam/configuration/applier/state.hh +++ b/broker/bam/inc/com/centreon/broker/bam/configuration/applier/state.hh @@ -24,9 +24,7 @@ #include "com/centreon/broker/bam/configuration/applier/kpi.hh" #include "com/centreon/broker/bam/service_book.hh" -namespace com::centreon::broker { - -namespace bam { +namespace com::centreon::broker::bam { // Forward declaration. class monitoring_stream; @@ -43,6 +41,8 @@ namespace applier { * Take the configuration of the BAM engine and apply it. */ class state { + std::shared_ptr _logger; + struct circular_check_node { circular_check_node(); @@ -50,19 +50,18 @@ class state { bool visited; std::set targets; }; - - void _circular_check(configuration::state const& my_state); - void _circular_check(circular_check_node& n); - void _internal_copy(state const& other); - ba _ba_applier; service_book _book_service; kpi _kpi_applier; bool_expression _bool_exp_applier; std::unordered_map _nodes; + void _circular_check(configuration::state const& my_state); + void _circular_check(circular_check_node& n); + void _internal_copy(state const& other); + public: - state() = default; + state(const std::shared_ptr& logger); ~state() noexcept = default; state(const state&) = delete; state& operator=(state const& other) = delete; @@ -75,8 +74,6 @@ class state { }; } // namespace applier } // namespace configuration -} // namespace bam - -} // namespace com::centreon::broker +} // namespace com::centreon::broker::bam #endif // !CCB_BAM_CONFIGURATION_APPLIER_STATE_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/configuration/ba.hh b/broker/bam/inc/com/centreon/broker/bam/configuration/ba.hh index 45b0cf701be..268d612d6fd 100644 --- a/broker/bam/inc/com/centreon/broker/bam/configuration/ba.hh +++ b/broker/bam/inc/com/centreon/broker/bam/configuration/ba.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2014 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2014, 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_BAM_CONFIGURATION_BA_HH #define CCB_BAM_CONFIGURATION_BA_HH @@ -93,6 +93,6 @@ class ba { } // namespace configuration } // namespace bam -} +} // namespace com::centreon::broker #endif // !CCB_BAM_CONFIGURATION_BA_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/configuration/bool_expression.hh b/broker/bam/inc/com/centreon/broker/bam/configuration/bool_expression.hh index 7f7a88ecaa2..950bd1fd296 100644 --- a/broker/bam/inc/com/centreon/broker/bam/configuration/bool_expression.hh +++ b/broker/bam/inc/com/centreon/broker/bam/configuration/bool_expression.hh @@ -1,25 +1,24 @@ -/* -** Copyright 2014 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2014, 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef BAM_CCB_CONFIGURATION_BOOL_EXPRESSION_HH #define BAM_CCB_CONFIGURATION_BOOL_EXPRESSION_HH - namespace com::centreon::broker { namespace bam { @@ -63,6 +62,6 @@ class bool_expression { } // namespace configuration } // namespace bam -} +} // namespace com::centreon::broker #endif // !CCB_BAM_CONFIGURATION_BOOL_EXPRESSION_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/configuration/kpi.hh b/broker/bam/inc/com/centreon/broker/bam/configuration/kpi.hh index 4bb02974a42..a87444a6df5 100644 --- a/broker/bam/inc/com/centreon/broker/bam/configuration/kpi.hh +++ b/broker/bam/inc/com/centreon/broker/bam/configuration/kpi.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2014 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2014, 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_BAM_CONFIGURATION_KPI_HH #define CCB_BAM_CONFIGURATION_KPI_HH @@ -119,6 +119,6 @@ class kpi { } // namespace configuration } // namespace bam -} +} // namespace com::centreon::broker #endif // CCB_BAM_CONFIGURATION_KPI_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/configuration/reader_exception.hh b/broker/bam/inc/com/centreon/broker/bam/configuration/reader_exception.hh index c77b560113b..387d79f869a 100644 --- a/broker/bam/inc/com/centreon/broker/bam/configuration/reader_exception.hh +++ b/broker/bam/inc/com/centreon/broker/bam/configuration/reader_exception.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2014 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2014, 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_CONFIGURATION_READER_EXCEPTION_HH #define CCB_CONFIGURATION_READER_EXCEPTION_HH @@ -45,6 +45,6 @@ class reader_exception : public com::centreon::exceptions::msg_fmt { } // namespace configuration } // namespace bam -} +} // namespace com::centreon::broker #endif // !CCB_CONFIGURATION_READER_EXCEPTION_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/configuration/reader_v2.hh b/broker/bam/inc/com/centreon/broker/bam/configuration/reader_v2.hh index 438ea7fd56f..2758b42451e 100644 --- a/broker/bam/inc/com/centreon/broker/bam/configuration/reader_v2.hh +++ b/broker/bam/inc/com/centreon/broker/bam/configuration/reader_v2.hh @@ -1,25 +1,26 @@ -/* -** Copyright 2014-2016 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2014-2016, 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_BAM_CONFIGURATION_READER_V2_HH #define CCB_BAM_CONFIGURATION_READER_V2_HH #include "com/centreon/broker/bam/configuration/state.hh" + #include "com/centreon/broker/sql/database_config.hh" namespace com::centreon::broker { @@ -27,8 +28,7 @@ namespace com::centreon::broker { // Forward declaration. class mysql; -namespace bam { -namespace configuration { +namespace bam::configuration { /** * @class reader_v2 reader_v2.hh * "com/centreon/broker/bam/configuration/reader_v2.hh" @@ -39,12 +39,10 @@ namespace configuration { * the BAM engine. */ class reader_v2 { - public: - reader_v2(mysql& centreon_db, const database_config& storage_cfg); - ~reader_v2() noexcept = default; - void read(state& state_obj); + std::shared_ptr _logger; + mysql& _mysql; + database_config _storage_cfg; - private: reader_v2(reader_v2 const& other); reader_v2& operator=(reader_v2 const& other); void _load(state::kpis& kpis); @@ -54,12 +52,13 @@ class reader_v2 { void _load(bam::hst_svc_mapping& mapping); void _load_dimensions(); - mysql& _mysql; - database_config _storage_cfg; + public: + reader_v2(mysql& centreon_db, const database_config& storage_cfg); + ~reader_v2() noexcept = default; + void read(state& state_obj); }; -} // namespace configuration -} // namespace bam +} // namespace bam::configuration -} +} // namespace com::centreon::broker #endif // !CCB_BAM_CONFIGURATION_READER_V2_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/configuration/state.hh b/broker/bam/inc/com/centreon/broker/bam/configuration/state.hh index f752da38b35..8976a97aa8f 100644 --- a/broker/bam/inc/com/centreon/broker/bam/configuration/state.hh +++ b/broker/bam/inc/com/centreon/broker/bam/configuration/state.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2014-2015 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2014-2015, 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_BAM_CONFIGURATION_STATE_HH #define CCB_BAM_CONFIGURATION_STATE_HH @@ -42,7 +42,8 @@ class state { using kpis = std::unordered_map; using bool_exps = std::unordered_map; - state() = default; + state(const std::shared_ptr& logger) + : _hst_svc_mapping(logger) {} ~state() noexcept = default; state(const state&) = delete; state& operator=(const state&) = delete; @@ -72,6 +73,6 @@ class state { } // namespace configuration } // namespace bam -} +} // namespace com::centreon::broker #endif // ! CCB_BAM_CONFIGURATION_STATE_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/connector.hh b/broker/bam/inc/com/centreon/broker/bam/connector.hh index 09a0359e35d..0c1e1c64ce9 100644 --- a/broker/bam/inc/com/centreon/broker/bam/connector.hh +++ b/broker/bam/inc/com/centreon/broker/bam/connector.hh @@ -1,5 +1,5 @@ /* -** Copyright 2014-2015, 2020-2023 Centreon +** Copyright 2014-2015, 2020-2024 Centreon ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. @@ -22,9 +22,7 @@ #include "com/centreon/broker/io/endpoint.hh" #include "com/centreon/broker/sql/database_config.hh" -namespace com::centreon::broker { - -namespace bam { +namespace com::centreon::broker::bam { /** * @class connector connector.hh "com/centreon/broker/bam/connector.hh" * @brief Connect to a database. @@ -42,7 +40,8 @@ class connector : public io::endpoint { connector(stream_type type, const database_config& db_cfg, - const multiplexing::muxer_filter& filter); + const multiplexing::muxer_filter& mandatory_filter, + const multiplexing::muxer_filter& forbidden_filter); public: static std::unique_ptr create_monitoring_connector( @@ -64,8 +63,6 @@ class connector : public io::endpoint { void connect_reporting(database_config const& db_cfg); std::shared_ptr open() override; }; -} // namespace bam - -} +} // namespace com::centreon::broker::bam #endif // !CCB_BAM_CONNECTOR_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/event_cache_visitor.hh b/broker/bam/inc/com/centreon/broker/bam/event_cache_visitor.hh index 161a2061ab0..b2aba8f9246 100644 --- a/broker/bam/inc/com/centreon/broker/bam/event_cache_visitor.hh +++ b/broker/bam/inc/com/centreon/broker/bam/event_cache_visitor.hh @@ -1,29 +1,27 @@ -/* -** Copyright 2014-2015, 2020-2021 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2014-2015, 2020-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_BAM_EVENT_CACHE_VISITOR_HH #define CCB_BAM_EVENT_CACHE_VISITOR_HH #include "com/centreon/broker/io/stream.hh" -namespace com::centreon::broker { - -namespace bam { +namespace com::centreon::broker::bam { /** * @class event_cache_visitor event_cache_visitor.hh * "com/centreon/broker/bam/event_cache_visitor.hh" @@ -33,9 +31,9 @@ namespace bam { * this order: others, ba_events, kpi_events. */ class event_cache_visitor : public io::stream { - std::vector > _others; - std::vector > _ba_events; - std::vector > _kpi_events; + std::vector> _others; + std::vector> _ba_events; + std::vector> _kpi_events; public: event_cache_visitor(); @@ -47,8 +45,6 @@ class event_cache_visitor : public io::stream { virtual int write(std::shared_ptr const& d) override; int32_t stop() override { return 0; } }; -} // namespace bam - -} +} // namespace com::centreon::broker::bam #endif // !CCB_BAM_EVENT_CACHE_VISITOR_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/exp_builder.hh b/broker/bam/inc/com/centreon/broker/bam/exp_builder.hh index 8bdfa7ebbd9..ea48124a243 100644 --- a/broker/bam/inc/com/centreon/broker/bam/exp_builder.hh +++ b/broker/bam/inc/com/centreon/broker/bam/exp_builder.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2016 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2016, 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_BAM_EXP_BUILDER_HH #define CCB_BAM_EXP_BUILDER_HH @@ -24,9 +24,7 @@ #include "com/centreon/broker/bam/exp_parser.hh" #include "com/centreon/broker/bam/hst_svc_mapping.hh" -namespace com::centreon::broker { - -namespace bam { +namespace com::centreon::broker::bam { /** * @class exp_builder exp_builder.hh "com/centreon/broker/bam/exp_builder.hh" * @brief Convert expression to syntax tree. @@ -41,6 +39,7 @@ class exp_builder { using any_operand = std::pair; private: + std::shared_ptr _logger; hst_svc_mapping const& _mapping; list_call _calls; list_service _services; @@ -54,7 +53,8 @@ class exp_builder { public: exp_builder(exp_parser::notation const& postfix, - hst_svc_mapping const& mapping); + hst_svc_mapping const& mapping, + const std::shared_ptr& logger); exp_builder(const exp_builder&) = delete; exp_builder& operator=(const exp_builder&); ~exp_builder() noexcept = default; @@ -62,8 +62,6 @@ class exp_builder { list_service const& get_services() const; bool_value::ptr get_tree() const; }; -} // namespace bam - -} +} // namespace com::centreon::broker::bam #endif // !CCB_BAM_EXP_BUILDER_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/exp_parser.hh b/broker/bam/inc/com/centreon/broker/bam/exp_parser.hh index b31f1a7f3d0..7a79cb9f5d6 100644 --- a/broker/bam/inc/com/centreon/broker/bam/exp_parser.hh +++ b/broker/bam/inc/com/centreon/broker/bam/exp_parser.hh @@ -1,28 +1,25 @@ -/* -** Copyright 2016 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2016 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_BAM_EXP_PARSER_HH #define CCB_BAM_EXP_PARSER_HH - -namespace com::centreon::broker { - -namespace bam { +namespace com::centreon::broker::bam { /** * @class exp_parser exp_parser.hh "com/centreon/broker/bam/exp_parser.hh" * @brief Expression parser. @@ -44,7 +41,7 @@ class exp_parser { notation _postfix; public: - exp_parser(std::string const& expression); + exp_parser(const std::string& expression); exp_parser(exp_parser const&) = delete; ~exp_parser() noexcept = default; exp_parser& operator=(const exp_parser&) = delete; @@ -52,8 +49,6 @@ class exp_parser { static bool is_function(std::string const& token); static bool is_operator(std::string const& token); }; -} // namespace bam - -} +} // namespace com::centreon::broker::bam #endif // !CCB_BAM_EXP_PARSER_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/exp_tokenizer.hh b/broker/bam/inc/com/centreon/broker/bam/exp_tokenizer.hh index 9fa9b98b366..8205401e753 100644 --- a/broker/bam/inc/com/centreon/broker/bam/exp_tokenizer.hh +++ b/broker/bam/inc/com/centreon/broker/bam/exp_tokenizer.hh @@ -1,28 +1,25 @@ -/* -** Copyright 2016 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2016, 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_BAM_EXP_TOKENIZER_HH #define CCB_BAM_EXP_TOKENIZER_HH - -namespace com::centreon::broker { - -namespace bam { +namespace com::centreon::broker::bam { /** * @class exp_tokenizer exp_tokenizer.hh * "com/centreon/broker/bam/exp_tokenizer.hh" @@ -54,8 +51,6 @@ class exp_tokenizer { std::size_t _size; std::string _text; }; -} // namespace bam - -} +} // namespace com::centreon::broker::bam #endif // !CCB_BAM_EXP_TOKENIZER_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/factory.hh b/broker/bam/inc/com/centreon/broker/bam/factory.hh index 328dd1e86dd..9d5251b780b 100644 --- a/broker/bam/inc/com/centreon/broker/bam/factory.hh +++ b/broker/bam/inc/com/centreon/broker/bam/factory.hh @@ -21,9 +21,7 @@ #include "com/centreon/broker/io/factory.hh" -namespace com::centreon::broker { - -namespace bam { +namespace com::centreon::broker::bam { /** * @class factory factory.hh "com/centreon/broker/bam/factory.hh" * @brief BAM layer factory. @@ -43,8 +41,6 @@ class factory : public io::factory { std::shared_ptr cache = std::shared_ptr()) const override; }; -} // namespace bam - -} +} // namespace com::centreon::broker::bam #endif // !CCB_BAM_FACTORY_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/hst_svc_mapping.hh b/broker/bam/inc/com/centreon/broker/bam/hst_svc_mapping.hh index e2b392e2dd6..3f825c67b12 100644 --- a/broker/bam/inc/com/centreon/broker/bam/hst_svc_mapping.hh +++ b/broker/bam/inc/com/centreon/broker/bam/hst_svc_mapping.hh @@ -1,30 +1,32 @@ -/* -** Copyright 2014, 2021 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2014, 2021-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_BAM_HST_SVC_MAPPING_HH #define CCB_BAM_HST_SVC_MAPPING_HH #include +#include "common/log_v2/log_v2.hh" -namespace com::centreon::broker { +namespace com::centreon::broker::bam { + +using com::centreon::common::log_v2::log_v2; -namespace bam { /** * @class hst_svc_mapping hst_svc_mapping.hh * "com/centreon/broker/bam/hst_svc_mapping.hh" @@ -33,6 +35,7 @@ namespace bam { * Allow to find an ID of a host or service by its name. */ class hst_svc_mapping { + std::shared_ptr _logger; absl::flat_hash_map, std::pair> _mapping; @@ -40,7 +43,8 @@ class hst_svc_mapping { absl::flat_hash_map, bool> _activated_mapping; public: - hst_svc_mapping() = default; + hst_svc_mapping(const std::shared_ptr& logger) + : _logger{logger} {} ~hst_svc_mapping() noexcept = default; hst_svc_mapping(const hst_svc_mapping&) = delete; hst_svc_mapping& operator=(const hst_svc_mapping&) = delete; @@ -56,8 +60,6 @@ class hst_svc_mapping { bool get_activated(uint32_t hst_id, uint32_t service_id) const; }; -} // namespace bam - -} +} // namespace com::centreon::broker::bam #endif // !CCB_BAM_HST_SVC_MAPPING_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/impact_values.hh b/broker/bam/inc/com/centreon/broker/bam/impact_values.hh index 34cc2c8daa6..22d55c545bd 100644 --- a/broker/bam/inc/com/centreon/broker/bam/impact_values.hh +++ b/broker/bam/inc/com/centreon/broker/bam/impact_values.hh @@ -1,5 +1,5 @@ /** - * Copyright 2014, 2024 Centreon + * Copyright 2014-2024 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,9 +21,7 @@ #include "bbdo/bam/state.hh" -namespace com::centreon::broker { - -namespace bam { +namespace com::centreon::broker::bam { /** * @class impact_values impact_values.hh * "com/centreon/broker/bam/impact_values.hh" @@ -58,8 +56,6 @@ class impact_values { void set_nominal(double nominal); void set_state(state state); }; -} // namespace bam - -} // namespace com::centreon::broker +} // namespace com::centreon::broker::bam #endif // !CCB_BAM_IMPACT_VALUES_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/internal.hh b/broker/bam/inc/com/centreon/broker/bam/internal.hh index 46daadc543f..58213184434 100644 --- a/broker/bam/inc/com/centreon/broker/bam/internal.hh +++ b/broker/bam/inc/com/centreon/broker/bam/internal.hh @@ -28,6 +28,7 @@ namespace com::centreon::broker { namespace bam { + using pb_inherited_downtime = io::protobuf; diff --git a/broker/bam/inc/com/centreon/broker/bam/kpi.hh b/broker/bam/inc/com/centreon/broker/bam/kpi.hh index 63397252379..9602012eb73 100644 --- a/broker/bam/inc/com/centreon/broker/bam/kpi.hh +++ b/broker/bam/inc/com/centreon/broker/bam/kpi.hh @@ -24,9 +24,7 @@ #include "com/centreon/broker/io/stream.hh" #include "com/centreon/broker/timestamp.hh" -namespace com::centreon::broker { - -namespace bam { +namespace com::centreon::broker::bam { // Forward declarations. class ba; class impact_values; @@ -49,7 +47,10 @@ class kpi : public computable { void _event_init(); public: - kpi(uint32_t kpi_id, uint32_t ba_id, const std::string& name); + kpi(uint32_t kpi_id, + uint32_t ba_id, + const std::string& name, + const std::shared_ptr& logger); virtual ~kpi() noexcept = default; kpi& operator=(const kpi&) = delete; kpi(const kpi&) = delete; @@ -66,8 +67,6 @@ class kpi : public computable { void commit_initial_events(io::stream* visitor); }; -} // namespace bam - -} // namespace com::centreon::broker +} // namespace com::centreon::broker::bam #endif // !CCB_BAM_KPI_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/kpi_ba.hh b/broker/bam/inc/com/centreon/broker/bam/kpi_ba.hh index 0e609812971..da3e15a8dc6 100644 --- a/broker/bam/inc/com/centreon/broker/bam/kpi_ba.hh +++ b/broker/bam/inc/com/centreon/broker/bam/kpi_ba.hh @@ -25,9 +25,8 @@ #include "com/centreon/broker/bam/kpi.hh" #include "com/centreon/broker/io/stream.hh" -namespace com::centreon::broker { +namespace com::centreon::broker::bam { -namespace bam { // Forward declaration. class ba; class computable; @@ -56,7 +55,10 @@ class kpi_ba : public kpi { const timestamp& event_start_time); public: - kpi_ba(uint32_t kpi_id, uint32_t ba_id, const std::string& ba_name); + kpi_ba(uint32_t kpi_id, + uint32_t ba_id, + const std::string& ba_name, + const std::shared_ptr& logger); ~kpi_ba() noexcept = default; kpi_ba(const kpi_ba&) = delete; kpi_ba& operator=(const kpi_ba&) = delete; @@ -72,12 +74,10 @@ class kpi_ba : public kpi { void visit(io::stream* visitor) override; bool ok_state() const override; bool in_downtime() const override; - virtual void update_from(computable* child, io::stream* visitor) override; + void update_from(computable* child, io::stream* visitor) override; std::string object_info() const override; void dump(std::ofstream& output) const override; }; -} // namespace bam - -} // namespace com::centreon::broker +} // namespace com::centreon::broker::bam #endif // !CCB_BAM_KPI_BA_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/kpi_boolexp.hh b/broker/bam/inc/com/centreon/broker/bam/kpi_boolexp.hh index 8e00a759e08..192a8b37c5f 100644 --- a/broker/bam/inc/com/centreon/broker/bam/kpi_boolexp.hh +++ b/broker/bam/inc/com/centreon/broker/bam/kpi_boolexp.hh @@ -24,9 +24,7 @@ #include "com/centreon/broker/io/stream.hh" #include "impact_values.hh" -namespace com::centreon::broker { - -namespace bam { +namespace com::centreon::broker::bam { // Forward declaration. class bool_expression; class computable; @@ -48,7 +46,10 @@ class kpi_boolexp : public kpi { void _open_new_event(io::stream* visitor, int impact, state state); public: - kpi_boolexp(uint32_t kpi_id, uint32_t ba_id, const std::string& bool_name); + kpi_boolexp(uint32_t kpi_id, + uint32_t ba_id, + const std::string& bool_name, + const std::shared_ptr& logger); ~kpi_boolexp() noexcept = default; kpi_boolexp(const kpi_boolexp&) = delete; kpi_boolexp& operator=(const kpi_boolexp&) = delete; @@ -65,8 +66,6 @@ class kpi_boolexp : public kpi { std::string object_info() const override; void dump(std::ofstream& output) const override; }; -} // namespace bam - -} // namespace com::centreon::broker +} // namespace com::centreon::broker::bam #endif // !CCB_BAM_KPI_BOOLEXP_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/kpi_service.hh b/broker/bam/inc/com/centreon/broker/bam/kpi_service.hh index 9943248a958..f57ad83d792 100644 --- a/broker/bam/inc/com/centreon/broker/bam/kpi_service.hh +++ b/broker/bam/inc/com/centreon/broker/bam/kpi_service.hh @@ -27,9 +27,7 @@ #include "com/centreon/broker/io/stream.hh" #include "com/centreon/broker/timestamp.hh" -namespace com::centreon::broker { - -namespace bam { +namespace com::centreon::broker::bam { /** * @class kpi_service kpi_service.hh "com/centreon/broker/bam/kpi_service.hh" * @brief Service as a KPI. @@ -61,7 +59,8 @@ class kpi_service : public service_listener, public kpi { uint32_t ba_id, uint32_t host_id, uint32_t service_id, - const std::string& host_serv); + const std::string& host_serv, + const std::shared_ptr& logger); ~kpi_service() noexcept = default; kpi_service(const kpi_service&) = delete; kpi_service& operator=(const kpi_service&) = delete; @@ -107,8 +106,6 @@ class kpi_service : public service_listener, public kpi { std::string object_info() const override; void dump(std::ofstream& output) const override; }; -} // namespace bam - -} // namespace com::centreon::broker +} // namespace com::centreon::broker::bam #endif // !CCB_BAM_KPI_SERVICE_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/monitoring_stream.hh b/broker/bam/inc/com/centreon/broker/bam/monitoring_stream.hh index e1aa396f9f8..3e2fda9a53a 100644 --- a/broker/bam/inc/com/centreon/broker/bam/monitoring_stream.hh +++ b/broker/bam/inc/com/centreon/broker/bam/monitoring_stream.hh @@ -20,6 +20,7 @@ #define CCB_BAM_MONITORING_STREAM_HH #include + #include "com/centreon/broker/bam/configuration/applier/state.hh" #include "com/centreon/broker/io/stream.hh" #include "com/centreon/broker/sql/database_config.hh" @@ -67,6 +68,10 @@ namespace bam { */ class monitoring_stream : public io::stream { const std::string _ext_cmd_file; + + /* Logger */ + std::shared_ptr _logger; + configuration::applier::state _applier; /* This mutex is to protect writes to the external command named pipe. */ mutable std::mutex _ext_cmd_file_m; @@ -109,7 +114,8 @@ class monitoring_stream : public io::stream { monitoring_stream(std::string const& ext_cmd_file, database_config const& db_cfg, database_config const& storage_db_cfg, - std::shared_ptr cache); + std::shared_ptr cache, + const std::shared_ptr& logger); ~monitoring_stream(); monitoring_stream(const monitoring_stream&) = delete; monitoring_stream& operator=(const monitoring_stream&) = delete; @@ -121,7 +127,6 @@ class monitoring_stream : public io::stream { int write(std::shared_ptr const& d) override; }; } // namespace bam - -} +} // namespace com::centreon::broker #endif // !CCB_BAM_MONITORING_STREAM_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/reporting_stream.hh b/broker/bam/inc/com/centreon/broker/bam/reporting_stream.hh index 95fb6d38f09..54046f48c61 100644 --- a/broker/bam/inc/com/centreon/broker/bam/reporting_stream.hh +++ b/broker/bam/inc/com/centreon/broker/bam/reporting_stream.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2014-2015, 2020-2021 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2014-2015, 2020-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_BAM_REPORTING_STREAM_HH #define CCB_BAM_REPORTING_STREAM_HH @@ -85,8 +85,12 @@ class reporting_stream : public io::stream { id_start_to_event_id _ba_event_cache; id_start_to_event_id _kpi_event_cache; + /* Logger */ + std::shared_ptr _logger; + public: - reporting_stream(database_config const& db_cfg); + reporting_stream(database_config const& db_cfg, + const std::shared_ptr& logger); ~reporting_stream(); reporting_stream(const reporting_stream&); reporting_stream& operator=(const reporting_stream&); @@ -137,7 +141,6 @@ class reporting_stream : public io::stream { void _compute_event_durations(const BaEvent& ev, io::stream* visitor); }; } // namespace bam - -} +} // namespace com::centreon::broker #endif // !CCB_BAM_REPORTING_STREAM_HH diff --git a/broker/bam/inc/com/centreon/broker/bam/service_book.hh b/broker/bam/inc/com/centreon/broker/bam/service_book.hh index 4c8c90e1cfc..5e9b7dfecb3 100644 --- a/broker/bam/inc/com/centreon/broker/bam/service_book.hh +++ b/broker/bam/inc/com/centreon/broker/bam/service_book.hh @@ -52,9 +52,11 @@ class service_book { service_state_listeners, absl::Hash>> _book; + std::shared_ptr _logger; public: - service_book() = default; + service_book(const std::shared_ptr& logger) + : _logger{logger} {} ~service_book() noexcept = default; service_book(const service_book&) = delete; service_book& operator=(const service_book&) = delete; diff --git a/broker/bam/inc/com/centreon/broker/bam/timeperiod_map.hh b/broker/bam/inc/com/centreon/broker/bam/timeperiod_map.hh index 5219c74aeea..1959cd4f3d0 100644 --- a/broker/bam/inc/com/centreon/broker/bam/timeperiod_map.hh +++ b/broker/bam/inc/com/centreon/broker/bam/timeperiod_map.hh @@ -1,29 +1,27 @@ -/* -** Copyright 2014 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2014, 2020-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_BAM_TIMEPERIOD_MAP_HH #define CCB_BAM_TIMEPERIOD_MAP_HH #include "com/centreon/broker/time/timeperiod.hh" -namespace com::centreon::broker { - -namespace bam { +namespace com::centreon::broker::bam { /** * @class timeperiod_map timeperiod_map.hh * "com/centreon/broker/bam/timeperiod_map.hh" @@ -50,8 +48,6 @@ class timeperiod_map { timeperiod_relation_map; timeperiod_relation_map _timeperiod_relations; }; -} // namespace bam - -} +} // namespace com::centreon::broker::bam #endif // !CCB_BAM_TIMEPERIOD_MAP_HH diff --git a/broker/bam/src/availability_builder.cc b/broker/bam/src/availability_builder.cc index 64e41c92534..99f4786d115 100644 --- a/broker/bam/src/availability_builder.cc +++ b/broker/bam/src/availability_builder.cc @@ -1,25 +1,23 @@ /** -* Copyright 2014-2015, 2021 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2014-2015, 2021-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/bam/availability_builder.hh" -#include "com/centreon/broker/log_v2.hh" - using namespace com::centreon::broker; using namespace com::centreon::broker::bam; @@ -59,13 +57,16 @@ availability_builder::~availability_builder() {} * @param[in] end The end of the event. * @param[in] was_in_downtime Was the event in downtime? * @param[in] tp The timeperiod of the event. + * @param[in] logger The logger to use. */ -void availability_builder::add_event(short status, - time_t start, - time_t end, - bool was_in_downtime, - time::timeperiod::ptr const& tp) { - log_v2::bam()->trace( +void availability_builder::add_event( + short status, + time_t start, + time_t end, + bool was_in_downtime, + time::timeperiod::ptr const& tp, + const std::shared_ptr& logger) { + logger->trace( "availability_builder::add_event (status: {}, start: {}, end: {}, was in " "downtime: {}", status, start, end, was_in_downtime); diff --git a/broker/bam/src/availability_thread.cc b/broker/bam/src/availability_thread.cc index f88336b49e6..4ce181f5a47 100644 --- a/broker/bam/src/availability_thread.cc +++ b/broker/bam/src/availability_thread.cc @@ -1,24 +1,23 @@ /** -* Copyright 2014, 2021 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2014, 2021-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/bam/availability_thread.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/time.hh" #include "com/centreon/broker/sql/mysql_error.hh" #include "com/centreon/exceptions/msg_fmt.hh" @@ -32,15 +31,19 @@ using namespace com::centreon::broker::bam; * * @param[in] db_cfg Database configuration. * @param[in] shared_map A timeperiod map shared with the reporting. + * @param[in] logger The logger to use in availability_thread. */ -availability_thread::availability_thread(database_config const& db_cfg, - timeperiod_map& shared_map) +availability_thread::availability_thread( + database_config const& db_cfg, + timeperiod_map& shared_map, + const std::shared_ptr& logger) : _started_flag{false}, _db_cfg(db_cfg), _shared_tps(shared_map), _mutex{}, _should_exit(false), - _should_rebuild_all(false) {} + _should_rebuild_all(false), + _logger{logger} {} /** * Destructor. @@ -65,30 +68,30 @@ void availability_thread::run() { // Calculate the duration until next midnight. time_t midnight = _compute_next_midnight(); unsigned long wait_for = std::difftime(midnight, ::time(nullptr)); - log_v2::bam()->debug( - "BAM-BI: availability thread sleeping for {} seconds.", wait_for); + _logger->debug("BAM-BI: availability thread sleeping for {} seconds.", + wait_for); _wait.wait_for(lock, std::chrono::seconds(wait_for)); - log_v2::bam()->debug("BAM-BI: availability thread waking up "); + _logger->debug("BAM-BI: availability thread waking up "); // Termination asked. if (_should_exit) break; - log_v2::bam()->debug("BAM-BI: opening database"); + _logger->debug("BAM-BI: opening database"); // Open the database. _open_database(); - log_v2::bam()->debug("BAM-BI: build availabilities"); + _logger->debug("BAM-BI: build availabilities"); _build_availabilities(misc::start_of_day(::time(nullptr))); _should_rebuild_all = false; _bas_to_rebuild.clear(); // Close the database. _close_database(); - log_v2::bam()->debug("BAM-BI: database closed"); + _logger->debug("BAM-BI: database closed"); } catch (const std::exception& e) { // Something bad happened. Wait for the next loop. - log_v2::bam()->error("BAM-BI: Something went wrong: {}", e.what()); + _logger->error("BAM-BI: Something went wrong: {}", e.what()); _close_database(); } } @@ -152,7 +155,7 @@ void availability_thread::rebuild_availabilities( * Delete all the availabilities. */ void availability_thread::_delete_all_availabilities() { - log_v2::bam()->debug("BAM-BI: availability thread deleting availabilities"); + _logger->debug("BAM-BI: availability thread deleting availabilities"); // Prepare the query. std::string query_str(fmt::format( @@ -201,7 +204,7 @@ void availability_thread::_build_availabilities(time_t midnight) { _delete_all_availabilities(); } catch (const std::exception& e) { - log_v2::bam()->error( + _logger->error( "BAM-BI: availability thread could not select the BA durations from " "the reporting database: {}", e.what()); @@ -220,7 +223,7 @@ void availability_thread::_build_availabilities(time_t midnight) { _mysql->run_query_and_get_result(query_str, std::move(promise)); database::mysql_result res(future.get()); if (!_mysql->fetch_row(res)) { - log_v2::bam()->error("no availability in table"); + _logger->error("no availability in table"); throw msg_fmt("no availability in table"); } first_day = res.value_as_i32(0); @@ -231,12 +234,12 @@ void availability_thread::_build_availabilities(time_t midnight) { "BAM-BI: availability thread could not select the BA availabilities " "from the reporting database: {}", e.what())); - log_v2::bam()->error(msg); + _logger->error(msg); throw msg_fmt(msg); } } - log_v2::bam()->debug( + _logger->debug( "BAM-BI: availability thread writing availabilities from: {} to {}", first_day, last_day); @@ -261,7 +264,7 @@ void availability_thread::_build_availabilities(time_t midnight) { void availability_thread::_build_daily_availabilities(int thread_id, time_t day_start, time_t day_end) { - log_v2::bam()->info( + _logger->info( "BAM-BI: availability thread writing daily availability for day : {}-{}", day_start, day_end); @@ -277,7 +280,7 @@ void availability_thread::_build_daily_availabilities(int thread_id, _should_rebuild_all ? fmt::format("AND b.ba_id IN({})", _bas_to_rebuild) : "")); - log_v2::bam()->debug("Query: {}", query); + _logger->debug("Query: {}", query); std::promise promise; std::future future = promise.get_future(); _mysql->run_query_and_get_result(query, std::move(promise), thread_id); @@ -294,16 +297,15 @@ void availability_thread::_build_daily_availabilities(int thread_id, time::timeperiod::ptr tp = _shared_tps.get_timeperiod(timeperiod_id); // No timeperiod found, skip. if (!tp) { - log_v2::bam()->debug("no timeperiod found with id {}", timeperiod_id); + _logger->debug("no timeperiod found with id {}", timeperiod_id); continue; } // Find the builder. auto found = builders.find({ba_id, timeperiod_id}); // No builders found, create one. if (found == builders.end()) { - log_v2::bam()->debug( - "adding new builder for ba id {} and timeperiod id {}", ba_id, - timeperiod_id); + _logger->debug("adding new builder for ba id {} and timeperiod id {}", + ba_id, timeperiod_id); found = builders .insert(std::make_pair( std::make_pair(ba_id, timeperiod_id), @@ -316,7 +318,7 @@ void availability_thread::_build_daily_availabilities(int thread_id, res.value_as_i32(2), // Start time res.value_as_i32(3), // End time res.value_as_bool(9), // Was in downtime - tp); + tp, _logger); // Add the timeperiod is default flag. found->second->set_timeperiod_is_default(res.value_as_bool(7)); } @@ -325,8 +327,7 @@ void availability_thread::_build_daily_availabilities(int thread_id, e.what()); } - log_v2::bam()->debug("{} builders of availabilities created", - builders.size()); + _logger->debug("{} builders of availabilities created", builders.size()); // Build the availabilities tied to event not finished. query = fmt::format( @@ -336,7 +337,7 @@ void availability_thread::_build_daily_availabilities(int thread_id, day_end, _should_rebuild_all ? fmt::format("AND ba_id IN ({})", _bas_to_rebuild) : ""); - log_v2::bam()->debug("Query: {}", query); + _logger->debug("Query: {}", query); std::promise promise_ba; std::future future_ba = promise_ba.get_future(); @@ -369,20 +370,18 @@ void availability_thread::_build_daily_availabilities(int thread_id, res.value_as_i32(2), // Start time res.value_as_i32(3), // End time res.value_as_bool(5), // Was in downtime - it->first); + it->first, _logger); // Add the timeperiod is default flag. found->second->set_timeperiod_is_default(it->second); } - log_v2::bam()->debug("{} builder(s) were missing for ba {}", count, - ba_id); + _logger->debug("{} builder(s) were missing for ba {}", count, ba_id); } } catch (const std::exception& e) { throw msg_fmt("BAM-BI: availability thread could not build the data: {}", e.what()); } - log_v2::bam()->debug("{} builder(s) to write availabilities", - builders.size()); + _logger->debug("{} builder(s) to write availabilities", builders.size()); // For each builder, write the availabilities. for (auto it = builders.begin(), end = builders.end(); it != end; ++it) _write_availability(thread_id, *it->second, it->first.first, day_start, @@ -405,7 +404,7 @@ void availability_thread::_write_availability( uint32_t ba_id, time_t day_start, uint32_t timeperiod_id) { - log_v2::bam()->debug( + _logger->debug( "BAM-BI: availability thread writing availability for BA {} at day {} " "(timeperiod {})", ba_id, day_start, timeperiod_id); @@ -424,7 +423,7 @@ void availability_thread::_write_availability( builder.get_unavailable_opened(), builder.get_degraded_opened(), builder.get_unknown_opened(), builder.get_downtime_opened())); - log_v2::bam()->debug("Query: {}", query_str); + _logger->debug("Query: {}", query_str); _mysql->run_query(query_str, database::mysql_error::insert_availability, thread_id); } diff --git a/broker/bam/src/ba.cc b/broker/bam/src/ba.cc index 8cc10ce7303..db9b53cc5d9 100644 --- a/broker/bam/src/ba.cc +++ b/broker/bam/src/ba.cc @@ -26,7 +26,6 @@ #include "com/centreon/broker/bam/impact_values.hh" #include "com/centreon/broker/bam/kpi.hh" #include "com/centreon/broker/config/applier/state.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/neb/downtime.hh" #include "com/centreon/broker/neb/service_status.hh" @@ -48,19 +47,23 @@ static bool time_is_undefined(uint64_t t) { /** * Constructor. * + * @param[in] id the id of this ba. * @param[in] host_id the id of the associated host. * @param[in] service_id the id of the associated service. - * @param[in] id the id of this ba. + * @param[in] source Source, i.e. the type of service. * @param[in] generate_virtual_status Whether or not the BA object * should generate statuses of * virtual hosts and services. + * @param[in] logger The logger used in this ba. */ ba::ba(uint32_t id, uint32_t host_id, uint32_t service_id, configuration::ba::state_source source, - bool generate_virtual_status) - : _id(id), + bool generate_virtual_status, + const std::shared_ptr& logger) + : computable(logger), + _id(id), _state_source(source), _host_id(host_id), _service_id(service_id), @@ -188,7 +191,7 @@ void ba::remove_impact(std::shared_ptr const& impact) { void ba::set_initial_event(const pb_ba_event& event) { const BaEvent& data = event.obj(); SPDLOG_LOGGER_TRACE( - log_v2::bam(), + _logger, "BAM: ba initial event set (ba_id:{}, start_time:{}, end_time:{}, " "in_downtime:{}, status:{})", data.ba_id(), data.start_time(), data.end_time(), data.in_downtime(), @@ -197,13 +200,12 @@ void ba::set_initial_event(const pb_ba_event& event) { if (!_event) { _event = std::make_shared(event); _in_downtime = data.in_downtime(); - SPDLOG_LOGGER_TRACE(log_v2::bam(), "ba initial event downtime: {}", - _in_downtime); + SPDLOG_LOGGER_TRACE(_logger, "ba initial event downtime: {}", _in_downtime); _last_kpi_update = data.start_time(); _initial_events.push_back(_event); } else { SPDLOG_LOGGER_ERROR( - log_v2::bam(), + _logger, "BAM: impossible to set ba initial event (ba_id:{}, start_time:{}, " "end_time:{}, in_downtime:{}, status:{}): event already defined", data.ba_id(), data.start_time(), data.end_time(), data.in_downtime(), @@ -254,7 +256,7 @@ void ba::visit(io::stream* visitor) { com::centreon::broker::bam::state hard_state(get_state_hard()); bool state_changed(false); if (!_event) { - SPDLOG_LOGGER_TRACE(log_v2::bam(), + SPDLOG_LOGGER_TRACE(_logger, "BAM: ba::visit no event => creation of one"); if (_last_kpi_update.is_null()) _last_kpi_update = time(nullptr); @@ -265,7 +267,7 @@ void ba::visit(io::stream* visitor) { com::centreon::broker::State(hard_state) != _event->obj().status()) { SPDLOG_LOGGER_TRACE( - log_v2::bam(), + _logger, "BAM: ba current event needs update? downtime?: {}, state?: {} ; " "dt:{}, state:{} ", _in_downtime != _event->obj().in_downtime(), @@ -300,11 +302,10 @@ void ba::visit(io::stream* visitor) { */ void ba::service_update(const std::shared_ptr& dt, io::stream* visitor) { - (void)visitor; if (dt->host_id == _host_id && dt->service_id == _service_id) { // Log message. SPDLOG_LOGGER_DEBUG( - log_v2::bam(), + _logger, "BAM: BA {} '{}' is getting notified of a downtime on its service ({}, " "{})", _id, _name, _host_id, _service_id); @@ -312,7 +313,7 @@ void ba::service_update(const std::shared_ptr& dt, // Check if there was a change. bool in_downtime(dt->was_started && dt->actual_end_time.is_null()); if (_in_downtime != in_downtime) { - SPDLOG_LOGGER_TRACE(log_v2::bam(), "ba: service_update downtime: {}", + SPDLOG_LOGGER_TRACE(_logger, "ba: service_update downtime: {}", _in_downtime); _in_downtime = in_downtime; @@ -323,7 +324,7 @@ void ba::service_update(const std::shared_ptr& dt, } } else SPDLOG_LOGGER_DEBUG( - log_v2::bam(), + _logger, "BAM: BA {} '{}' has got an invalid downtime event. This should never " "happen. Check your database: got (host {}, service {}) expected ({}, " "{})", @@ -340,14 +341,13 @@ void ba::service_update(const std::shared_ptr& dt, */ void ba::service_update(const std::shared_ptr& dt, io::stream* visitor) { - (void)visitor; auto& downtime = dt->obj(); assert(downtime.host_id() == _host_id && downtime.service_id() == _service_id); // Log message. SPDLOG_LOGGER_DEBUG( - log_v2::bam(), + _logger, "BAM: BA {} '{}' is getting notified of a downtime (pb) on its service " "({}, {})", _id, _name, _host_id, _service_id); @@ -356,7 +356,7 @@ void ba::service_update(const std::shared_ptr& dt, bool in_downtime(downtime.started() && time_is_undefined(downtime.actual_end_time())); if (_in_downtime != in_downtime) { - SPDLOG_LOGGER_TRACE(log_v2::bam(), "ba: service_update downtime: {}", + SPDLOG_LOGGER_TRACE(_logger, "ba: service_update downtime: {}", _in_downtime); _in_downtime = in_downtime; @@ -410,9 +410,8 @@ void ba::set_inherited_downtime(const inherited_downtime& dwn) { */ void ba::_open_new_event(io::stream* visitor, com::centreon::broker::bam::state service_hard_state) { - SPDLOG_LOGGER_TRACE(log_v2::bam(), - "new pb_ba_event on ba {} with downtime = {}", _id, - _in_downtime); + SPDLOG_LOGGER_TRACE(_logger, "new pb_ba_event on ba {} with downtime = {}", + _id, _in_downtime); _event = std::make_shared(); BaEvent& data = _event->mut_obj(); data.set_ba_id(_id); @@ -449,8 +448,7 @@ void ba::_commit_initial_events(io::stream* visitor) { void ba::_compute_inherited_downtime(io::stream* visitor) { // kpi downtime heritance deactived. Do nothing. if (_dt_behaviour != configuration::ba::dt_inherit) { - SPDLOG_LOGGER_TRACE(log_v2::bam(), "ba: BA {} doesn't inherite downtimes", - _id); + SPDLOG_LOGGER_TRACE(_logger, "ba: BA {} doesn't inherite downtimes", _id); return; } @@ -462,7 +460,7 @@ void ba::_compute_inherited_downtime(io::stream* visitor) { it != end; ++it) { if (!it->first->ok_state() && !it->first->in_downtime()) { SPDLOG_LOGGER_TRACE( - log_v2::bam(), + _logger, "ba: every kpi in downtime ? no, kpi {} is not ok and not in " "downtime", it->first->get_id()); @@ -478,7 +476,7 @@ void ba::_compute_inherited_downtime(io::stream* visitor) { _inherited_downtime = std::make_unique(); _inherited_downtime->mut_obj().set_ba_id(_id); _inherited_downtime->mut_obj().set_in_downtime(true); - SPDLOG_LOGGER_TRACE(log_v2::bam(), + SPDLOG_LOGGER_TRACE(_logger, "ba: inherited downtime computation downtime true"); _in_downtime = true; @@ -490,7 +488,7 @@ void ba::_compute_inherited_downtime(io::stream* visitor) { // Remove the downtime. else if ((s_ok || !every_kpi_in_downtime) && _inherited_downtime) { _inherited_downtime->mut_obj().set_in_downtime(false); - SPDLOG_LOGGER_TRACE(log_v2::bam(), + SPDLOG_LOGGER_TRACE(_logger, "ba: inherited downtime computation downtime false"); _in_downtime = false; @@ -499,8 +497,7 @@ void ba::_compute_inherited_downtime(io::stream* visitor) { _inherited_downtime.reset(); } else SPDLOG_LOGGER_TRACE( - log_v2::bam(), - "ba: inherited downtime computation downtime not changed ({})", + _logger, "ba: inherited downtime computation downtime not changed ({})", _in_downtime); } @@ -592,8 +589,7 @@ void ba::set_level_warning(double level) { * @param visitor The visitor to handle events. */ void ba::update_from(computable* child, io::stream* visitor) { - auto logger = log_v2::bam(); - logger->trace("ba::update_from (BA {})", _id); + _logger->trace("ba::update_from (BA {})", _id); // Get impact. impact_values new_hard_impact; impact_values new_soft_impact; @@ -605,7 +601,7 @@ void ba::update_from(computable* child, io::stream* visitor) { // Logging. SPDLOG_LOGGER_DEBUG( - logger, + _logger, "BAM: BA {}, '{}' is getting notified of child update (KPI {}, impact " "{}, last state change {}, downtime {})", _id, _name, kpi_child->get_id(), new_hard_impact.get_nominal(), @@ -616,11 +612,11 @@ void ba::update_from(computable* child, io::stream* visitor) { _last_kpi_update = std::max(_last_kpi_update, last_state_change); // Apply new data. - SPDLOG_LOGGER_TRACE(log_v2::bam(), "BAM: BA {} updated from KPI {}", _id, + SPDLOG_LOGGER_TRACE(_logger, "BAM: BA {} updated from KPI {}", _id, kpi_child->get_id()); bool changed = _apply_changes(kpi_child, new_hard_impact, new_soft_impact, kpi_in_downtime); - SPDLOG_LOGGER_TRACE(log_v2::bam(), "BA {} has changed: {}", _id, changed); + SPDLOG_LOGGER_TRACE(_logger, "BA {} has changed: {}", _id, changed); // Check for inherited downtimes. _compute_inherited_downtime(visitor); @@ -655,8 +651,8 @@ void ba::dump(const std::string& filename) const { dump(output); output << "}\n"; } else - log_v2::bam()->error("Unable to open the file '{}' to write BA {} info", - filename, _id); + _logger->error("Unable to open the file '{}' to write BA {} info", filename, + _id); } /** diff --git a/broker/bam/src/ba_best.cc b/broker/bam/src/ba_best.cc index 257f3a56d62..77328a328b4 100644 --- a/broker/bam/src/ba_best.cc +++ b/broker/bam/src/ba_best.cc @@ -26,7 +26,6 @@ #include "com/centreon/broker/bam/impact_values.hh" #include "com/centreon/broker/bam/kpi.hh" #include "com/centreon/broker/config/applier/state.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/neb/downtime.hh" #include "com/centreon/broker/neb/service_status.hh" @@ -42,16 +41,19 @@ using namespace com::centreon::broker::bam; * @param[in] generate_virtual_status Whether or not the BA object * should generate statuses of * virtual hosts and services. + * @param[in] logger The logger to use in this BA. */ ba_best::ba_best(uint32_t id, uint32_t host_id, uint32_t service_id, - bool generate_virtual_status) + bool generate_virtual_status, + const std::shared_ptr& logger) : ba(id, host_id, service_id, configuration::ba::state_source_best, - generate_virtual_status) {} + generate_virtual_status, + logger) {} /** * Get BA hard state. @@ -220,7 +222,7 @@ std::shared_ptr ba_best::_generate_ba_status( status.set_output(get_output() + "|" + perfdata); SPDLOG_LOGGER_DEBUG( - log_v2::bam(), + _logger, "BAM: generating status of best BA {} '{}' (state {}, in downtime {})", get_id(), _name, status.state(), status.in_downtime()); return ret; diff --git a/broker/bam/src/ba_impact.cc b/broker/bam/src/ba_impact.cc index 213b7b73f56..4219fe4dde1 100644 --- a/broker/bam/src/ba_impact.cc +++ b/broker/bam/src/ba_impact.cc @@ -26,7 +26,6 @@ #include "com/centreon/broker/bam/impact_values.hh" #include "com/centreon/broker/bam/kpi.hh" #include "com/centreon/broker/config/applier/state.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/neb/downtime.hh" #include "com/centreon/broker/neb/service_status.hh" @@ -38,22 +37,25 @@ constexpr double eps = 0.000001; /** * Constructor. * + * @param[in] id the id of this ba. * @param[in] host_id the id of the associated host. * @param[in] service_id the id of the associated service. - * @param[in] id the id of this ba. * @param[in] generate_virtual_status Whether or not the BA object * should generate statuses of * virtual hosts and services. + * @param[in] logger The logger to use in this BA. */ ba_impact::ba_impact(uint32_t id, uint32_t host_id, uint32_t service_id, - bool generate_virtual_status) + bool generate_virtual_status, + const std::shared_ptr& logger) : ba(id, host_id, service_id, configuration::ba::state_source_impact, - generate_virtual_status) {} + generate_virtual_status, + logger) {} /** * Get BA hard state. @@ -288,7 +290,7 @@ std::shared_ptr ba_impact::_generate_ba_status( status.set_output(get_output() + "|" + perfdata); SPDLOG_LOGGER_DEBUG( - log_v2::bam(), + _logger, "BAM: generating status of impact BA {} '{}' (state {}, in downtime {}, " "level {})", get_id(), _name, status.state(), status.in_downtime(), diff --git a/broker/bam/src/ba_ratio_number.cc b/broker/bam/src/ba_ratio_number.cc index d3c08c01e70..974aa376e4d 100644 --- a/broker/bam/src/ba_ratio_number.cc +++ b/broker/bam/src/ba_ratio_number.cc @@ -26,7 +26,6 @@ #include "com/centreon/broker/bam/impact_values.hh" #include "com/centreon/broker/bam/kpi.hh" #include "com/centreon/broker/config/applier/state.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/neb/downtime.hh" #include "com/centreon/broker/neb/service_status.hh" @@ -38,22 +37,25 @@ static constexpr double eps = 0.000001; /** * Constructor. * + * @param[in] id the id of this ba. * @param[in] host_id the id of the associated host. * @param[in] service_id the id of the associated service. - * @param[in] id the id of this ba. * @param[in] generate_virtual_status Whether or not the BA object * should generate statuses of * virtual hosts and services. + * @param[in] logger The logger to use in this BA. */ ba_ratio_number::ba_ratio_number(uint32_t id, uint32_t host_id, uint32_t service_id, - bool generate_virtual_status) + bool generate_virtual_status, + const std::shared_ptr& logger) : ba(id, host_id, service_id, configuration::ba::state_source_ratio_number, - generate_virtual_status) { + generate_virtual_status, + logger) { _level_hard = _level_soft = 0; } @@ -208,7 +210,7 @@ std::shared_ptr ba_ratio_number::_generate_ba_status( else status.set_output(get_output() + "|" + perfdata); - SPDLOG_LOGGER_DEBUG(log_v2::bam(), + SPDLOG_LOGGER_DEBUG(_logger, "BAM: generating status of ratio number BA {} '{}' " "(state {}, in downtime {}, level {})", get_id(), _name, status.state(), status.in_downtime(), diff --git a/broker/bam/src/ba_ratio_percent.cc b/broker/bam/src/ba_ratio_percent.cc index cf3777564e9..99a600797df 100644 --- a/broker/bam/src/ba_ratio_percent.cc +++ b/broker/bam/src/ba_ratio_percent.cc @@ -26,7 +26,6 @@ #include "com/centreon/broker/bam/impact_values.hh" #include "com/centreon/broker/bam/kpi.hh" #include "com/centreon/broker/config/applier/state.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/neb/downtime.hh" #include "com/centreon/broker/neb/service_status.hh" @@ -38,22 +37,26 @@ static constexpr double eps = 0.000001; /** * Constructor. * + * @param[in] id the id of this ba. * @param[in] host_id the id of the associated host. * @param[in] service_id the id of the associated service. - * @param[in] id the id of this ba. * @param[in] generate_virtual_status Whether or not the BA object * should generate statuses of * virtual hosts and services. + * @param[in] logger The logger to use in this BA. */ -ba_ratio_percent::ba_ratio_percent(uint32_t id, - uint32_t host_id, - uint32_t service_id, - bool generate_virtual_status) +ba_ratio_percent::ba_ratio_percent( + uint32_t id, + uint32_t host_id, + uint32_t service_id, + bool generate_virtual_status, + const std::shared_ptr& logger) : ba(id, host_id, service_id, configuration::ba::state_source_ratio_percent, - generate_virtual_status) { + generate_virtual_status, + logger) { _level_hard = _level_soft = 0; } @@ -211,7 +214,7 @@ std::shared_ptr ba_ratio_percent::_generate_ba_status( else status.set_output(get_output() + "|" + perfdata); - SPDLOG_LOGGER_DEBUG(log_v2::bam(), + SPDLOG_LOGGER_DEBUG(_logger, "BAM: generating status of ratio percent BA {} '{}' " "(state {}, in downtime {}, level {})", get_id(), _name, status.state(), status.in_downtime(), diff --git a/broker/bam/src/ba_worst.cc b/broker/bam/src/ba_worst.cc index f58b4e3d0d5..c04eba63767 100644 --- a/broker/bam/src/ba_worst.cc +++ b/broker/bam/src/ba_worst.cc @@ -26,7 +26,6 @@ #include "com/centreon/broker/bam/impact_values.hh" #include "com/centreon/broker/bam/kpi.hh" #include "com/centreon/broker/config/applier/state.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/neb/downtime.hh" #include "com/centreon/broker/neb/service_status.hh" @@ -36,22 +35,25 @@ using namespace com::centreon::broker::bam; /** * Constructor. * + * @param[in] id the id of this ba. * @param[in] host_id the id of the associated host. * @param[in] service_id the id of the associated service. - * @param[in] id the id of this ba. * @param[in] generate_virtual_status Whether or not the BA object * should generate statuses of * virtual hosts and services. + * @param[in] logger The logger to use in this BA. */ ba_worst::ba_worst(uint32_t id, uint32_t host_id, uint32_t service_id, - bool generate_virtual_status) + bool generate_virtual_status, + const std::shared_ptr& logger) : ba(id, host_id, service_id, configuration::ba::state_source_worst, - generate_virtual_status) {} + generate_virtual_status, + logger) {} /** * Get BA hard state. @@ -240,7 +242,7 @@ std::shared_ptr ba_worst::_generate_ba_status( status.set_output(get_output() + "|" + perfdata); SPDLOG_LOGGER_DEBUG( - log_v2::bam(), + _logger, "BAM: generating status of worst BA {} '{}' (state {}, in downtime {})", get_id(), _name, status.state(), status.in_downtime()); return ret; diff --git a/broker/bam/src/bool_and.cc b/broker/bam/src/bool_and.cc index b4bfd08c393..7aee37529cb 100644 --- a/broker/bam/src/bool_and.cc +++ b/broker/bam/src/bool_and.cc @@ -1,5 +1,5 @@ /** - * Copyright 2014, 2023 Centreon + * Copyright 2014, 2023-2024 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,6 @@ */ #include "com/centreon/broker/bam/bool_and.hh" -#include "com/centreon/broker/log_v2.hh" using namespace com::centreon::broker::bam; @@ -32,14 +31,14 @@ constexpr double eps = 0.000001; * good value. */ void bool_and::_update_state() { - log_v2::bam()->trace("bool_and::update_state..."); + _logger->trace("bool_and::update_state..."); if (_left && _left->state_known() && !_left->boolean_value()) { - log_v2::bam()->trace("bam: bool and left changed to true"); + _logger->trace("bam: bool and left changed to true"); _left_hard = false; _boolean_value = false; _state_known = true; } else if (_right && _right->state_known() && !_right->boolean_value()) { - log_v2::bam()->trace("bam: bool and right changed to true"); + _logger->trace("bam: bool and right changed to true"); _right_hard = false; _boolean_value = false; _state_known = true; @@ -51,9 +50,8 @@ void bool_and::_update_state() { _boolean_value = left && right; } else _boolean_value = false; - log_v2::bam()->trace( - "bam: bool and generic rule applied: value: {} - known : {}", - _boolean_value, _state_known); + _logger->trace("bam: bool and generic rule applied: value: {} - known : {}", + _boolean_value, _state_known); } } diff --git a/broker/bam/src/bool_binary_operator.cc b/broker/bam/src/bool_binary_operator.cc index afda0850a46..1d1766ad91b 100644 --- a/broker/bam/src/bool_binary_operator.cc +++ b/broker/bam/src/bool_binary_operator.cc @@ -17,7 +17,6 @@ */ #include "com/centreon/broker/bam/bool_binary_operator.hh" -#include "com/centreon/broker/log_v2.hh" using namespace com::centreon::broker::bam; @@ -34,14 +33,13 @@ static constexpr double eps = 0.000001; void bool_binary_operator::_update_state() { if (_left && _right) { _state_known = _left->state_known() && _right->state_known(); - log_v2::bam()->trace( - "{}::_update_state: bool binary operator: state updated? {}", - typeid(*this).name(), _state_known ? "yes" : "no"); + _logger->trace("{}::_update_state: bool binary operator: state updated? {}", + typeid(*this).name(), _state_known ? "yes" : "no"); if (_state_known) { _left_hard = _left->value_hard(); _right_hard = _right->value_hard(); _in_downtime = _left->in_downtime() || _right->in_downtime(); - log_v2::bam()->trace( + _logger->trace( "{}::_update_state: bool binary operator: new left value: {} - new " "right value: {} - downtime: {}", typeid(*this).name(), _left_hard, _right_hard, @@ -49,7 +47,7 @@ void bool_binary_operator::_update_state() { } } else { _state_known = false; - log_v2::bam()->trace( + _logger->trace( "{}::_update_state: bool binary operator: some children are empty", typeid(*this).name()); } @@ -61,7 +59,7 @@ void bool_binary_operator::_update_state() { * @param[in] left Left member of the boolean operator. */ void bool_binary_operator::set_left(std::shared_ptr const& left) { - log_v2::bam()->trace("{}::set_left", typeid(*this).name()); + _logger->trace("{}::set_left", typeid(*this).name()); _left = left; _update_state(); } @@ -72,7 +70,7 @@ void bool_binary_operator::set_left(std::shared_ptr const& left) { * @param[in] right Right member of the boolean operator. */ void bool_binary_operator::set_right(std::shared_ptr const& right) { - log_v2::bam()->trace("{}::set_right", typeid(*this).name()); + _logger->trace("{}::set_right", typeid(*this).name()); _right = right; _update_state(); } @@ -102,15 +100,14 @@ bool bool_binary_operator::in_downtime() const { * @param visitor The visitor to handle events. */ void bool_binary_operator::update_from(computable* child, io::stream* visitor) { - auto logger = log_v2::bam(); - logger->trace("bool_binary_operator::update_from"); + _logger->trace("bool_binary_operator::update_from"); // Check operation members values. bool changed = false; if (child) { if (child == _left.get()) { if (_left->state_known() != _state_known || std::abs(_left_hard - _left->value_hard()) > ::eps) { - logger->trace( + _logger->trace( "{}::update_from: on left: old state known: {} - new state " "known: {} - old value: {} - new value: {}", typeid(*this).name(), _state_known, _left->state_known(), @@ -118,14 +115,14 @@ void bool_binary_operator::update_from(computable* child, io::stream* visitor) { _update_state(); changed = true; } else - logger->trace( + _logger->trace( "{}::update_from: bool_binary_operator: update_from: no " "on left - state known: {} - value: {}", typeid(*this).name(), _state_known, _left_hard); } else if (child == _right.get()) { if (_right->state_known() != _state_known || std::abs(_right_hard - _right->value_hard()) > ::eps) { - logger->trace( + _logger->trace( "{}::update_from on right: old state known: {} - new state " "known: {} - old value: {} - new value: {}", typeid(*this).name(), _state_known, _right->state_known(), @@ -133,7 +130,7 @@ void bool_binary_operator::update_from(computable* child, io::stream* visitor) { _update_state(); changed = true; } else - logger->trace( + _logger->trace( "{}::update_from: bool_binary_operator: update_from: no " "on right", typeid(*this).name()); diff --git a/broker/bam/src/bool_call.cc b/broker/bam/src/bool_call.cc index d9ef598ede9..48f3fb6a48d 100644 --- a/broker/bam/src/bool_call.cc +++ b/broker/bam/src/bool_call.cc @@ -17,7 +17,7 @@ */ #include "com/centreon/broker/bam/bool_call.hh" -#include "com/centreon/broker/log_v2.hh" +#include "com/centreon/broker/bam/bool_value.hh" using namespace com::centreon::broker::bam; @@ -25,8 +25,11 @@ using namespace com::centreon::broker::bam; * Constructor. * * @param[in] name The name of the external expression. + * @param[in] logger The logger to use in this boolean rule. */ -bool_call::bool_call(std::string const& name) : _name(name) {} +bool_call::bool_call(std::string const& name, + const std::shared_ptr& logger) + : bool_value(logger), _name(name) {} /** * Get the hard value. @@ -90,7 +93,7 @@ void bool_call::set_expression(std::shared_ptr expression) { */ void bool_call::update_from(computable* child [[maybe_unused]], io::stream* visitor) { - log_v2::bam()->trace("bool_call::update_from"); + _logger->trace("bool_call::update_from"); if (child == _expression.get()) notify_parents_of_change(visitor); diff --git a/broker/bam/src/bool_constant.cc b/broker/bam/src/bool_constant.cc index 5db05c3c153..65eef3a8a0c 100644 --- a/broker/bam/src/bool_constant.cc +++ b/broker/bam/src/bool_constant.cc @@ -17,7 +17,6 @@ */ #include "com/centreon/broker/bam/bool_constant.hh" -#include "com/centreon/broker/log_v2.hh" using namespace com::centreon::broker::bam; @@ -27,9 +26,11 @@ constexpr double eps = 0.000001; * Constructor. * * @param[in] val The constant value to assign. + * @param[in] logger The logger to use in this boolean rule. */ -bool_constant::bool_constant(double val) - : _value(val), _boolean_value{std::abs(val) > ::eps} {} +bool_constant::bool_constant(double val, + const std::shared_ptr& logger) + : bool_value(logger), _value(val), _boolean_value{std::abs(val) > ::eps} {} /** * Get the hard value. @@ -66,7 +67,7 @@ bool bool_constant::state_known() const { */ void bool_constant::update_from(computable* child [[maybe_unused]], io::stream* visitor [[maybe_unused]]) { - log_v2::bam()->trace("bool_constant::update_from"); + _logger->trace("bool_constant::update_from"); } std::string bool_constant::object_info() const { diff --git a/broker/bam/src/bool_equal.cc b/broker/bam/src/bool_equal.cc index fb60c27e62d..1e13f263805 100644 --- a/broker/bam/src/bool_equal.cc +++ b/broker/bam/src/bool_equal.cc @@ -17,7 +17,6 @@ */ #include "com/centreon/broker/bam/bool_equal.hh" -#include "com/centreon/broker/log_v2.hh" #include diff --git a/broker/bam/src/bool_expression.cc b/broker/bam/src/bool_expression.cc index 34c2dc4d322..829b390af11 100644 --- a/broker/bam/src/bool_expression.cc +++ b/broker/bam/src/bool_expression.cc @@ -20,7 +20,6 @@ #include "com/centreon/broker/bam/bool_value.hh" #include "com/centreon/broker/bam/impact_values.hh" -#include "com/centreon/broker/log_v2.hh" using namespace com::centreon::broker::bam; using namespace com::centreon::broker; @@ -31,9 +30,12 @@ using namespace com::centreon::broker; * @param id Id of the boolean expression * @param impact_if True if impact is applied if the expression is true.False * otherwise. + * @param logger The logger to use. */ -bool_expression::bool_expression(uint32_t id, bool impact_if) - : _id(id), _impact_if(impact_if) {} +bool_expression::bool_expression(uint32_t id, + bool impact_if, + const std::shared_ptr& logger) + : computable(logger), _id(id), _impact_if(impact_if) {} /** * Get the boolean expression state. @@ -43,7 +45,7 @@ bool_expression::bool_expression(uint32_t id, bool impact_if) state bool_expression::get_state() const { bool v = _expression->boolean_value(); state retval = v == _impact_if ? state_critical : state_ok; - log_v2::bam()->debug( + _logger->debug( "BAM: boolean expression {} - impact if: {} - value: {} - state: {}", _id, _impact_if, static_cast(v), static_cast(retval)); return retval; @@ -97,7 +99,7 @@ uint32_t bool_expression::get_id() const { * @param visitor The visitor to handle events. */ void bool_expression::update_from(computable* child, io::stream* visitor) { - log_v2::bam()->trace("bool_expression::update_from"); + _logger->trace("bool_expression::update_from"); if (child == _expression.get()) notify_parents_of_change(visitor); } diff --git a/broker/bam/src/bool_less_than.cc b/broker/bam/src/bool_less_than.cc index ec6090d4285..bb2f3b8ac62 100644 --- a/broker/bam/src/bool_less_than.cc +++ b/broker/bam/src/bool_less_than.cc @@ -24,8 +24,11 @@ using namespace com::centreon::broker::bam; * Default constructor. * * @param[in] strict Should the operator be strict? + * @param[in] logger The logger to use. */ -bool_less_than::bool_less_than(bool strict) : _strict(strict) {} +bool_less_than::bool_less_than(bool strict, + const std::shared_ptr& logger) + : bool_binary_operator(logger), _strict{strict} {} /** * Get the hard value. diff --git a/broker/bam/src/bool_more_than.cc b/broker/bam/src/bool_more_than.cc index 2f6b25e340a..95d4008c58c 100644 --- a/broker/bam/src/bool_more_than.cc +++ b/broker/bam/src/bool_more_than.cc @@ -1,5 +1,5 @@ /** - * Copyright 2014, 2023 Centreon + * Copyright 2014, 2023-2024 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ */ #include "com/centreon/broker/bam/bool_more_than.hh" +#include "com/centreon/broker/bam/bool_binary_operator.hh" using namespace com::centreon::broker::bam; @@ -24,8 +25,11 @@ using namespace com::centreon::broker::bam; * Default constructor. * * @param[in] strict Should the operator be strict? + * @param[in] logger The logger to use. */ -bool_more_than::bool_more_than(bool strict) : _strict(strict) {} +bool_more_than::bool_more_than(bool strict, + const std::shared_ptr& logger) + : bool_binary_operator(logger), _strict{strict} {} /** * Get the hard value. diff --git a/broker/bam/src/bool_not.cc b/broker/bam/src/bool_not.cc index f0b8be0f03c..ee1363a26ef 100644 --- a/broker/bam/src/bool_not.cc +++ b/broker/bam/src/bool_not.cc @@ -18,7 +18,6 @@ #include "com/centreon/broker/bam/bool_not.hh" #include -#include "com/centreon/broker/log_v2.hh" using namespace com::centreon::broker::bam; @@ -29,7 +28,9 @@ constexpr double eps = 0.000001; * * @param[in] val Value that will be negated. */ -bool_not::bool_not(bool_value::ptr val) : _value(std::move(val)) {} +bool_not::bool_not(bool_value::ptr val, + const std::shared_ptr& logger) + : bool_value(logger), _value(std::move(val)) {} /** * Set value object. @@ -84,7 +85,7 @@ bool bool_not::in_downtime() const { */ void bool_not::update_from(computable* child [[maybe_unused]], io::stream* visitor) { - log_v2::bam()->trace("bool_not::update_from"); + _logger->trace("bool_not::update_from"); if (_value.get() == child) notify_parents_of_change(visitor); } diff --git a/broker/bam/src/bool_operation.cc b/broker/bam/src/bool_operation.cc index 12bef11453b..d1df6247cdf 100644 --- a/broker/bam/src/bool_operation.cc +++ b/broker/bam/src/bool_operation.cc @@ -19,6 +19,8 @@ #include "com/centreon/broker/bam/bool_operation.hh" #include +#include +#include "com/centreon/broker/bam/bool_binary_operator.hh" using namespace com::centreon::broker::bam; @@ -27,13 +29,15 @@ using namespace com::centreon::broker::bam; * * @param[in] op The operation in string format. */ -bool_operation::bool_operation(std::string const& op) - : _type((op == "+") ? addition +bool_operation::bool_operation(const std::string& op, + const std::shared_ptr& logger) + : bool_binary_operator(logger), + _type{(op == "+") ? addition : (op == "-") ? substraction : (op == "*") ? multiplication : (op == "/") ? division : (op == "%") ? modulo - : addition) {} + : addition} {} /** * Get the hard value. diff --git a/broker/bam/src/bool_or.cc b/broker/bam/src/bool_or.cc index f85d11d3a3e..b37ad3e4c7a 100644 --- a/broker/bam/src/bool_or.cc +++ b/broker/bam/src/bool_or.cc @@ -17,12 +17,9 @@ */ #include "com/centreon/broker/bam/bool_or.hh" -#include "com/centreon/broker/log_v2.hh" using namespace com::centreon::broker::bam; -constexpr double eps = 0.000001; - /** * @brief Check that the children are known and in that case propagate their * values to _left_hard and _right_hard. Otherwise these attributes have no @@ -32,25 +29,24 @@ constexpr double eps = 0.000001; * good value. */ void bool_or::_update_state() { - log_v2::bam()->trace("bool_or::update_state..."); + _logger->trace("bool_or::update_state..."); if (_left && _left->state_known() && _left->boolean_value()) { - log_v2::bam()->trace("bam: bool or left changed to true"); + _logger->trace("bam: bool or left changed to true"); _left_hard = true; _boolean_value = true; _state_known = true; } else if (_right && _right->state_known() && _right->boolean_value()) { - log_v2::bam()->trace("bam: bool or right changed to true"); + _logger->trace("bam: bool or right changed to true"); _right_hard = true; _boolean_value = true; _state_known = true; } else { - log_v2::bam()->trace( + _logger->trace( "bam: bool or: left false or unknown - right false or unknown"); _boolean_value = false; bool_binary_operator::_update_state(); - log_v2::bam()->trace( - "bam: bool or generic rule applied: value: {} - known : {}", - _boolean_value, _state_known); + _logger->trace("bam: bool or generic rule applied: value: {} - known : {}", + _boolean_value, _state_known); } } diff --git a/broker/bam/src/bool_service.cc b/broker/bam/src/bool_service.cc index 0b076683f72..13f4bae0c72 100644 --- a/broker/bam/src/bool_service.cc +++ b/broker/bam/src/bool_service.cc @@ -1,5 +1,5 @@ /** - * Copyright 2014, 2021-2023 Centreon + * Copyright 2014, 2021-2024 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,21 +22,23 @@ #include "bbdo/bam/state.hh" #include "com/centreon/broker/bam/service_state.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/neb/service_status.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::bam; -static constexpr bool time_is_undefined(uint64_t t) { - return t == 0 || t == static_cast(-1); -} - /** - * Default constructor. + * @brief Constructor + * + * @param host_id The host ID of the service. + * @param service_id The service ID of the service. + * @param logger The logger to use. */ -bool_service::bool_service(uint32_t host_id, uint32_t service_id) - : _host_id(host_id), +bool_service::bool_service(uint32_t host_id, + uint32_t service_id, + const std::shared_ptr& logger) + : bool_value(logger), + _host_id(host_id), _service_id(service_id), _state_hard(0), _state_known(false), @@ -69,13 +71,13 @@ uint32_t bool_service::get_service_id() const { */ void bool_service::service_update(const service_state& s) { // Update information. - log_v2::bam()->debug("BAM: bool_service updated with service state {}", s); + _logger->debug("BAM: bool_service updated with service state {}", s); bool changed = _state_hard != static_cast(s.last_hard_state) || !_state_known; _state_hard = static_cast(s.last_hard_state); - log_v2::bam()->debug("BAM: bool_service ({},{}) state hard set to {}", - s.host_id, s.service_id, _state_hard); + _logger->debug("BAM: bool_service ({},{}) state hard set to {}", s.host_id, + s.service_id, _state_hard); if (_state_hard != state_unknown) _state_known = true; @@ -91,9 +93,9 @@ void bool_service::service_update(const service_state& s) { * @param[out] visitor Object that will receive events. */ void bool_service::service_update( - std::shared_ptr const& status, + const std::shared_ptr& status, io::stream* visitor) { - SPDLOG_LOGGER_TRACE(log_v2::bam(), + SPDLOG_LOGGER_TRACE(_logger, "bool_service: service update with neb::service_status"); if (status && status->host_id == _host_id && status->service_id == _service_id) { @@ -118,7 +120,7 @@ void bool_service::service_update( void bool_service::service_update(const std::shared_ptr& svc, io::stream* visitor) { auto& o = svc->obj(); - SPDLOG_LOGGER_TRACE(log_v2::bam(), + SPDLOG_LOGGER_TRACE(_logger, "bool_service: service ({},{}) updated with " "neb::pb_service hard state: {}, downtime: {}", o.host_id(), o.service_id(), o.last_hard_state(), @@ -131,7 +133,7 @@ void bool_service::service_update(const std::shared_ptr& svc, _state_hard = o.last_hard_state(); _state_known = true; _in_downtime = new_in_downtime; - log_v2::bam()->trace("bool_service: updated with state: {}", _state_hard); + _logger->trace("bool_service: updated with state: {}", _state_hard); notify_parents_of_change(visitor); } } @@ -147,7 +149,7 @@ void bool_service::service_update( const std::shared_ptr& status, io::stream* visitor) { auto& o = status->obj(); - SPDLOG_LOGGER_TRACE(log_v2::bam(), + SPDLOG_LOGGER_TRACE(_logger, "bool_service: service ({},{}) updated with " "neb::pb_service_status hard state: {}, downtime: {}", o.host_id(), o.service_id(), o.last_hard_state(), @@ -159,7 +161,7 @@ void bool_service::service_update( _state_hard = o.last_hard_state(); _state_known = true; _in_downtime = new_in_downtime; - log_v2::bam()->trace("bool_service: updated with state: {}", _state_hard); + _logger->trace("bool_service: updated with state: {}", _state_hard); notify_parents_of_change(visitor); } } @@ -209,7 +211,7 @@ bool bool_service::in_downtime() const { */ void bool_service::update_from(computable* child [[maybe_unused]], io::stream* visitor) { - log_v2::bam()->trace("bool_service::update_from"); + _logger->trace("bool_service::update_from"); notify_parents_of_change(visitor); } diff --git a/broker/bam/src/bool_value.cc b/broker/bam/src/bool_value.cc index a4e7191de70..767ddda1879 100644 --- a/broker/bam/src/bool_value.cc +++ b/broker/bam/src/bool_value.cc @@ -1,20 +1,20 @@ /** -* Copyright 2014 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2014 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/bam/bool_value.hh" diff --git a/broker/bam/src/computable.cc b/broker/bam/src/computable.cc index af9871894b3..58c186e5e11 100644 --- a/broker/bam/src/computable.cc +++ b/broker/bam/src/computable.cc @@ -18,8 +18,6 @@ #include "com/centreon/broker/bam/computable.hh" -#include "com/centreon/broker/log_v2.hh" - using namespace com::centreon::broker::bam; /** @@ -55,7 +53,7 @@ void computable::remove_parent(std::shared_ptr const& parent) { * @param visitor Used to handle events. */ void computable::notify_parents_of_change(io::stream* visitor) { - log_v2::bam()->trace("{}::notify_parents_of_change: ", typeid(*this).name()); + _logger->trace("{}::notify_parents_of_change: ", typeid(*this).name()); for (auto& p : _parents) { if (std::shared_ptr parent = p.lock()) parent->update_from(this, visitor); diff --git a/broker/bam/src/configuration/applier/ba.cc b/broker/bam/src/configuration/applier/ba.cc index c2e8e31cbf5..be141603f09 100644 --- a/broker/bam/src/configuration/applier/ba.cc +++ b/broker/bam/src/configuration/applier/ba.cc @@ -25,18 +25,22 @@ #include "com/centreon/broker/bam/ba_worst.hh" #include "com/centreon/broker/bam/internal.hh" #include "com/centreon/broker/config/applier/state.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/multiplexing/publisher.hh" #include "com/centreon/broker/neb/host.hh" #include "com/centreon/broker/neb/service.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::bam::configuration; +using com::centreon::common::log_v2::log_v2; /** - * Default constructor. + * @brief Constructor of an applier of BA. + * + * @param logger The logger to use. */ -applier::ba::ba() {} +applier::ba::ba(const std::shared_ptr& logger) + : _logger{logger} {} /** * Copy constructor. @@ -122,7 +126,7 @@ void applier::ba::apply(const bam::configuration::state::bas& my_bas, for (std::map::iterator it = to_delete.begin(), end = to_delete.end(); it != end; ++it) { - log_v2::bam()->info("BAM: removing BA {}", it->first); + _logger->info("BAM: removing BA {}", it->first); std::shared_ptr s; if (bbdo3_enabled) { auto bs = _ba_pb_service(it->first, it->second.cfg.get_host_id(), @@ -146,8 +150,8 @@ void applier::ba::apply(const bam::configuration::state::bas& my_bas, for (bam::configuration::state::bas::iterator it = to_create.begin(), end = to_create.end(); it != end; ++it) { - log_v2::bam()->info("BAM: creating BA {} ('{}')", it->first, - it->second.get_name()); + _logger->info("BAM: creating BA {} ('{}')", it->first, + it->second.get_name()); std::shared_ptr new_ba(_new_ba(it->second, book)); applied& content(_applied[it->first]); content.cfg = it->second; @@ -173,14 +177,14 @@ void applier::ba::apply(const bam::configuration::state::bas& my_bas, for (auto& b : to_modify) { std::map::iterator pos = _applied.find(b.get_id()); if (pos != _applied.end()) { - log_v2::bam()->info("BAM: modifying BA {}", b.get_id()); + _logger->info("BAM: modifying BA {}", b.get_id()); pos->second.obj->set_name(b.get_name()); assert(pos->second.obj->get_state_source() == b.get_state_source()); pos->second.obj->set_level_warning(b.get_warning_level()); pos->second.obj->set_level_critical(b.get_critical_level()); pos->second.cfg = b; } else - log_v2::bam()->error( + _logger->error( "BAM: attempting to modify BA {}, however associated object was not " "found. This is likely a software bug that you should report to " "Centreon Broker developers", @@ -268,8 +272,8 @@ std::shared_ptr applier::ba::_ba_service(uint32_t ba_id, uint32_t host_id, uint32_t service_id, bool in_downtime) { - log_v2::bam()->trace("_ba_service ba {}, service {}:{} with downtime {}", - ba_id, host_id, service_id, in_downtime); + _logger->trace("_ba_service ba {}, service {}:{} with downtime {}", ba_id, + host_id, service_id, in_downtime); auto s{std::make_shared()}; s->host_id = host_id; s->service_id = service_id; @@ -294,8 +298,8 @@ std::shared_ptr applier::ba::_ba_pb_service( uint32_t host_id, uint32_t service_id, bool in_downtime) { - log_v2::bam()->trace("_ba_pb_service ba {}, service {}:{} with downtime {}", - ba_id, host_id, service_id, in_downtime); + _logger->trace("_ba_pb_service ba {}, service {}:{} with downtime {}", ba_id, + host_id, service_id, in_downtime); auto s{std::make_shared()}; auto& o = s->mut_obj(); o.set_host_id(host_id); @@ -333,23 +337,28 @@ std::shared_ptr applier::ba::_new_ba(configuration::ba const& cfg, switch (cfg.get_state_source()) { case configuration::ba::state_source_impact: obj = std::make_shared(cfg.get_id(), cfg.get_host_id(), - cfg.get_service_id(), false); + cfg.get_service_id(), false, + _logger); break; case configuration::ba::state_source_best: - obj = std::make_shared(cfg.get_id(), cfg.get_host_id(), - cfg.get_service_id(), false); + obj = + std::make_shared(cfg.get_id(), cfg.get_host_id(), + cfg.get_service_id(), false, _logger); break; case configuration::ba::state_source_worst: - obj = std::make_shared(cfg.get_id(), cfg.get_host_id(), - cfg.get_service_id(), false); + obj = + std::make_shared(cfg.get_id(), cfg.get_host_id(), + cfg.get_service_id(), false, _logger); break; case configuration::ba::state_source_ratio_percent: obj = std::make_shared( - cfg.get_id(), cfg.get_host_id(), cfg.get_service_id(), false); + cfg.get_id(), cfg.get_host_id(), cfg.get_service_id(), false, + _logger); break; case configuration::ba::state_source_ratio_number: obj = std::make_shared( - cfg.get_id(), cfg.get_host_id(), cfg.get_service_id(), false); + cfg.get_id(), cfg.get_host_id(), cfg.get_service_id(), false, + _logger); break; default: /* Should not arrive */ @@ -390,8 +399,7 @@ void applier::ba::apply_inherited_downtime(const inherited_downtime& dwn) { std::map::iterator found = _applied.find(dwn.ba_id); if (found != _applied.end()) { - log_v2::bam()->debug("BAM: found an inherited downtime for BA {}", - found->first); + _logger->debug("BAM: found an inherited downtime for BA {}", found->first); found->second.obj->set_inherited_downtime(dwn); std::shared_ptr s; if (bbdo3_enabled) @@ -410,8 +418,7 @@ void applier::ba::apply_inherited_downtime(const pb_inherited_downtime& dwn) { std::map::iterator found = _applied.find(dwn.obj().ba_id()); if (found != _applied.end()) { - log_v2::bam()->debug("BAM: found an inherited downtime for BA {}", - found->first); + _logger->debug("BAM: found an inherited downtime for BA {}", found->first); found->second.obj->set_inherited_downtime(dwn); std::shared_ptr s; if (bbdo3_enabled) diff --git a/broker/bam/src/configuration/applier/bool_expression.cc b/broker/bam/src/configuration/applier/bool_expression.cc index 74bc6f13cc2..35cb28115e9 100644 --- a/broker/bam/src/configuration/applier/bool_expression.cc +++ b/broker/bam/src/configuration/applier/bool_expression.cc @@ -1,20 +1,20 @@ /** -* Copyright 2014-2016 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2014-2016 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/bam/bool_expression.hh" #include "com/centreon/broker/bam/ba.hh" @@ -24,7 +24,6 @@ #include "com/centreon/broker/bam/exp_builder.hh" #include "com/centreon/broker/bam/exp_parser.hh" #include "com/centreon/broker/bam/service_book.hh" -#include "com/centreon/broker/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::bam::configuration; @@ -85,8 +84,8 @@ void applier::bool_expression::apply( for (std::map::iterator it(to_delete.begin()), end(to_delete.end()); it != end; ++it) { - log_v2::bam()->info("BAM: removing boolean expression {}", - it->second.cfg.get_id()); + _logger->info("BAM: removing boolean expression {}", + it->second.cfg.get_id()); for (std::list::const_iterator it2(it->second.svc.begin()), end2(it->second.svc.end()); @@ -101,12 +100,12 @@ void applier::bool_expression::apply( for (bam::configuration::state::bool_exps::iterator it = to_create.begin(), end = to_create.end(); it != end; ++it) { - log_v2::bam()->info("BAM: creating new boolean expression {}", it->first); + _logger->info("BAM: creating new boolean expression {}", it->first); auto new_bool_exp = std::make_shared( - it->first, it->second.get_impact_if()); + it->first, it->second.get_impact_if(), _logger); try { bam::exp_parser p(it->second.get_expression()); - bam::exp_builder b(p.get_postfix(), mapping); + bam::exp_builder b(p.get_postfix(), mapping, _logger); bam::bool_value::ptr tree(b.get_tree()); new_bool_exp->set_expression(tree); if (tree) @@ -125,7 +124,7 @@ void applier::bool_expression::apply( book.listen((*it2)->get_host_id(), (*it2)->get_service_id(), it2->get()); } catch (std::exception const& e) { - log_v2::bam()->error( + _logger->error( "BAM: could not create boolean expression {} so it will be " "discarded: {}", it->first, e.what()); @@ -170,7 +169,7 @@ void applier::bool_expression::_resolve_expression_calls() { std::map::const_iterator found = _name_to_ids.find((*call_it)->get_name()); if (found == _name_to_ids.end()) { - log_v2::bam()->error( + _logger->error( "BAM: could not resolve the external boolean called '{}' for " "expression '{}'", (*call_it)->get_name(), it->second.cfg.get_name()); diff --git a/broker/bam/src/configuration/applier/kpi.cc b/broker/bam/src/configuration/applier/kpi.cc index bfabdbbdddb..09dc1bbd613 100644 --- a/broker/bam/src/configuration/applier/kpi.cc +++ b/broker/bam/src/configuration/applier/kpi.cc @@ -1,20 +1,20 @@ /** -* Copyright 2014-2015, 2021 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2014-2015, 2021-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/bam/configuration/applier/kpi.hh" #include "com/centreon/broker/bam/bool_expression.hh" @@ -25,17 +25,25 @@ #include "com/centreon/broker/bam/kpi_service.hh" #include "com/centreon/broker/bam/service_book.hh" #include "com/centreon/broker/exceptions/config.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/multiplexing/publisher.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::bam::configuration; +using log_v2 = com::centreon::common::log_v2::log_v2; + /** - * Default constructor. + * @brief Constructor of an applier of KPI. + * + * @param logger The logger to use. */ -applier::kpi::kpi() - : _bas(nullptr), _book(nullptr), _boolexps(nullptr), _mapping(nullptr) {} +applier::kpi::kpi(const std::shared_ptr& logger) + : _logger{logger}, + _bas(nullptr), + _book(nullptr), + _boolexps(nullptr), + _mapping(nullptr) {} /** * Copy constructor. @@ -123,7 +131,7 @@ void applier::kpi::apply(bam::configuration::state::kpis const& my_kpis, for (std::map::iterator it(to_delete.begin()), end(to_delete.end()); it != end; ++it) { - log_v2::bam()->info("BAM: removing KPI {}", it->second.cfg.get_id()); + _logger->info("BAM: removing KPI {}", it->second.cfg.get_id()); std::map::iterator kpi_it = _applied.find(it->first); if (kpi_it != _applied.end()) _remove_kpi(kpi_it); @@ -136,8 +144,8 @@ void applier::kpi::apply(bam::configuration::state::kpis const& my_kpis, it != end; ++it) { if (!mapping.get_activated(it->second.get_host_id(), it->second.get_service_id())) { - log_v2::bam()->info( - "BAM: ignoring kpi '{}' linked to a deactivated service", it->first); + _logger->info("BAM: ignoring kpi '{}' linked to a deactivated service", + it->first); continue; } try { @@ -147,8 +155,7 @@ void applier::kpi::apply(bam::configuration::state::kpis const& my_kpis, content.obj = new_kpi; } catch (exceptions::config const& e) { // Log message. - log_v2::bam()->error("BAM: could not create KPI {}: {}", it->first, - e.what()); + _logger->error("BAM: could not create KPI {}: {}", it->first, e.what()); _invalidate_ba(it->second); } @@ -168,8 +175,8 @@ void applier::kpi::apply(bam::configuration::state::kpis const& my_kpis, _resolve_kpi(cfg, my_kpi); } catch (exceptions::config const& e) { // Log message. - log_v2::bam()->error("BAM: could not resolve KPI {}: {}", cfg.get_id(), - e.what()); + _logger->error("BAM: could not resolve KPI {}: {}", cfg.get_id(), + e.what()); _invalidate_ba(cfg); next_kpi_it = _applied.begin(); @@ -223,8 +230,8 @@ void applier::kpi::_invalidate_ba(configuration::kpi const& kpi) { // Set BA as invalid. std::shared_ptr my_ba(_bas->find_ba(kpi_ba_id)); if (my_ba) { - log_v2::bam()->error("BAM: BA '{}' with id {} is set as invalid", - my_ba->get_name(), my_ba->get_id()); + _logger->error("BAM: BA '{}' with id {} is set as invalid", + my_ba->get_name(), my_ba->get_id()); my_ba->set_valid(false); } } @@ -246,7 +253,8 @@ void applier::kpi::visit(io::stream* visitor) { * * @param[in] other Object to copy. */ -void applier::kpi::_internal_copy(applier::kpi const& other) { +void applier::kpi::_internal_copy(const applier::kpi& other) { + _logger = other._logger; _applied = other._applied; _bas = other._bas; _book = other._book; @@ -266,13 +274,13 @@ std::shared_ptr applier::kpi::_new_kpi( // Create KPI according to its type. std::shared_ptr my_kpi; if (cfg.is_service()) { - log_v2::bam()->info( + _logger->info( "BAM: creating new KPI {} of service {} ({}, {}) impacting BA {}", cfg.get_id(), cfg.get_name(), cfg.get_host_id(), cfg.get_service_id(), cfg.get_ba_id()); auto obj{std::make_shared( cfg.get_id(), cfg.get_ba_id(), cfg.get_host_id(), cfg.get_service_id(), - cfg.get_name())}; + cfg.get_name(), _logger)}; obj->set_acknowledged(cfg.is_acknowledged()); obj->set_downtimed(cfg.is_downtimed()); obj->set_impact_critical(cfg.get_impact_critical()); @@ -283,21 +291,21 @@ std::shared_ptr applier::kpi::_new_kpi( _book->listen(cfg.get_host_id(), cfg.get_service_id(), obj.get()); my_kpi = std::static_pointer_cast(obj); } else if (cfg.is_ba()) { - log_v2::bam()->info("BAM: creating new KPI {} of BA {}:{} impacting BA {}", - cfg.get_id(), cfg.get_indicator_ba_id(), cfg.get_name(), - cfg.get_ba_id()); + _logger->info("BAM: creating new KPI {} of BA {}:{} impacting BA {}", + cfg.get_id(), cfg.get_indicator_ba_id(), cfg.get_name(), + cfg.get_ba_id()); std::shared_ptr obj(std::make_shared( - cfg.get_id(), cfg.get_ba_id(), cfg.get_name())); + cfg.get_id(), cfg.get_ba_id(), cfg.get_name(), _logger)); obj->set_impact_critical(cfg.get_impact_critical()); obj->set_impact_unknown(cfg.get_impact_unknown()); obj->set_impact_warning(cfg.get_impact_warning()); my_kpi = std::static_pointer_cast(obj); } else if (cfg.is_boolexp()) { - log_v2::bam()->info( + _logger->info( "BAM: creating new KPI {} of boolean expression {}:{} impacting BA {}", cfg.get_id(), cfg.get_boolexp_id(), cfg.get_name(), cfg.get_ba_id()); std::shared_ptr obj(std::make_shared( - cfg.get_id(), cfg.get_ba_id(), cfg.get_name())); + cfg.get_id(), cfg.get_ba_id(), cfg.get_name(), _logger)); obj->set_impact(cfg.get_impact_critical()); my_kpi = std::static_pointer_cast(obj); } else @@ -331,8 +339,7 @@ void applier::kpi::_resolve_kpi(configuration::kpi const& cfg, cfg.get_indicator_ba_id()); obj->link_ba(target); target->add_parent(obj); - log_v2::bam()->info("BAM: Resolve KPI {} connections to its BA", - kpi->get_id()); + _logger->info("BAM: Resolve KPI {} connections to its BA", kpi->get_id()); } else if (cfg.is_boolexp()) { std::shared_ptr obj( std::static_pointer_cast(kpi)); @@ -343,9 +350,8 @@ void applier::kpi::_resolve_kpi(configuration::kpi const& cfg, cfg.get_boolexp_id()); obj->link_boolexp(target); target->add_parent(obj); - log_v2::bam()->info( - "BAM: Resolve KPI {} connections to its boolean expression", - kpi->get_id()); + _logger->info("BAM: Resolve KPI {} connections to its boolean expression", + kpi->get_id()); } // Link KPI with BA. diff --git a/broker/bam/src/configuration/applier/state.cc b/broker/bam/src/configuration/applier/state.cc index cfe79e0d8a1..b1ac2c999f7 100644 --- a/broker/bam/src/configuration/applier/state.cc +++ b/broker/bam/src/configuration/applier/state.cc @@ -1,5 +1,5 @@ /** - * Copyright 2014-2023 Centreon + * Copyright 2014-2024 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +21,6 @@ #include "com/centreon/broker/bam/internal.hh" #include "com/centreon/broker/bam/exp_builder.hh" -#include "com/centreon/broker/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; @@ -72,6 +71,18 @@ static std::string service_node_id(uint32_t host_id, uint32_t service_id) { return fmt::format("service ({}, {})", host_id, service_id); } +/** + * @brief Constructor + * + * @param logger The logger to use with this class. + */ +applier::state::state(const std::shared_ptr& logger) + : _logger{logger}, + _ba_applier(_logger), + _book_service(_logger), + _kpi_applier(_logger), + _bool_exp_applier(_logger) {} + /** * Apply configuration. * @@ -148,7 +159,8 @@ void applier::state::_circular_check(configuration::state const& my_state) { _nodes[bool_id]; try { exp_parser parsr(it->second.get_expression()); - exp_builder buildr(parsr.get_postfix(), my_state.get_hst_svc_mapping()); + exp_builder buildr(parsr.get_postfix(), my_state.get_hst_svc_mapping(), + _logger); for (std::list::const_iterator it_svc(buildr.get_services().begin()), end_svc(buildr.get_services().end()); @@ -224,12 +236,12 @@ void applier::state::_circular_check(applier::state::circular_check_node& n) { * @param[in] cache The cache. */ void applier::state::save_to_cache(persistent_cache& cache) { - log_v2::bam()->trace("BAM: Saving states to cache"); + _logger->trace("BAM: Saving states to cache"); cache.transaction(); _book_service.save_to_cache(cache); _ba_applier.save_to_cache(cache); cache.commit(); - log_v2::bam()->trace("BAM: States correctly saved"); + _logger->trace("BAM: States correctly saved"); } /** @@ -238,8 +250,7 @@ void applier::state::save_to_cache(persistent_cache& cache) { * @param[in] cache the cache. */ void applier::state::load_from_cache(persistent_cache& cache) { - log_v2::bam()->debug( - "BAM: Loading restoring inherited downtimes and BA states"); + _logger->debug("BAM: Loading restoring inherited downtimes and BA states"); std::shared_ptr d; cache.get(d); @@ -263,7 +274,7 @@ void applier::state::load_from_cache(persistent_cache& cache) { } cache.get(d); } - log_v2::bam()->debug("BAM: Inherited downtimes and BA states restored"); + _logger->debug("BAM: Inherited downtimes and BA states restored"); } /** diff --git a/broker/bam/src/configuration/reader_v2.cc b/broker/bam/src/configuration/reader_v2.cc index d012a3907fe..28089d1f5f4 100644 --- a/broker/bam/src/configuration/reader_v2.cc +++ b/broker/bam/src/configuration/reader_v2.cc @@ -25,15 +25,16 @@ #include "com/centreon/broker/bam/configuration/state.hh" #include "com/centreon/broker/config/applier/state.hh" #include "com/centreon/broker/io/stream.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/multiplexing/publisher.hh" #include "com/centreon/broker/sql/mysql.hh" #include "com/centreon/broker/time/timeperiod.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::bam::configuration; +using com::centreon::common::log_v2::log_v2; /** * Constructor. @@ -42,7 +43,9 @@ using namespace com::centreon::broker::bam::configuration; * @param[in] storage_cfg Storage database configuration. */ reader_v2::reader_v2(mysql& centreon_db, const database_config& storage_cfg) - : _mysql(centreon_db), _storage_cfg(storage_cfg) {} + : _logger{log_v2::instance().get(log_v2::BAM)}, + _mysql(centreon_db), + _storage_cfg(storage_cfg) {} /** * Read configuration from database. @@ -52,20 +55,20 @@ reader_v2::reader_v2(mysql& centreon_db, const database_config& storage_cfg) */ void reader_v2::read(state& st) { try { - SPDLOG_LOGGER_INFO(log_v2::bam(), "loading dimensions."); + SPDLOG_LOGGER_INFO(_logger, "loading dimensions."); _load_dimensions(); - SPDLOG_LOGGER_INFO(log_v2::bam(), "loading BAs."); + SPDLOG_LOGGER_INFO(_logger, "loading BAs."); _load(st.get_bas(), st.get_ba_svc_mapping()); - SPDLOG_LOGGER_INFO(log_v2::bam(), "loading KPIs."); + SPDLOG_LOGGER_INFO(_logger, "loading KPIs."); _load(st.get_kpis()); - SPDLOG_LOGGER_INFO(log_v2::bam(), "loading boolean expressions."); + SPDLOG_LOGGER_INFO(_logger, "loading boolean expressions."); _load(st.get_bool_exps()); - SPDLOG_LOGGER_INFO(log_v2::bam(), "loading mapping hosts <-> services."); + SPDLOG_LOGGER_INFO(_logger, "loading mapping hosts <-> services."); _load(st.get_hst_svc_mapping()); - SPDLOG_LOGGER_INFO(log_v2::bam(), "bam configuration loaded."); + SPDLOG_LOGGER_INFO(_logger, "bam configuration loaded."); } catch (std::exception const& e) { - SPDLOG_LOGGER_ERROR(log_v2::bam(), - "Error while reading bam configuration: {}", e.what()); + SPDLOG_LOGGER_ERROR(_logger, "Error while reading bam configuration: {}", + e.what()); st.clear(); throw; } @@ -225,7 +228,7 @@ void reader_v2::_load(state::kpis& kpis) { * description. */ void reader_v2::_load(state::bas& bas, bam::ba_svc_mapping& mapping) { - SPDLOG_LOGGER_INFO(log_v2::bam(), "BAM: loading BAs"); + SPDLOG_LOGGER_INFO(_logger, "BAM: loading BAs"); try { { std::string query( @@ -265,7 +268,7 @@ void reader_v2::_load(state::bas& bas, bam::ba_svc_mapping& mapping) { e.mut_obj().set_in_downtime(res.value_as_bool(7)); bas[ba_id].set_opened_event(e); SPDLOG_LOGGER_TRACE( - log_v2::bam(), + _logger, "BAM: ba {} configuration (start_time:{}, in downtime: {})", ba_id, e.obj().start_time(), e.obj().in_downtime()); } @@ -305,7 +308,7 @@ void reader_v2::_load(state::bas& bas, bam::ba_svc_mapping& mapping) { uint32_t ba_id; if (!absl::SimpleAtoi(service_description, &ba_id)) { SPDLOG_LOGGER_INFO( - log_v2::bam(), + _logger, "BAM: service '{}' of host '{}' is not a valid virtual BA " "service", res.value_as_str(1), res.value_as_str(0)); @@ -314,7 +317,7 @@ void reader_v2::_load(state::bas& bas, bam::ba_svc_mapping& mapping) { state::bas::iterator found = bas.find(ba_id); if (found == bas.end()) { SPDLOG_LOGGER_INFO( - log_v2::bam(), + _logger, "BAM: virtual BA service '{}' of host '{}' references an " "unknown BA ({})", res.value_as_str(1), res.value_as_str(0), ba_id); @@ -415,7 +418,7 @@ void reader_v2::_load(bam::hst_svc_mapping& mapping) { * Load the dimensions from the database. */ void reader_v2::_load_dimensions() { - SPDLOG_LOGGER_TRACE(log_v2::bam(), "load dimensions"); + SPDLOG_LOGGER_TRACE(_logger, "load dimensions"); auto out{std::make_unique()}; // As this operation is destructive (it truncates the database), // we cache the data until we are sure we have all the data @@ -653,11 +656,10 @@ void reader_v2::_load_dimensions() { if (ev.kpi_ba_id()) { auto found = bas.find(ev.kpi_ba_id()); if (found == bas.end()) { - SPDLOG_LOGGER_ERROR( - log_v2::bam(), - "BAM: could not retrieve BA {} used as KPI {} in dimension " - "table: ignoring this KPI", - ev.kpi_ba_id(), ev.kpi_id()); + SPDLOG_LOGGER_ERROR(_logger, + "BAM: could not retrieve BA {} used as KPI {} in " + "dimension table: ignoring this KPI", + ev.kpi_ba_id(), ev.kpi_id()); continue; } ev.set_kpi_ba_name(found->second->obj().ba_name()); diff --git a/broker/bam/src/connector.cc b/broker/bam/src/connector.cc index 8c5486b4ec5..0819f341921 100644 --- a/broker/bam/src/connector.cc +++ b/broker/bam/src/connector.cc @@ -50,6 +50,9 @@ static constexpr multiplexing::muxer_filter _monitoring_stream_filter = { inherited_downtime::static_type(), pb_inherited_downtime::static_type(), extcmd::pb_ba_info::static_type(), pb_services_book_state::static_type()}; +static constexpr multiplexing::muxer_filter _monitoring_forbidden_filter = + multiplexing::muxer_filter(_monitoring_stream_filter).reverse(); + static constexpr multiplexing::muxer_filter _reporting_stream_filter = { bam::kpi_event::static_type(), bam::pb_kpi_event::static_type(), @@ -73,6 +76,9 @@ static constexpr multiplexing::muxer_filter _reporting_stream_filter = { bam::pb_dimension_ba_timeperiod_relation::static_type(), bam::rebuild::static_type()}; +static constexpr multiplexing::muxer_filter _reporting_forbidden_filter = + multiplexing::muxer_filter(_reporting_stream_filter).reverse(); + /** * @brief Constructor. This function is not easy to use so it is private and * called thanks two static functions: @@ -82,12 +88,16 @@ static constexpr multiplexing::muxer_filter _reporting_stream_filter = { * @param type A stream_type enum giving the following choices : * bam_monitoring_type or bam_reporting_type. * @param db_cfg The database configuration. - * @param filter The mandatory filters of the underlying stream. + * @param mandatory_filter The mandatory filters of the underlying stream. + * @param forbidden_filter The forbidden filters of the underlying stream. */ connector::connector(stream_type type, const database_config& db_cfg, - const multiplexing::muxer_filter& filter) - : io::endpoint(false, filter), _type{type}, _db_cfg{db_cfg} {} + const multiplexing::muxer_filter& mandatory_filter, + const multiplexing::muxer_filter& forbidden_filter) + : io::endpoint(false, mandatory_filter, forbidden_filter), + _type{type}, + _db_cfg{db_cfg} {} /** * @brief Static function to create a connector for a bam monitoring stream. @@ -104,8 +114,9 @@ std::unique_ptr connector::create_monitoring_connector( const database_config& db_cfg, const std::string& storage_db_name, std::shared_ptr cache) { - auto retval = std::unique_ptr(new bam::connector( - bam_monitoring_type, db_cfg, _monitoring_stream_filter)); + auto retval = std::unique_ptr( + new bam::connector(bam_monitoring_type, db_cfg, _monitoring_stream_filter, + _monitoring_forbidden_filter)); retval->_ext_cmd_file = ext_cmd_file; retval->_cache = std::move(cache); if (storage_db_name.empty()) @@ -123,7 +134,8 @@ std::unique_ptr connector::create_monitoring_connector( std::unique_ptr connector::create_reporting_connector( const database_config& db_cfg) { auto retval = std::unique_ptr( - new bam::connector(bam_reporting_type, db_cfg, _reporting_stream_filter)); + new bam::connector(bam_reporting_type, db_cfg, _reporting_stream_filter, + _reporting_forbidden_filter)); return retval; } @@ -133,13 +145,14 @@ std::unique_ptr connector::create_reporting_connector( * @return BAM connection object. */ std::shared_ptr connector::open() { + auto logger = log_v2::instance().get(log_v2::BAM); if (_type == bam_reporting_type) - return std::shared_ptr(new reporting_stream(_db_cfg)); + return std::make_shared(_db_cfg, logger); else { database_config storage_db_cfg(_db_cfg); storage_db_cfg.set_name(_storage_db_name); - auto u = std::make_shared(_ext_cmd_file, _db_cfg, - storage_db_cfg, _cache); + auto u = std::make_shared( + _ext_cmd_file, _db_cfg, storage_db_cfg, _cache, logger); // FIXME DBR: just after this creation, initialize() is called by update() // So I think this call is not needed. But for now not totally sure. // u->initialize(); diff --git a/broker/bam/src/exp_builder.cc b/broker/bam/src/exp_builder.cc index 923714dba08..8c010ac0584 100644 --- a/broker/bam/src/exp_builder.cc +++ b/broker/bam/src/exp_builder.cc @@ -1,20 +1,20 @@ /** -* Copyright 2016 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2016, 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/bam/exp_builder.hh" @@ -42,12 +42,14 @@ using namespace com::centreon::broker::bam; * @param[in] postfix Postfix notation of the expression. Likely * generated by exp_parser. * @param[in] mapping Map host names and service descriptions to IDs. + * @param[in] logger The logger to use. * * @see exp_parser */ exp_builder::exp_builder(exp_parser::notation const& postfix, - hst_svc_mapping const& mapping) - : _mapping(mapping) { + hst_svc_mapping const& mapping, + const std::shared_ptr& logger) + : _logger(logger), _mapping(mapping) { // Browse all tokens. for (exp_parser::notation::const_iterator it(postfix.begin()), end(postfix.end()); @@ -59,7 +61,7 @@ exp_builder::exp_builder(exp_parser::notation const& postfix, // XXX } else if (*it == "!") { bool_value::ptr arg(_pop_operand()); - any_operand exp(std::make_shared(arg), ""); + any_operand exp(std::make_shared(arg, _logger), ""); arg->add_parent(exp.first); _operands.push(exp); } @@ -67,31 +69,29 @@ exp_builder::exp_builder(exp_parser::notation const& postfix, else { bool_binary_operator::ptr binary; if (*it == "&&" || *it == "AND") - binary.reset(new bool_and()); + binary = std::make_shared(_logger); else if (*it == "||" || *it == "OR") - binary.reset(new bool_or()); + binary = std::make_shared(_logger); else if (*it == "^" || *it == "XOR") - binary.reset(new bool_xor()); + binary = std::make_shared(_logger); else if (*it == "==" || *it == "IS") - binary.reset(new bool_equal()); + binary = std::make_shared(_logger); else if (*it == "!=" || *it == "NOT") - binary.reset(new bool_not_equal()); + binary = std::make_shared(_logger); else if (*it == ">") - binary.reset(new bool_more_than(true)); + binary = std::make_shared(true, _logger); else if (*it == ">=") - binary.reset(new bool_more_than(false)); + binary = std::make_shared(false, _logger); else if (*it == "<") - binary.reset(new bool_less_than(true)); + binary = std::make_shared(true, _logger); else if (*it == "<=") - binary.reset(new bool_less_than(false)); + binary = std::make_shared(false, _logger); else if (*it == "+" || *it == "-" || *it == "*" || *it == "/" || *it == "%") - binary.reset(new bool_operation(*it)); + binary = std::make_shared(*it, _logger); else throw msg_fmt( - "unsupported operator {}" - " found while parsing expression", - *it); + "unsupported operator {} found while parsing expression", *it); bool_value::ptr right(_pop_operand()); bool_value::ptr left(_pop_operand()); left->add_parent(binary); @@ -134,7 +134,7 @@ exp_builder::exp_builder(exp_parser::notation const& postfix, // Build object. bool_service::ptr obj{ - std::make_shared(ids.first, ids.second)}; + std::make_shared(ids.first, ids.second, _logger)}; // Store it in the operand stack and within the service list. _operands.push(any_operand(obj, "")); @@ -284,7 +284,7 @@ bool_value::ptr exp_builder::_pop_operand() { value = 2; else value = std::strtod(value_str.c_str(), nullptr); - retval.reset(new bool_constant(value)); + retval.reset(new bool_constant(value, _logger)); } else retval = _operands.top().first; diff --git a/broker/bam/src/exp_parser.cc b/broker/bam/src/exp_parser.cc index 3841747d803..4c128ed311d 100644 --- a/broker/bam/src/exp_parser.cc +++ b/broker/bam/src/exp_parser.cc @@ -1,30 +1,31 @@ /** -* Copyright 2016 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2016 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/bam/exp_parser.hh" #include "com/centreon/broker/bam/exp_tokenizer.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::bam; +using com::centreon::common::log_v2::log_v2; /** * Constructor. @@ -39,7 +40,9 @@ exp_parser::exp_parser(const std::string& expression) {"==", 3}, {"!=", 3}, {"+", 4}, {"-", 4}, {"*", 5}, {"/", 5}, {"%", 5}, {"-u", 6}, {"!", 6}} { - log_v2::bam()->trace("exp_parser constructor '{}'", expression); + log_v2::instance() + .get(log_v2::BAM) + ->trace("exp_parser constructor '{}'", expression); } /** diff --git a/broker/bam/src/hst_svc_mapping.cc b/broker/bam/src/hst_svc_mapping.cc index 70887131558..174fbf15ba9 100644 --- a/broker/bam/src/hst_svc_mapping.cc +++ b/broker/bam/src/hst_svc_mapping.cc @@ -1,25 +1,26 @@ /** -* Copyright 2014, 2021 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2014, 2021 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/bam/hst_svc_mapping.hh" -#include "com/centreon/broker/log_v2.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker::bam; +using com::centreon::common::log_v2::log_v2; /** * Get host ID by its name. @@ -45,10 +46,12 @@ std::pair hst_svc_mapping::get_service_id( std::string const& hst, std::string const& svc) const { auto it{_mapping.find(std::make_pair(hst, svc))}; - if (it == _mapping.end()) - log_v2::bam()->debug( + if (it == _mapping.end()) { + auto logger = log_v2::instance().get(log_v2::BAM); + logger->debug( "hst_svc_mapping: service id for host: {} ; service: {} not found", hst, svc); + } return it != _mapping.end() ? it->second : std::make_pair(0u, 0u); } diff --git a/broker/bam/src/kpi.cc b/broker/bam/src/kpi.cc index e29dc0d0997..550793583a9 100644 --- a/broker/bam/src/kpi.cc +++ b/broker/bam/src/kpi.cc @@ -19,7 +19,6 @@ #include "com/centreon/broker/bam/kpi.hh" #include "com/centreon/broker/bam/ba.hh" -#include "com/centreon/broker/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::bam; @@ -29,8 +28,11 @@ static constexpr double eps = 0.000001; /** * Constructor. */ -kpi::kpi(uint32_t kpi_id, uint32_t ba_id, const std::string& name) - : _id(kpi_id), _ba_id(ba_id), _name(name) {} +kpi::kpi(uint32_t kpi_id, + uint32_t ba_id, + const std::string& name, + const std::shared_ptr& logger) + : computable(logger), _id(kpi_id), _ba_id(ba_id), _name(name) {} /** * Get KPI ID. @@ -65,7 +67,7 @@ timestamp kpi::get_last_state_change() const { * @param[in] e The kpi event. */ void kpi::set_initial_event(const KpiEvent& e) { - log_v2::bam()->trace("bam: kpi::set_initial_event"); + _logger->trace("bam: kpi::set_initial_event"); if (!_event) { _event = e; impact_values impacts; diff --git a/broker/bam/src/kpi_ba.cc b/broker/bam/src/kpi_ba.cc index 463447dcd14..9b6d8c05b15 100644 --- a/broker/bam/src/kpi_ba.cc +++ b/broker/bam/src/kpi_ba.cc @@ -19,16 +19,20 @@ #include "com/centreon/broker/bam/kpi_ba.hh" #include "com/centreon/broker/bam/ba.hh" -#include "com/centreon/broker/log_v2.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::bam; +using log_v2 = com::centreon::common::log_v2::log_v2; /** * Default constructor. */ -kpi_ba::kpi_ba(uint32_t kpi_id, uint32_t ba_id, const std::string& ba_name) - : kpi(kpi_id, ba_id, ba_name) {} +kpi_ba::kpi_ba(uint32_t kpi_id, + uint32_t ba_id, + const std::string& ba_name, + const std::shared_ptr& logger) + : kpi(kpi_id, ba_id, ba_name, logger) {} /** * Get the impact introduced by a CRITICAL state of the BA. @@ -74,8 +78,8 @@ void kpi_ba::impact_soft(impact_values& soft_impact) { * @param[in] my_ba Linked BA. */ void kpi_ba::link_ba(std::shared_ptr& my_ba) { - log_v2::bam()->trace("kpi ba ({}, {}) linked to ba {} {}", _id, _ba_id, - my_ba->get_name(), my_ba->get_id()); + _logger->trace("kpi ba ({}, {}) linked to ba {} {}", _id, _ba_id, + my_ba->get_name(), my_ba->get_id()); _ba = my_ba; } @@ -110,8 +114,8 @@ void kpi_ba::set_impact_unknown(double impact) { * Unlink from BA. */ void kpi_ba::unlink_ba() { - log_v2::bam()->trace("kpi ba ({}, {}) unlinked from ba {} {}", _id, _ba_id, - _ba->get_name(), _ba->get_id()); + _logger->trace("kpi ba ({}, {}) unlinked from ba {} {}", _id, _ba_id, + _ba->get_name(), _ba->get_id()); _ba.reset(); } @@ -158,7 +162,7 @@ void kpi_ba::visit(io::stream* visitor) { // Generate status event. { - log_v2::bam()->debug("Generating kpi status {} for BA {}", _id, _ba_id); + _logger->debug("Generating kpi status {} for BA {}", _id, _ba_id); std::shared_ptr status{std::make_shared()}; KpiStatus& ev(status->mut_obj()); ev.set_kpi_id(_id); @@ -274,13 +278,13 @@ bool kpi_ba::in_downtime() const { * @param visitor The visitor to handle events. */ void kpi_ba::update_from(computable* child, io::stream* visitor) { - log_v2::bam()->trace("kpi_ba::update_from"); + _logger->trace("kpi_ba::update_from"); // It is useless to maintain a cache of BA values in this class, as // the ba class already cache most of them. if (child == _ba.get()) { // Logging. - log_v2::bam()->debug( - "BAM: BA {} KPI {} is getting notified of child update", _ba_id, _id); + _logger->debug("BAM: BA {} KPI {} is getting notified of child update", + _ba_id, _id); // Generate status event. visit(visitor); diff --git a/broker/bam/src/kpi_boolexp.cc b/broker/bam/src/kpi_boolexp.cc index 1e0aabbed23..79719077fb8 100644 --- a/broker/bam/src/kpi_boolexp.cc +++ b/broker/bam/src/kpi_boolexp.cc @@ -20,7 +20,6 @@ #include "com/centreon/broker/bam/bool_expression.hh" #include "com/centreon/broker/bam/impact_values.hh" #include "com/centreon/broker/bam/internal.hh" -#include "com/centreon/broker/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::bam; @@ -30,8 +29,9 @@ using namespace com::centreon::broker::bam; */ kpi_boolexp::kpi_boolexp(uint32_t kpi_id, uint32_t ba_id, - const std::string& bool_name) - : kpi(kpi_id, ba_id, bool_name) {} + const std::string& bool_name, + const std::shared_ptr& logger) + : kpi(kpi_id, ba_id, bool_name, logger) {} /** * Return true if in downtime. @@ -118,7 +118,7 @@ void kpi_boolexp::visit(io::stream* visitor) { if (!_event) _open_new_event(visitor, values.get_nominal(), state); // If state changed, close event and open a new one. - else if (state != _event->status()) { + else if (static_cast(state) != _event->status()) { _event->set_end_time(::time(nullptr)); visitor->write(std::make_shared(std::move(*_event))); _event.reset(); @@ -203,17 +203,16 @@ void kpi_boolexp::_update_state() { uint32_t id = _boolexp->get_id(); if (_boolexp->state_known()) { _current_state = _boolexp->get_state(); - log_v2::bam()->trace( - "BAM: kpi {} boolean expression: state (known) value: {}", id, - static_cast(_current_state)); + _logger->trace("BAM: kpi {} boolean expression: state (known) value: {}", + id, static_cast(_current_state)); } else if (_event) { _current_state = static_cast(_event->status()); - log_v2::bam()->trace( + _logger->trace( "BAM: kpi {} boolean expression: state from internal event: {}", id, static_cast(_current_state)); } else { _current_state = _boolexp->get_state(); - log_v2::bam()->trace( + _logger->trace( "BAM: kpi {} boolean expression: state value still taken from " "boolexp: {}", id, static_cast(_current_state)); @@ -236,7 +235,7 @@ bool kpi_boolexp::ok_state() const { * @param visitor The visitor to handle events. */ void kpi_boolexp::update_from(computable* child, io::stream* visitor) { - log_v2::bam()->trace("kpi_boolexp::update_from"); + _logger->trace("kpi_boolexp::update_from"); // It is useless to maintain a cache of boolean expression values in // this class, as the bool_expression class already cache most of them. if (child == _boolexp.get()) { @@ -244,7 +243,7 @@ void kpi_boolexp::update_from(computable* child, io::stream* visitor) { // Generate status event. _update_state(); visit(visitor); - log_v2::bam()->debug( + _logger->debug( "BAM: boolean expression KPI {} is getting notified of child update " "old_state={}, new_state={}", _id, static_cast(old_state), diff --git a/broker/bam/src/kpi_service.cc b/broker/bam/src/kpi_service.cc index 3e79ed2242b..e689dbb03fa 100644 --- a/broker/bam/src/kpi_service.cc +++ b/broker/bam/src/kpi_service.cc @@ -23,16 +23,18 @@ #include "com/centreon/broker/bam/impact_values.hh" #include "com/centreon/broker/bam/internal.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/neb/acknowledgement.hh" #include "com/centreon/broker/neb/downtime.hh" #include "com/centreon/broker/neb/service_status.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::bam; +using log_v2 = com::centreon::common::log_v2::log_v2; + static constexpr bool time_is_undefined(uint64_t t) { return t == 0 || t == static_cast(-1); } @@ -44,8 +46,9 @@ kpi_service::kpi_service(uint32_t kpi_id, uint32_t ba_id, uint32_t host_id, uint32_t service_id, - const std::string& host_serv) - : kpi(kpi_id, ba_id, host_serv), + const std::string& host_serv, + const std::shared_ptr& logger) + : kpi(kpi_id, ba_id, host_serv, logger), _host_id(host_id), _service_id(service_id), _acknowledged(false), @@ -168,13 +171,12 @@ bool kpi_service::is_acknowledged() const { void kpi_service::service_update(const service_state& s) { // Log message. - log_v2::bam()->debug("BAM: Service KPI {} is restored from persistent cache", - _id); + _logger->debug("BAM: Service KPI {} is restored from persistent cache", _id); // Update information. if (!time_is_undefined(s.last_check)) { _last_check = s.last_check; - log_v2::bam()->trace( + _logger->trace( "service kpi {} last check updated with status last check {}", _id, s.last_check); } @@ -204,7 +206,7 @@ void kpi_service::service_update( if (status && status->host_id == _host_id && status->service_id == _service_id) { // Log message. - log_v2::bam()->debug( + _logger->debug( "BAM: KPI {} is getting notified of service ({}, {}) update (state: " "{} hard state: {})", _id, _host_id, _service_id, status->current_state, @@ -214,13 +216,13 @@ void kpi_service::service_update( if (status->last_check.is_null()) { if (_last_check.is_null()) { _last_check = status->last_update; - log_v2::bam()->trace( + _logger->trace( "service kpi {} last check updated with status last update {}", _id, static_cast(status->last_update)); } } else { _last_check = status->last_check; - log_v2::bam()->trace( + _logger->trace( "service kpi {} last check updated with status last check {}", _id, static_cast(status->last_check)); } @@ -255,7 +257,7 @@ void kpi_service::service_update(const std::shared_ptr& status, status->obj().service_id() == _service_id) { auto& o = status->obj(); // Log message. - log_v2::bam()->debug( + _logger->debug( "BAM: KPI {} is getting notified of service ({}, {}) update (state: " "{})", _id, _host_id, _service_id, static_cast(o.state())); @@ -264,13 +266,13 @@ void kpi_service::service_update(const std::shared_ptr& status, if (o.last_check() == 0 || o.last_check() == -1) { if (_last_check.is_null()) { _last_check = std::time(nullptr); - log_v2::bam()->trace( + _logger->trace( "service kpi {} last check updated with status last update {}", _id, static_cast(_last_check)); } } else { _last_check = o.last_check(); - log_v2::bam()->trace( + _logger->trace( "service kpi {} last check updated with status last check {}", _id, o.last_check()); } @@ -304,7 +306,7 @@ void kpi_service::service_update( status->obj().service_id() == _service_id) { auto& o = status->obj(); // Log message. - log_v2::bam()->debug( + _logger->debug( "BAM: KPI {} is getting notified of service ({}, {}) update (state: " "{} hard state: {})", _id, _host_id, _service_id, static_cast(o.state()), @@ -314,13 +316,13 @@ void kpi_service::service_update( if (o.last_check() == 0 || o.last_check() == -1) { if (_last_check.is_null()) { _last_check = std::time(nullptr); - log_v2::bam()->trace( + _logger->trace( "service kpi {} last check updated with status last update {}", _id, static_cast(_last_check)); } } else { _last_check = o.last_check(); - log_v2::bam()->trace( + _logger->trace( "service kpi {} last check updated with status last check {}", _id, o.last_check()); } @@ -354,7 +356,7 @@ void kpi_service::service_update( const std::shared_ptr& ack, io::stream* visitor) { // Log message. - log_v2::bam()->debug( + _logger->debug( "BAM: KPI {} is getting a pb acknowledgement event for service ({}, {}) " "entry_time {} ; deletion_time {}", _id, _host_id, _service_id, ack->obj().entry_time(), @@ -383,7 +385,7 @@ void kpi_service::service_update( const std::shared_ptr& ack, io::stream* visitor) { // Log message. - log_v2::bam()->debug( + _logger->debug( "BAM: KPI {} is getting an acknowledgement event for service ({}, {}) " "entry_time {} ; deletion_time {}", _id, _host_id, _service_id, ack->entry_time, ack->deletion_time); @@ -410,31 +412,36 @@ void kpi_service::service_update( */ void kpi_service::service_update(const std::shared_ptr& dt, io::stream* visitor) { - log_v2::bam()->info("kpi_service:service_update on downtime {}: was started {} ; actual end time {}", + _logger->info( + "kpi_service:service_update on downtime {}: was started {} ; actual end " + "time {}", dt->internal_id, dt->was_started, dt->actual_end_time.get_time_t()); // Update information. bool downtimed = dt->was_started && dt->actual_end_time.is_null(); bool changed = false; if (_downtime_ids.contains(dt->internal_id) && dt->deletion_time.is_null()) { - log_v2::bam()->trace("Downtime {} already handled in this kpi service", - dt->internal_id); + _logger->trace("Downtime {} already handled in this kpi service", + dt->internal_id); return; } - log_v2::bam()->info("kpi_service:service_update on downtime {}: was started {} ; actual end time {} ; downtimed {}", - dt->internal_id, dt->was_started, dt->actual_end_time.get_time_t(), downtimed); + _logger->info( + "kpi_service:service_update on downtime {}: was started {} ; actual end " + "time {} ; downtimed {}", + dt->internal_id, dt->was_started, dt->actual_end_time.get_time_t(), + downtimed); if (downtimed) { - log_v2::bam()->trace("adding in kpi service the impacting downtime {}", - dt->internal_id); + _logger->trace("adding in kpi service the impacting downtime {}", + dt->internal_id); _downtime_ids.insert(dt->internal_id); if (!_downtimed) { _downtimed = true; changed = true; } } else { - log_v2::bam()->trace("removing from kpi service the impacting downtime {}", - dt->internal_id); + _logger->trace("removing from kpi service the impacting downtime {}", + dt->internal_id); _downtime_ids.erase(dt->internal_id); bool new_downtimed = !_downtime_ids.empty(); if (new_downtimed != _downtimed) { @@ -445,12 +452,12 @@ void kpi_service::service_update(const std::shared_ptr& dt, if (!_event || _event->in_downtime() != _downtimed) { _last_check = _downtimed ? dt->actual_start_time : dt->actual_end_time; - log_v2::bam()->trace("kpi service {} update, last check set to {}", _id, - _last_check); + _logger->trace("kpi service {} update, last check set to {}", _id, + _last_check); } // Log message. - log_v2::bam()->debug( + _logger->debug( "BAM: KPI {} is getting notified of a downtime ({}) on its service ({}, " "{}), in downtime: {} at {}", _id, dt->internal_id, _host_id, _service_id, _downtimed, _last_check); @@ -482,18 +489,18 @@ void kpi_service::service_update(const std::shared_ptr& dt, if (_downtime_ids.contains(downtime.id()) && time_is_undefined(downtime.deletion_time())) { - log_v2::bam()->trace("Downtime {} already handled in this kpi service", - downtime.id()); + _logger->trace("Downtime {} already handled in this kpi service", + downtime.id()); return; } if (downtimed) { - log_v2::bam()->trace("adding in kpi service the impacting downtime {}", - downtime.id()); + _logger->trace("adding in kpi service the impacting downtime {}", + downtime.id()); _downtime_ids.insert(downtime.id()); } else { - log_v2::bam()->trace("removing from kpi service the impacting downtime {}", - downtime.id()); + _logger->trace("removing from kpi service the impacting downtime {}", + downtime.id()); _downtime_ids.erase(downtime.id()); bool new_downtimed = !_downtime_ids.empty(); if (new_downtimed != _downtimed) { @@ -505,12 +512,12 @@ void kpi_service::service_update(const std::shared_ptr& dt, if (!_event || _event->in_downtime() != _downtimed) { _last_check = _downtimed ? downtime.actual_start_time() : downtime.actual_end_time(); - log_v2::bam()->trace("kpi service {} update, last check set to {}", _id, - _last_check); + _logger->trace("kpi service {} update, last check set to {}", _id, + _last_check); } // Log message. - log_v2::bam()->debug( + _logger->debug( "BAM: KPI {} is getting notified of a downtime ({}) on its service ({}, " "{}), in downtime: {} at {}", _id, downtime.id(), _host_id, _service_id, _downtimed, _last_check); @@ -615,8 +622,7 @@ void kpi_service::visit(io::stream* visitor) { // If no event was cached, create one. if (!_event) { if (!_last_check.is_null()) { - log_v2::bam()->trace( - "BAM: kpi_service::visit no event => creation of one"); + _logger->trace("BAM: kpi_service::visit no event => creation of one"); _open_new_event(visitor, hard_values); } } @@ -624,12 +630,12 @@ void kpi_service::visit(io::stream* visitor) { else if (_last_check.get_time_t() >= static_cast(_event->start_time()) && (_downtimed != _event->in_downtime() || - _state_hard != _event->status())) { - log_v2::bam()->trace( + static_cast(_state_hard) != _event->status())) { + _logger->trace( "BAM: kpi_service::visit event needs update downtime: {}, state: " "{}", _downtimed != _event->in_downtime(), - _state_hard != _event->status()); + static_cast(_state_hard) != _event->status()); _event->set_end_time(_last_check); visitor->write(std::make_shared(std::move(*_event))); _open_new_event(visitor, hard_values); @@ -638,7 +644,7 @@ void kpi_service::visit(io::stream* visitor) { // Generate status event. { - log_v2::bam()->debug("Generating kpi status {} for service", _id); + _logger->debug("Generating kpi status {} for service", _id); auto status{std::make_shared()}; KpiStatus& ev(status->mut_obj()); ev.set_kpi_id(_id); @@ -654,7 +660,7 @@ void kpi_service::visit(io::stream* visitor) { ev.set_last_state_change(get_last_state_change()); ev.set_last_impact(_downtimed ? hard_values.get_downtime() : hard_values.get_nominal()); - log_v2::bam()->trace( + _logger->trace( "Writing kpi status {}: in downtime: {} ; last state changed: {} ; " "state: {}", _id, ev.in_downtime(), static_cast(ev.last_state_change()), @@ -698,9 +704,8 @@ void kpi_service::_open_new_event(io::stream* visitor, _event->set_output(_output); _event->set_perfdata(_perfdata); _event->set_status(com::centreon::broker::State(_state_hard)); - log_v2::bam()->trace( - "BAM: New BI event for kpi {}, ba {}, in downtime {} since {}", _id, - _ba_id, _downtimed, _last_check); + _logger->trace("BAM: New BI event for kpi {}, ba {}, in downtime {} since {}", + _id, _ba_id, _downtimed, _last_check); if (visitor) { /* We make a real copy because the writing into the DB is asynchronous and * so the event could have changed... */ @@ -715,7 +720,7 @@ void kpi_service::_open_new_event(io::stream* visitor, */ void kpi_service::set_initial_event(const KpiEvent& e) { kpi::set_initial_event(e); - log_v2::bam()->trace( + _logger->trace( "BAM: set initial event from kpi event {} (start time {} ; in downtime " "{})", _event->kpi_id(), _event->start_time(), _event->in_downtime()); @@ -740,7 +745,7 @@ bool kpi_service::ok_state() const { */ void kpi_service::update_from(computable* child [[maybe_unused]], io::stream* visitor) { - log_v2::bam()->trace("kpi_service::update_from"); + _logger->trace("kpi_service::update_from"); notify_parents_of_change(visitor); } @@ -751,8 +756,8 @@ void kpi_service::update_from(computable* child [[maybe_unused]], * @return A multiline strings with various informations. */ std::string kpi_service::object_info() const { - return fmt::format("KPI {} with service ({}, {})\nstate: {}\ndowntime: {}", get_id(), - get_host_id(), get_service_id(), + return fmt::format("KPI {} with service ({}, {})\nstate: {}\ndowntime: {}", + get_id(), get_host_id(), get_service_id(), static_cast(get_state_hard()), _downtimed); } diff --git a/broker/bam/src/main.cc b/broker/bam/src/main.cc index ee9d9f2d77a..4695537fcaf 100644 --- a/broker/bam/src/main.cc +++ b/broker/bam/src/main.cc @@ -37,11 +37,12 @@ #include "com/centreon/broker/bam/internal.hh" #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/io/protocols.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; +using log_v2 = com::centreon::common::log_v2::log_v2; // Load count. namespace { @@ -90,12 +91,13 @@ bool broker_module_deinit() { */ void broker_module_init(void const* arg) { (void)arg; + auto logger = log_v2::instance().get(log_v2::BAM); // Increment instance number. if (!instances++) { // BAM module. - log_v2::bam()->info("BAM: module for Centreon Broker {} ", - CENTREON_BROKER_VERSION); + logger->info("BAM: module for Centreon Broker {} ", + CENTREON_BROKER_VERSION); io::protocols::instance().reg(bam_module, std::make_shared(), 1, 7); diff --git a/broker/bam/src/monitoring_stream.cc b/broker/bam/src/monitoring_stream.cc index 6ba0b889ea4..c22519d688d 100644 --- a/broker/bam/src/monitoring_stream.cc +++ b/broker/bam/src/monitoring_stream.cc @@ -1,5 +1,5 @@ /** - * Copyright 2014-2023 Centreon + * Copyright 2014-2024 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,7 +30,6 @@ #include "com/centreon/broker/config/applier/state.hh" #include "com/centreon/broker/exceptions/shutdown.hh" #include "com/centreon/broker/io/events.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/fifo_client.hh" #include "com/centreon/broker/multiplexing/publisher.hh" #include "com/centreon/broker/neb/acknowledgement.hh" @@ -41,12 +40,15 @@ #include "com/centreon/broker/timestamp.hh" #include "com/centreon/common/pool.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::bam; using namespace com::centreon::broker::database; +using log_v2 = com::centreon::common::log_v2::log_v2; + /** * Constructor. * @@ -56,12 +58,16 @@ using namespace com::centreon::broker::database; * configuration. * @param[in] cache The persistent cache. */ -monitoring_stream::monitoring_stream(const std::string& ext_cmd_file, - const database_config& db_cfg, - const database_config& storage_db_cfg, - std::shared_ptr cache) +monitoring_stream::monitoring_stream( + const std::string& ext_cmd_file, + const database_config& db_cfg, + const database_config& storage_db_cfg, + std::shared_ptr cache, + const std::shared_ptr& logger) : io::stream("BAM"), _ext_cmd_file(ext_cmd_file), + _logger{logger}, + _applier(_logger), _mysql(db_cfg.auto_commit_conf()), _conf_queries_per_transaction(db_cfg.get_queries_per_transaction()), _pending_events(0), @@ -69,7 +75,7 @@ monitoring_stream::monitoring_stream(const std::string& ext_cmd_file, _storage_db_cfg(storage_db_cfg), _cache(std::move(cache)), _forced_svc_checks_timer{com::centreon::common::pool::io_context()} { - SPDLOG_LOGGER_TRACE(log_v2::bam(), "BAM: monitoring_stream constructor"); + SPDLOG_LOGGER_TRACE(_logger, "BAM: monitoring_stream constructor"); if (!_conf_queries_per_transaction) { _conf_queries_per_transaction = 1; } @@ -86,13 +92,13 @@ monitoring_stream::monitoring_stream(const std::string& ext_cmd_file, */ monitoring_stream::~monitoring_stream() { // save cache - SPDLOG_LOGGER_TRACE(log_v2::bam(), "BAM: monitoring_stream destructor"); + SPDLOG_LOGGER_TRACE(_logger, "BAM: monitoring_stream destructor"); try { _write_cache(); } catch (std::exception const& e) { - log_v2::bam()->error("BAM: can't save cache: '{}'", e.what()); + _logger->error("BAM: can't save cache: '{}'", e.what()); } - SPDLOG_LOGGER_DEBUG(log_v2::bam(), "BAM: monitoring_stream destruction done"); + SPDLOG_LOGGER_DEBUG(_logger, "BAM: monitoring_stream destruction done"); } /** @@ -104,7 +110,7 @@ int32_t monitoring_stream::flush() { _execute(); _pending_request = 0; int retval = _pending_events; - SPDLOG_LOGGER_TRACE(log_v2::bam(), "BAM: monitoring_stream flush: {} events", + SPDLOG_LOGGER_TRACE(_logger, "BAM: monitoring_stream flush: {} events", retval); _pending_events = 0; return retval; @@ -117,12 +123,12 @@ int32_t monitoring_stream::flush() { */ int32_t monitoring_stream::stop() { int32_t retval = flush(); - log_v2::core()->info("monitoring stream: stopped with {} events acknowledged", - retval); + _logger->info("monitoring stream: stopped with {} events acknowledged", + retval); /* I want to be sure the timer is really stopped. */ std::promise p; { - log_v2::bam()->info( + _logger->info( "bam: monitoring_stream - waiting for forced service checks to be " "done"); std::lock_guard lck(_forced_svc_checks_m); @@ -139,7 +145,7 @@ int32_t monitoring_stream::stop() { } p.get_future().wait(); /* Now, it is really cancelled. */ - log_v2::bam()->info("bam: monitoring_stream - stop finished"); + _logger->info("bam: monitoring_stream - stop finished"); return retval; } @@ -148,7 +154,7 @@ int32_t monitoring_stream::stop() { * Generate default state. */ void monitoring_stream::initialize() { - SPDLOG_LOGGER_TRACE(log_v2::bam(), "BAM: monitoring_stream initialize"); + SPDLOG_LOGGER_TRACE(_logger, "BAM: monitoring_stream initialize"); multiplexing::publisher pblshr; event_cache_visitor ev_cache; _applier.visit(&ev_cache); @@ -175,9 +181,9 @@ bool monitoring_stream::read(std::shared_ptr& d, time_t deadline) { * Rebuild index and metrics cache. */ void monitoring_stream::update() { - SPDLOG_LOGGER_TRACE(log_v2::bam(), "BAM: monitoring_stream update"); + SPDLOG_LOGGER_TRACE(_logger, "BAM: monitoring_stream update"); try { - configuration::state s; + configuration::state s{_logger}; configuration::reader_v2 r(_mysql, _storage_db_cfg); r.read(s); _applier.apply(s); @@ -354,8 +360,8 @@ struct kpi_binder { * * @return Number of events acknowledged. */ -int monitoring_stream::write(std::shared_ptr const& data) { - SPDLOG_LOGGER_TRACE(log_v2::bam(), "BAM: monitoring_stream write {}", *data); +int monitoring_stream::write(const std::shared_ptr& data) { + SPDLOG_LOGGER_TRACE(_logger, "BAM: monitoring_stream write {}", *data); // Take this event into account. ++_pending_events; @@ -372,7 +378,7 @@ int monitoring_stream::write(std::shared_ptr const& data) { } }; - SPDLOG_LOGGER_TRACE(log_v2::bam(), "BAM: {} pending events", _pending_events); + SPDLOG_LOGGER_TRACE(_logger, "BAM: {} pending events", _pending_events); // Process service status events. switch (data->type()) { @@ -381,7 +387,7 @@ int monitoring_stream::write(std::shared_ptr const& data) { std::shared_ptr ss( std::static_pointer_cast(data)); SPDLOG_LOGGER_TRACE( - log_v2::bam(), + _logger, "BAM: processing service status (host: {}, service: {}, hard state " "{}, " "current state {})", @@ -395,7 +401,7 @@ int monitoring_stream::write(std::shared_ptr const& data) { auto ss = std::static_pointer_cast(data); auto& o = ss->obj(); SPDLOG_LOGGER_TRACE( - log_v2::bam(), + _logger, "BAM: processing pb service status (host: {}, service: {}, hard " "state {}, current state {})", o.host_id(), o.service_id(), o.last_hard_state(), o.state()); @@ -408,7 +414,7 @@ int monitoring_stream::write(std::shared_ptr const& data) { auto s = std::static_pointer_cast(data); auto& o = s->obj(); SPDLOG_LOGGER_TRACE( - log_v2::bam(), + _logger, "BAM: processing pb service (host: {}, service: {}, hard " "state {}, current state {})", o.host_id(), o.service_id(), o.last_hard_state(), o.state()); @@ -420,7 +426,7 @@ int monitoring_stream::write(std::shared_ptr const& data) { case neb::pb_acknowledgement::static_type(): { std::shared_ptr ack( std::static_pointer_cast(data)); - SPDLOG_LOGGER_TRACE(log_v2::bam(), + SPDLOG_LOGGER_TRACE(_logger, "BAM: processing acknowledgement on service ({}, {})", ack->obj().host_id(), ack->obj().service_id()); multiplexing::publisher pblshr; @@ -431,7 +437,7 @@ int monitoring_stream::write(std::shared_ptr const& data) { case neb::acknowledgement::static_type(): { std::shared_ptr ack( std::static_pointer_cast(data)); - SPDLOG_LOGGER_TRACE(log_v2::bam(), + SPDLOG_LOGGER_TRACE(_logger, "BAM: processing acknowledgement on service ({}, {})", ack->host_id, ack->service_id); multiplexing::publisher pblshr; @@ -443,7 +449,7 @@ int monitoring_stream::write(std::shared_ptr const& data) { std::shared_ptr dt( std::static_pointer_cast(data)); SPDLOG_LOGGER_TRACE( - log_v2::bam(), + _logger, "BAM: processing downtime ({}) on service ({}, {}) started: {}, " "stopped: {}", dt->internal_id, dt->host_id, dt->service_id, dt->was_started, @@ -457,7 +463,7 @@ int monitoring_stream::write(std::shared_ptr const& data) { std::shared_ptr dt( std::static_pointer_cast(data)); auto& downtime = dt->obj(); - SPDLOG_LOGGER_TRACE(log_v2::bam(), + SPDLOG_LOGGER_TRACE(_logger, "BAM: processing downtime (pb) ({}) on service " "({}, {}) started: {}, " "stopped: {}", @@ -483,7 +489,7 @@ int monitoring_stream::write(std::shared_ptr const& data) { std::pair ba_svc_name( _ba_mapping.get_service(status->ba_id)); if (ba_svc_name.first.empty() || ba_svc_name.second.empty()) { - log_v2::bam()->error( + _logger->error( "BAM: could not trigger check of virtual service of BA {}:" "host name and service description were not found", status->ba_id); @@ -510,7 +516,7 @@ int monitoring_stream::write(std::shared_ptr const& data) { std::pair ba_svc_name( _ba_mapping.get_service(status.ba_id())); if (ba_svc_name.first.empty() || ba_svc_name.second.empty()) { - log_v2::bam()->error( + _logger->error( "BAM: could not trigger check of virtual service of BA {}:" "host name and service description were not found", status.ba_id()); @@ -538,7 +544,7 @@ int monitoring_stream::write(std::shared_ptr const& data) { inherited_downtime const& dwn = *std::static_pointer_cast(data); SPDLOG_LOGGER_TRACE( - log_v2::bam(), "BAM: processing inherited downtime (ba id {}, now {}", + _logger, "BAM: processing inherited downtime (ba id {}, now {}", dwn.ba_id, now); if (dwn.in_downtime) cmd = fmt::format( @@ -562,8 +568,7 @@ int monitoring_stream::write(std::shared_ptr const& data) { pb_inherited_downtime const& dwn = *std::static_pointer_cast(data); SPDLOG_LOGGER_TRACE( - log_v2::bam(), - "BAM: processing pb inherited downtime (ba id {}, now {}", + _logger, "BAM: processing pb inherited downtime (ba id {}, now {}", dwn.obj().ba_id(), now); if (dwn.obj().in_downtime()) cmd = fmt::format( @@ -583,7 +588,7 @@ int monitoring_stream::write(std::shared_ptr const& data) { _write_external_command(cmd); } break; case extcmd::pb_ba_info::static_type(): { - log_v2::bam()->info("BAM: dump BA"); + _logger->info("BAM: dump BA"); extcmd::pb_ba_info const& e = *std::static_pointer_cast(data); auto& obj = e.obj(); @@ -591,7 +596,7 @@ int monitoring_stream::write(std::shared_ptr const& data) { if (ba) ba->dump(obj.output_file()); else - log_v2::bam()->error( + _logger->error( "extcmd: Unable to get info about BA {} - it doesn't exist", obj.id()); } break; @@ -602,13 +607,13 @@ int monitoring_stream::write(std::shared_ptr const& data) { // if uncommited request, we can't yet acknowledge if (_pending_request) { if (_pending_events >= 10 * _conf_queries_per_transaction) { - log_v2::bam()->trace( + _logger->trace( "BAM: monitoring_stream write: too many pending events =>flush and " "acknowledge {} events", _pending_events); return flush(); } - log_v2::bam()->trace( + _logger->trace( "BAM: monitoring_stream write: 0 events (request pending) {} to " "acknowledge", _pending_events); @@ -616,7 +621,7 @@ int monitoring_stream::write(std::shared_ptr const& data) { } int retval = _pending_events; _pending_events = 0; - log_v2::bam()->trace("BAM: monitoring_stream write: {} events", retval); + _logger->trace("BAM: monitoring_stream write: {} events", retval); return retval; } @@ -625,7 +630,7 @@ int monitoring_stream::write(std::shared_ptr const& data) { */ void monitoring_stream::_prepare() { if (_mysql.support_bulk_statement()) { - log_v2::bam()->trace("BAM: monitoring stream _prepare"); + _logger->trace("BAM: monitoring stream _prepare"); _ba_query = std::make_unique( _mysql, "UPDATE mod_bam SET " @@ -668,7 +673,7 @@ void monitoring_stream::_prepare() { * Rebuilds BA durations/availabilities from BA events. */ void monitoring_stream::_rebuild() { - SPDLOG_LOGGER_TRACE(log_v2::bam(), "BAM: monitoring stream _rebuild"); + SPDLOG_LOGGER_TRACE(_logger, "BAM: monitoring stream _rebuild"); // Get the list of the BAs that should be rebuild. std::vector bas_to_rebuild; { @@ -690,7 +695,7 @@ void monitoring_stream::_rebuild() { if (bas_to_rebuild.empty()) return; - SPDLOG_LOGGER_TRACE(log_v2::bam(), + SPDLOG_LOGGER_TRACE(_logger, "BAM: rebuild asked, sending the rebuild signal"); auto r{std::make_shared( @@ -718,8 +723,8 @@ void monitoring_stream::_rebuild() { void monitoring_stream::_explicitly_send_forced_svc_checks( const boost::system::error_code& ec) { static int count = 0; - SPDLOG_LOGGER_DEBUG(log_v2::bam(), - "BAM: time to send forced service checks {}", count++); + SPDLOG_LOGGER_DEBUG(_logger, "BAM: time to send forced service checks {}", + count++); if (!ec) { if (_timer_forced_svc_checks.empty()) { std::lock_guard lck(_forced_svc_checks_m); @@ -727,17 +732,17 @@ void monitoring_stream::_explicitly_send_forced_svc_checks( } if (!_timer_forced_svc_checks.empty()) { std::lock_guard lock(_ext_cmd_file_m); - log_v2::bam()->trace("opening {}", _ext_cmd_file); + _logger->trace("opening {}", _ext_cmd_file); misc::fifo_client fc(_ext_cmd_file); - SPDLOG_LOGGER_DEBUG(log_v2::bam(), "BAM: {} forced checks to schedule", + SPDLOG_LOGGER_DEBUG(_logger, "BAM: {} forced checks to schedule", _timer_forced_svc_checks.size()); for (auto& p : _timer_forced_svc_checks) { time_t now = time(nullptr); std::string cmd{fmt::format("[{}] SCHEDULE_FORCED_SVC_CHECK;{};{};{}\n", now, p.first, p.second, now)}; - log_v2::bam()->debug("writing '{}' into {}", cmd, _ext_cmd_file); + _logger->debug("writing '{}' into {}", cmd, _ext_cmd_file); if (fc.write(cmd) < 0) { - log_v2::bam()->error( + _logger->error( "BAM: could not write forced service check to command file '{}'", _ext_cmd_file); _forced_svc_checks_timer.expires_after(std::chrono::seconds(5)); @@ -759,7 +764,7 @@ void monitoring_stream::_explicitly_send_forced_svc_checks( void monitoring_stream::_write_forced_svc_check( const std::string& host, const std::string& description) { - SPDLOG_LOGGER_TRACE(log_v2::bam(), + SPDLOG_LOGGER_TRACE(_logger, "BAM: monitoring stream _write_forced_svc_check"); std::lock_guard lck(_forced_svc_checks_m); _forced_svc_checks.emplace(host, description); @@ -775,28 +780,26 @@ void monitoring_stream::_write_forced_svc_check( * @param[in] cmd Command to write to the external command pipe. */ void monitoring_stream::_write_external_command(const std::string& cmd) { - SPDLOG_LOGGER_TRACE(log_v2::bam(), - "BAM: monitoring stream _write_external_command <<{}>>", - cmd); + SPDLOG_LOGGER_TRACE( + _logger, "BAM: monitoring stream _write_external_command <<{}>>", cmd); std::lock_guard lock(_ext_cmd_file_m); misc::fifo_client fc(_ext_cmd_file); if (fc.write(cmd) < 0) { - log_v2::bam()->error( - "BAM: could not write BA check result to command file '{}'", - _ext_cmd_file); + _logger->error("BAM: could not write BA check result to command file '{}'", + _ext_cmd_file); } else - SPDLOG_LOGGER_DEBUG(log_v2::bam(), "BAM: sent external command '{}'", cmd); + SPDLOG_LOGGER_DEBUG(_logger, "BAM: sent external command '{}'", cmd); } /** * Get inherited downtime from the cache. */ void monitoring_stream::_read_cache() { - SPDLOG_LOGGER_TRACE(log_v2::bam(), "BAM: monitoring stream _read_cache"); + SPDLOG_LOGGER_TRACE(_logger, "BAM: monitoring stream _read_cache"); if (_cache == nullptr) - SPDLOG_LOGGER_DEBUG(log_v2::bam(), "BAM: no cache configured"); + SPDLOG_LOGGER_DEBUG(_logger, "BAM: no cache configured"); else { - SPDLOG_LOGGER_DEBUG(log_v2::bam(), "BAM: loading cache"); + SPDLOG_LOGGER_DEBUG(_logger, "BAM: loading cache"); _applier.load_from_cache(*_cache); } } @@ -805,11 +808,11 @@ void monitoring_stream::_read_cache() { * Save inherited downtime to the cache. */ void monitoring_stream::_write_cache() { - SPDLOG_LOGGER_TRACE(log_v2::bam(), "BAM: monitoring stream _write_cache"); + SPDLOG_LOGGER_TRACE(_logger, "BAM: monitoring stream _write_cache"); if (_cache == nullptr) - SPDLOG_LOGGER_DEBUG(log_v2::bam(), "BAM: no cache configured"); + SPDLOG_LOGGER_DEBUG(_logger, "BAM: no cache configured"); else { - SPDLOG_LOGGER_DEBUG(log_v2::bam(), "BAM: saving cache"); + SPDLOG_LOGGER_DEBUG(_logger, "BAM: saving cache"); _applier.save_to_cache(*_cache); } } diff --git a/broker/bam/src/reporting_stream.cc b/broker/bam/src/reporting_stream.cc index 55096d29bf0..58ce9a1eeb2 100644 --- a/broker/bam/src/reporting_stream.cc +++ b/broker/bam/src/reporting_stream.cc @@ -34,29 +34,34 @@ #include "com/centreon/broker/bam/ba.hh" #include "com/centreon/broker/exceptions/shutdown.hh" #include "com/centreon/broker/io/events.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/string.hh" #include "com/centreon/broker/sql/table_max_size.hh" #include "com/centreon/broker/time/timezone_manager.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::exceptions; using namespace com::centreon::broker::bam; using namespace com::centreon::broker::database; +using log_v2 = com::centreon::common::log_v2::log_v2; + /** * Constructor. * * @param[in] db_cfg BAM DB configuration. */ -reporting_stream::reporting_stream(database_config const& db_cfg) +reporting_stream::reporting_stream( + database_config const& db_cfg, + const std::shared_ptr& logger) : io::stream("BAM-BI"), _ack_events(0), _pending_events(0), _mysql(db_cfg), - _processing_dimensions(false) { - SPDLOG_LOGGER_TRACE(log_v2::bam(), "BAM: reporting stream constructor"); + _processing_dimensions(false), + _logger{logger} { + SPDLOG_LOGGER_TRACE(_logger, "BAM: reporting stream constructor"); // Prepare queries. _prepare(); @@ -73,7 +78,8 @@ reporting_stream::reporting_stream(database_config const& db_cfg) _close_all_events(); // Initialize the availabilities thread. - _availabilities = std::make_unique(db_cfg, _timeperiods); + _availabilities = + std::make_unique(db_cfg, _timeperiods, _logger); _availabilities->start_and_wait(); } @@ -81,7 +87,7 @@ reporting_stream::reporting_stream(database_config const& db_cfg) * Destructor. */ reporting_stream::~reporting_stream() { - SPDLOG_LOGGER_TRACE(log_v2::bam(), "BAM: reporting stream destructor"); + SPDLOG_LOGGER_TRACE(_logger, "BAM: reporting stream destructor"); // Terminate the availabilities thread. _availabilities->terminate(); _availabilities->wait(); @@ -119,7 +125,7 @@ void reporting_stream::statistics(nlohmann::json& tree) const { * @return Number of acknowledged events. */ int32_t reporting_stream::flush() { - SPDLOG_LOGGER_TRACE(log_v2::bam(), "BAM: reporting stream flush"); + SPDLOG_LOGGER_TRACE(_logger, "BAM: reporting stream flush"); _commit(); int retval(_ack_events + _pending_events); _ack_events = 0; @@ -134,8 +140,7 @@ int32_t reporting_stream::flush() { */ int32_t reporting_stream::stop() { int32_t retval = flush(); - log_v2::core()->info("reporting stream stopped with {} events acknowledged", - retval); + _logger->info("reporting stream stopped with {} events acknowledged", retval); return retval; } @@ -151,11 +156,11 @@ int reporting_stream::write(std::shared_ptr const& data) { ++_pending_events; assert(data); - if (log_v2::bam()->level() == spdlog::level::trace) { + if (_logger->level() == spdlog::level::trace) { SPDLOG_LOGGER_TRACE( - log_v2::bam(), "BAM: reporting stream write - event of type {}", *data); + _logger, "BAM: reporting stream write - event of type {}", *data); } else { - SPDLOG_LOGGER_DEBUG(log_v2::bam(), + SPDLOG_LOGGER_DEBUG(_logger, "BAM: reporting stream write - event of type {:x}", data->type()); } @@ -229,8 +234,7 @@ int reporting_stream::write(std::shared_ptr const& data) { commit_if_needed(); break; default: - SPDLOG_LOGGER_TRACE(log_v2::bam(), - "BAM: nothing to do with event of type {:x}", + SPDLOG_LOGGER_TRACE(_logger, "BAM: nothing to do with event of type {:x}", data->type()); if (_pending_events == 1) { // no request in transaction => acknowledge right now @@ -252,7 +256,7 @@ int reporting_stream::write(std::shared_ptr const& data) { * @param[in] tp Timeperiod declaration. */ void reporting_stream::_apply(const DimensionTimeperiod& tp) { - SPDLOG_LOGGER_TRACE(log_v2::bam(), "BAM-BI: applying timeperiod {} to cache", + SPDLOG_LOGGER_TRACE(_logger, "BAM-BI: applying timeperiod {} to cache", tp.id()); _timeperiods.add_timeperiod( tp.id(), @@ -272,7 +276,7 @@ void reporting_stream::_close_inconsistent_events(char const* event_type, char const* table, char const* id) { SPDLOG_LOGGER_TRACE( - log_v2::bam(), + _logger, "BAM-BI: reporting stream _close_inconsistent events (type {}, table: " "{}, id: {})", event_type, table, id); @@ -287,7 +291,7 @@ void reporting_stream::_close_inconsistent_events(char const* event_type, id, table)); std::promise promise; std::future future = promise.get_future(); - SPDLOG_LOGGER_TRACE(log_v2::bam(), "reporting_stream: query: '{}'", query); + SPDLOG_LOGGER_TRACE(_logger, "reporting_stream: query: '{}'", query); _mysql.run_query_and_get_result(query, std::move(promise)); try { mysql_result res(future.get()); @@ -307,8 +311,7 @@ void reporting_stream::_close_inconsistent_events(char const* event_type, fmt::format("SELECT start_time FROM {} WHERE {}={} AND start_time>{} " "ORDER BY start_time ASC LIMIT 1", table, id, p.first, p.second)); - SPDLOG_LOGGER_TRACE(log_v2::bam(), "reporting_stream: query: '{}'", - query_str); + SPDLOG_LOGGER_TRACE(_logger, "reporting_stream: query: '{}'", query_str); std::promise promise; std::future future = promise.get_future(); _mysql.run_query_and_get_result(query_str, std::move(promise)); @@ -330,28 +333,27 @@ void reporting_stream::_close_inconsistent_events(char const* event_type, std::string query( fmt::format("UPDATE {} SET end_time={} WHERE {}={} AND start_time={}", table, end_time, id, p.first, p.second)); - SPDLOG_LOGGER_TRACE(log_v2::bam(), "reporting_stream: query: '{}'", - query); + SPDLOG_LOGGER_TRACE(_logger, "reporting_stream: query: '{}'", query); _mysql.run_query(query, database::mysql_error::close_event); } } } void reporting_stream::_close_all_events() { - SPDLOG_LOGGER_TRACE(log_v2::bam(), "reporting stream _close_all_events"); + SPDLOG_LOGGER_TRACE(_logger, "reporting stream _close_all_events"); time_t now(::time(nullptr)); std::string query( fmt::format("UPDATE mod_bam_reporting_ba_events SET end_time={} WHERE " "end_time IS NULL", now)); - SPDLOG_LOGGER_TRACE(log_v2::bam(), "reporting_stream: query: '{}'", query); + SPDLOG_LOGGER_TRACE(_logger, "reporting_stream: query: '{}'", query); _mysql.run_query(query, database::mysql_error::close_ba_events); query = fmt::format( "UPDATE mod_bam_reporting_kpi_events SET end_time={} WHERE end_time IS " "NULL", now); - SPDLOG_LOGGER_TRACE(log_v2::bam(), "reporting_stream: query: '{}'", query); + SPDLOG_LOGGER_TRACE(_logger, "reporting_stream: query: '{}'", query); _mysql.run_query(query, database::mysql_error::close_kpi_events); } @@ -359,7 +361,7 @@ void reporting_stream::_close_all_events() { * Load timeperiods from DB. */ void reporting_stream::_load_timeperiods() { - SPDLOG_LOGGER_TRACE(log_v2::bam(), "reporting stream _load_timeperiods"); + SPDLOG_LOGGER_TRACE(_logger, "reporting stream _load_timeperiods"); // Clear old timeperiods. _timeperiods.clear(); @@ -370,7 +372,7 @@ void reporting_stream::_load_timeperiods() { "thursday, friday, saturday FROM mod_bam_reporting_timeperiods"); std::promise promise; std::future future = promise.get_future(); - SPDLOG_LOGGER_TRACE(log_v2::bam(), "reporting_stream: query: '{}'", query); + SPDLOG_LOGGER_TRACE(_logger, "reporting_stream: query: '{}'", query); _mysql.run_query_and_get_result(query, std::move(promise)); try { mysql_result res(future.get()); @@ -395,7 +397,7 @@ void reporting_stream::_load_timeperiods() { "mod_bam_reporting_timeperiods_exceptions"); std::promise promise; std::future future = promise.get_future(); - SPDLOG_LOGGER_TRACE(log_v2::bam(), "reporting_stream: query: '{}'", query); + SPDLOG_LOGGER_TRACE(_logger, "reporting_stream: query: '{}'", query); _mysql.run_query_and_get_result(query, std::move(promise)); try { mysql_result res(future.get()); @@ -404,7 +406,7 @@ void reporting_stream::_load_timeperiods() { _timeperiods.get_timeperiod(res.value_as_u32(0)); if (!tp) SPDLOG_LOGGER_ERROR( - log_v2::bam(), + _logger, "BAM-BI: could not apply exception to non-existing timeperiod {}", res.value_as_u32(0)); else @@ -423,7 +425,7 @@ void reporting_stream::_load_timeperiods() { " FROM mod_bam_reporting_timeperiods_exclusions"); std::promise promise; std::future future = promise.get_future(); - SPDLOG_LOGGER_TRACE(log_v2::bam(), "reporting_stream: query: '{}'", query); + SPDLOG_LOGGER_TRACE(_logger, "reporting_stream: query: '{}'", query); _mysql.run_query_and_get_result(query, std::move(promise)); try { mysql_result res(future.get()); @@ -434,7 +436,7 @@ void reporting_stream::_load_timeperiods() { _timeperiods.get_timeperiod(res.value_as_u32(1)); if (!tp || !excluded_tp) SPDLOG_LOGGER_ERROR( - log_v2::bam(), + _logger, "BAM-BI: could not apply exclusion of timeperiod {} by " "timeperiod {}: at least one timeperiod does not exist", res.value_as_u32(1), res.value_as_u32(0)); @@ -453,7 +455,7 @@ void reporting_stream::_load_timeperiods() { " FROM mod_bam_reporting_relations_ba_timeperiods"); std::promise promise; std::future future = promise.get_future(); - SPDLOG_LOGGER_TRACE(log_v2::bam(), "reporting_stream: query: '{}'", query); + SPDLOG_LOGGER_TRACE(_logger, "reporting_stream: query: '{}'", query); _mysql.run_query_and_get_result(query, std::move(promise)); try { mysql_result res(future.get()); @@ -473,7 +475,7 @@ void reporting_stream::_load_timeperiods() { * */ void reporting_stream::_load_kpi_ba_events() { - SPDLOG_LOGGER_TRACE(log_v2::bam(), "reporting stream _load_kpi_ba_events"); + SPDLOG_LOGGER_TRACE(_logger, "reporting stream _load_kpi_ba_events"); _ba_event_cache.clear(); _kpi_event_cache.clear(); @@ -482,7 +484,7 @@ void reporting_stream::_load_kpi_ba_events() { "SELECT ba_event_id, ba_id, start_time FROM mod_bam_reporting_ba_events"); std::promise promise; std::future future = promise.get_future(); - SPDLOG_LOGGER_TRACE(log_v2::bam(), "reporting_stream: query: '{}'", query); + SPDLOG_LOGGER_TRACE(_logger, "reporting_stream: query: '{}'", query); _mysql.run_query_and_get_result(query, std::move(promise)); try { mysql_result res(future.get()); @@ -501,7 +503,7 @@ void reporting_stream::_load_kpi_ba_events() { "mod_bam_reporting_kpi_events"; std::promise kpi_promise; std::future kpi_future = kpi_promise.get_future(); - SPDLOG_LOGGER_TRACE(log_v2::bam(), "reporting_stream: query: '{}'", query); + SPDLOG_LOGGER_TRACE(_logger, "reporting_stream: query: '{}'", query); _mysql.run_query_and_get_result(query, std::move(kpi_promise)); try { mysql_result res(kpi_future.get()); @@ -517,6 +519,7 @@ void reporting_stream::_load_kpi_ba_events() { // When bulk statements are available. struct bulk_dimension_kpi_binder { + std::shared_ptr logger; const std::shared_ptr& event; void operator()(database::mysql_bulk_bind& binder) const { if (event->type() == bam::dimension_kpi_event::static_type()) { @@ -533,7 +536,7 @@ struct bulk_dimension_kpi_binder { kpi_name = dk.boolean_name; else if (!dk.meta_service_name.empty()) kpi_name = dk.meta_service_name; - SPDLOG_LOGGER_DEBUG(log_v2::bam(), + SPDLOG_LOGGER_DEBUG(logger, "BAM-BI: processing declaration of KPI {} ('{}')", dk.kpi_id, kpi_name); @@ -595,7 +598,7 @@ struct bulk_dimension_kpi_binder { kpi_name = dk.boolean_name(); else if (!dk.meta_service_name().empty()) kpi_name = dk.meta_service_name(); - SPDLOG_LOGGER_DEBUG(log_v2::bam(), + SPDLOG_LOGGER_DEBUG(logger, "BAM-BI: processing declaration of KPI {} ('{}')", dk.kpi_id(), kpi_name); @@ -649,6 +652,7 @@ struct bulk_dimension_kpi_binder { // When bulk statements are not available. struct dimension_kpi_binder { + std::shared_ptr logger; const std::shared_ptr& event; std::string operator()() const { if (event->type() == bam::dimension_kpi_event::static_type()) { @@ -667,7 +671,7 @@ struct dimension_kpi_binder { kpi_name = dk.meta_service_name; std::string sz_kpi_ba_id = dk.kpi_ba_id ? std::to_string(dk.kpi_ba_id) : "NULL"; - SPDLOG_LOGGER_DEBUG(log_v2::bam(), + SPDLOG_LOGGER_DEBUG(logger, "BAM-BI: processing declaration of KPI {} ('{}')", dk.kpi_id, kpi_name); return fmt::format( @@ -718,7 +722,7 @@ struct dimension_kpi_binder { kpi_name = dk.meta_service_name(); std::string sz_kpi_ba_id = dk.kpi_ba_id() ? std::to_string(dk.kpi_ba_id()) : "NULL"; - SPDLOG_LOGGER_DEBUG(log_v2::bam(), + SPDLOG_LOGGER_DEBUG(logger, "BAM-BI: processing declaration of KPI {} ('{}')", dk.kpi_id(), kpi_name); return fmt::format( @@ -818,7 +822,7 @@ struct kpi_event_update_binder { * Prepare queries. */ void reporting_stream::_prepare() { - SPDLOG_LOGGER_TRACE(log_v2::bam(), "reporting stream _prepare"); + SPDLOG_LOGGER_TRACE(_logger, "reporting stream _prepare"); std::string query{ "INSERT INTO mod_bam_reporting_ba_events (ba_id," "first_level,start_time,end_time,status,in_downtime)" @@ -978,7 +982,7 @@ void reporting_stream::_prepare() { void reporting_stream::_process_ba_event(std::shared_ptr const& e) { bam::ba_event const& be = *std::static_pointer_cast(e); SPDLOG_LOGGER_DEBUG( - log_v2::bam(), + _logger, "BAM-BI: processing event of BA {} (start time {}, end time {}, status " "{}, in downtime {})", be.ba_id, be.start_time, be.end_time, be.status, be.in_downtime); @@ -1074,7 +1078,7 @@ void reporting_stream::_process_pb_ba_event( const BaEvent& be = std::static_pointer_cast(e)->obj(); SPDLOG_LOGGER_DEBUG( - log_v2::bam(), + _logger, "BAM-BI: processing pb_ba_event of BA {} (start time {}, end time {}, " "status " "{}, in downtime {})", @@ -1142,8 +1146,8 @@ void reporting_stream::_process_pb_ba_event( } } catch (std::exception const& e) { throw msg_fmt( - "BAM-BI: could not update event of BA {} " - " starting at {} and ending at {}: {}", + "BAM-BI: could not update event of BA {} starting at {} and ending " + "at {}: {}", be.ba_id(), be.start_time(), be.end_time(), e.what()); } } @@ -1161,7 +1165,7 @@ void reporting_stream::_process_ba_duration_event( std::shared_ptr const& e) { bam::ba_duration_event const& bde = *std::static_pointer_cast(e); - SPDLOG_LOGGER_DEBUG(log_v2::bam(), + SPDLOG_LOGGER_DEBUG(_logger, "BAM-BI: processing BA duration event of BA {} (start " "time {}, end time " "{}, duration {}, sla duration {})", @@ -1221,7 +1225,7 @@ void reporting_stream::_process_pb_ba_duration_event( std::shared_ptr const& e) { const BaDurationEvent& bde = std::static_pointer_cast(e)->obj(); - SPDLOG_LOGGER_DEBUG(log_v2::bam(), + SPDLOG_LOGGER_DEBUG(_logger, "BAM-BI: processing BA duration event of BA {} (start " "time {}, end time " "{}, duration {}, sla duration {})", @@ -1276,13 +1280,13 @@ void reporting_stream::_process_pb_ba_duration_event( void reporting_stream::_process_kpi_event(std::shared_ptr const& e) { bam::kpi_event const& ke = *std::static_pointer_cast(e); SPDLOG_LOGGER_DEBUG( - log_v2::bam(), + _logger, "BAM-BI: processing event of KPI {} (start time {}, end time {}, state " "{}, in downtime {})", ke.kpi_id, ke.start_time, ke.end_time, ke.status, ke.in_downtime); if (ke.start_time.is_null()) { - SPDLOG_LOGGER_ERROR(log_v2::bam(), "BAM_BI invalid null start_time "); + SPDLOG_LOGGER_ERROR(_logger, "BAM_BI invalid null start_time "); return; } id_start kpi_key = std::make_pair( @@ -1350,14 +1354,14 @@ void reporting_stream::_process_pb_kpi_event( const KpiEvent& ke = std::static_pointer_cast(e)->obj(); SPDLOG_LOGGER_DEBUG( - log_v2::bam(), + _logger, "BAM-BI: processing event of KPI {} (start time {}, end time {}, state " "{}, in downtime {})", ke.kpi_id(), ke.start_time(), ke.end_time(), ke.status(), ke.in_downtime()); if (ke.start_time() > std::numeric_limits::max()) { - SPDLOG_LOGGER_ERROR(log_v2::bam(), "BAM_BI invalid start_time {}", + SPDLOG_LOGGER_ERROR(_logger, "BAM_BI invalid start_time {}", ke.start_time()); return; } @@ -1422,8 +1426,7 @@ void reporting_stream::_process_dimension_ba( std::shared_ptr const& e) { bam::dimension_ba_event const& dba = *std::static_pointer_cast(e); - SPDLOG_LOGGER_DEBUG(log_v2::bam(), - "BAM-BI: processing declaration of BA {} ('{}')", + SPDLOG_LOGGER_DEBUG(_logger, "BAM-BI: processing declaration of BA {} ('{}')", dba.ba_id, dba.ba_description); _dimension_ba_insert.bind_value_as_i32(0, dba.ba_id); _dimension_ba_insert.bind_value_as_str( @@ -1450,7 +1453,7 @@ void reporting_stream::_process_pb_dimension_ba( std::shared_ptr const& e) { const DimensionBaEvent& dba = std::static_pointer_cast(e)->obj(); - SPDLOG_LOGGER_DEBUG(log_v2::bam(), + SPDLOG_LOGGER_DEBUG(_logger, "BAM-BI: pb processing declaration of BA {} ('{}')", dba.ba_id(), dba.ba_description()); _dimension_ba_insert.bind_value_as_i32(0, dba.ba_id()); @@ -1478,8 +1481,7 @@ void reporting_stream::_process_dimension_bv( std::shared_ptr const& e) { bam::dimension_bv_event const& dbv = *std::static_pointer_cast(e); - SPDLOG_LOGGER_DEBUG(log_v2::bam(), - "BAM-BI: processing declaration of BV {} ('{}')", + SPDLOG_LOGGER_DEBUG(_logger, "BAM-BI: processing declaration of BV {} ('{}')", dbv.bv_id, dbv.bv_name); _dimension_bv_insert.bind_value_as_i32(0, dbv.bv_id); @@ -1503,7 +1505,7 @@ void reporting_stream::_process_pb_dimension_bv( std::shared_ptr const& e) { const DimensionBvEvent& dbv = std::static_pointer_cast(e)->obj(); - SPDLOG_LOGGER_DEBUG(log_v2::bam(), + SPDLOG_LOGGER_DEBUG(_logger, "BAM-BI: processing pb declaration of BV {} ('{}')", dbv.bv_id(), dbv.bv_name()); @@ -1528,7 +1530,7 @@ void reporting_stream::_process_dimension_ba_bv_relation( std::shared_ptr const& e) { bam::dimension_ba_bv_relation_event const& dbabv = *std::static_pointer_cast(e); - SPDLOG_LOGGER_DEBUG(log_v2::bam(), + SPDLOG_LOGGER_DEBUG(_logger, "BAM-BI: processing relation between BA {} and BV {}", dbabv.ba_id, dbabv.bv_id); @@ -1548,7 +1550,7 @@ void reporting_stream::_process_pb_dimension_ba_bv_relation( const DimensionBaBvRelationEvent& dbabv = std::static_pointer_cast(e) ->obj(); - SPDLOG_LOGGER_DEBUG(log_v2::bam(), + SPDLOG_LOGGER_DEBUG(_logger, "BAM-BI: processing pb relation between BA {} and BV {}", dbabv.ba_id(), dbabv.bv_id()); @@ -1570,15 +1572,14 @@ void reporting_stream::_process_dimension(const std::shared_ptr& e) { case io::events::data_type::value: { bam::dimension_ba_event const& dba = *std::static_pointer_cast(e); - SPDLOG_LOGGER_DEBUG(log_v2::bam(), + SPDLOG_LOGGER_DEBUG(_logger, "BAM-BI: preparing ba dimension {} ('{}' '{}')", dba.ba_id, dba.ba_name, dba.ba_description); } break; case io::events::data_type::value: { bam::dimension_bv_event const& dbv = *std::static_pointer_cast(e); - SPDLOG_LOGGER_DEBUG(log_v2::bam(), - "BAM-BI: preparing bv dimension {} ('{}')", + SPDLOG_LOGGER_DEBUG(_logger, "BAM-BI: preparing bv dimension {} ('{}')", dbv.bv_id, dbv.bv_name); } break; case io::events::data_type< @@ -1587,7 +1588,7 @@ void reporting_stream::_process_dimension(const std::shared_ptr& e) { *std::static_pointer_cast< bam::dimension_ba_bv_relation_event const>(e); SPDLOG_LOGGER_DEBUG( - log_v2::bam(), "BAM-BI: preparing relation between ba {} and bv {}", + _logger, "BAM-BI: preparing relation between ba {} and bv {}", dbabv.ba_id, dbabv.bv_id); } break; case io::events::data_type::value: { @@ -1603,7 +1604,7 @@ void reporting_stream::_process_dimension(const std::shared_ptr& e) { kpi_name = fmt::format("bool: {}", dk.boolean_name); else if (!dk.meta_service_name.empty()) kpi_name = fmt::format("meta: {}", dk.meta_service_name); - SPDLOG_LOGGER_DEBUG(log_v2::bam(), + SPDLOG_LOGGER_DEBUG(_logger, "BAM-BI: preparing declaration of kpi {} ('{}')", dk.kpi_id, kpi_name); } break; @@ -1612,9 +1613,8 @@ void reporting_stream::_process_dimension(const std::shared_ptr& e) { bam::dimension_timeperiod const& tp = *std::static_pointer_cast(e); SPDLOG_LOGGER_DEBUG( - log_v2::bam(), - "BAM-BI: preparing declaration of timeperiod {} ('{}')", tp.id, - tp.name); + _logger, "BAM-BI: preparing declaration of timeperiod {} ('{}')", + tp.id, tp.name); } break; case io::events::data_type< io::bam, bam::de_dimension_ba_timeperiod_relation>::value: { @@ -1622,20 +1622,19 @@ void reporting_stream::_process_dimension(const std::shared_ptr& e) { *std::static_pointer_cast< bam::dimension_ba_timeperiod_relation const>(e); SPDLOG_LOGGER_DEBUG( - log_v2::bam(), - "BAM-BI: preparing relation of BA {} to timeperiod {}", r.ba_id, - r.timeperiod_id); + _logger, "BAM-BI: preparing relation of BA {} to timeperiod {}", + r.ba_id, r.timeperiod_id); } break; default: - SPDLOG_LOGGER_DEBUG(log_v2::bam(), - "BAM-BI: preparing event of type {:x}", e->type()); + SPDLOG_LOGGER_DEBUG(_logger, "BAM-BI: preparing event of type {:x}", + e->type()); break; } _dimension_data_cache.emplace_back(e); } else SPDLOG_LOGGER_WARN( - log_v2::bam(), + _logger, "Dimension of type {:x} not handled because dimension block not " "opened.", e->type()); @@ -1655,8 +1654,7 @@ void reporting_stream::_process_pb_dimension( const DimensionBvEvent& dbv = std::static_pointer_cast(e) ->obj(); - SPDLOG_LOGGER_DEBUG(log_v2::bam(), - "BAM-BI: preparing bv dimension {} ('{}')", + SPDLOG_LOGGER_DEBUG(_logger, "BAM-BI: preparing bv dimension {} ('{}')", dbv.bv_id(), dbv.bv_name()); } break; case pb_dimension_ba_bv_relation_event::static_type(): { @@ -1665,22 +1663,21 @@ void reporting_stream::_process_pb_dimension( bam::pb_dimension_ba_bv_relation_event const>(e) ->obj(); SPDLOG_LOGGER_DEBUG( - log_v2::bam(), "BAM-BI: preparing relation between ba {} and bv {}", + _logger, "BAM-BI: preparing relation between ba {} and bv {}", dbabv.ba_id(), dbabv.bv_id()); } break; case bam::pb_dimension_timeperiod::static_type(): { bam::pb_dimension_timeperiod const& tp = *std::static_pointer_cast(e); SPDLOG_LOGGER_DEBUG( - log_v2::bam(), - "BAM-BI: preparing declaration of timeperiod {} ('{}')", + _logger, "BAM-BI: preparing declaration of timeperiod {} ('{}')", tp.obj().id(), tp.obj().name()); } break; case bam::pb_dimension_ba_event::static_type(): { const DimensionBaEvent& dba = std::static_pointer_cast(e) ->obj(); - SPDLOG_LOGGER_DEBUG(log_v2::bam(), + SPDLOG_LOGGER_DEBUG(_logger, "BAM-BI: preparing ba dimension {} ('{}' '{}')", dba.ba_id(), dba.ba_name(), dba.ba_description()); } break; @@ -1698,7 +1695,7 @@ void reporting_stream::_process_pb_dimension( kpi_name = fmt::format("bool: {}", dk.boolean_name()); else if (!dk.meta_service_name().empty()) kpi_name = fmt::format("meta: {}", dk.meta_service_name()); - SPDLOG_LOGGER_DEBUG(log_v2::bam(), + SPDLOG_LOGGER_DEBUG(_logger, "BAM-BI: preparing declaration of kpi {} ('{}')", dk.kpi_id(), kpi_name); } break; @@ -1708,21 +1705,20 @@ void reporting_stream::_process_pb_dimension( e) ->obj(); SPDLOG_LOGGER_DEBUG( - log_v2::bam(), - "BAM-BI: preparing relation of BA {} to timeperiod {}", r.ba_id(), - r.timeperiod_id()); + _logger, "BAM-BI: preparing relation of BA {} to timeperiod {}", + r.ba_id(), r.timeperiod_id()); } break; default: - SPDLOG_LOGGER_DEBUG(log_v2::bam(), - "BAM-BI: preparing event of type {:x}", e->type()); + SPDLOG_LOGGER_DEBUG(_logger, "BAM-BI: preparing event of type {:x}", + e->type()); break; } _dimension_data_cache.emplace_back(e); } else SPDLOG_LOGGER_WARN( - log_v2::bam(), + _logger, "Dimension of type {:x} not handled because dimension block not " "opened.", e->type()); @@ -1809,12 +1805,12 @@ void reporting_stream::_process_pb_dimension_truncate_signal( void reporting_stream::_process_dimension_truncate_signal(bool update_started) { if (update_started) { _processing_dimensions = true; - SPDLOG_LOGGER_DEBUG(log_v2::bam(), + SPDLOG_LOGGER_DEBUG(_logger, "BAM-BI: processing table truncation signal (opening)"); _dimension_data_cache.clear(); } else { - SPDLOG_LOGGER_DEBUG(log_v2::bam(), + SPDLOG_LOGGER_DEBUG(_logger, "BAM-BI: processing table truncation signal (closing)"); // Lock the availability thread. std::lock_guard lock(*_availabilities); @@ -1831,9 +1827,8 @@ void reporting_stream::_process_dimension_truncate_signal(bool update_started) { for (auto& e : _dimension_data_cache) _dimension_dispatch(e); } catch (std::exception const& e) { - SPDLOG_LOGGER_ERROR(log_v2::bam(), - "BAM-BI: ignored dimension insertion failure: {}", - e.what()); + SPDLOG_LOGGER_ERROR( + _logger, "BAM-BI: ignored dimension insertion failure: {}", e.what()); } _mysql.commit(); @@ -1850,9 +1845,9 @@ void reporting_stream::_process_dimension_truncate_signal(bool update_started) { void reporting_stream::_process_dimension_kpi( std::shared_ptr const& e) { if (_dimension_kpi_insert->is_bulk()) - _dimension_kpi_insert->add_bulk_row(bulk_dimension_kpi_binder{e}); + _dimension_kpi_insert->add_bulk_row(bulk_dimension_kpi_binder{_logger, e}); else - _dimension_kpi_insert->add_multi_row(dimension_kpi_binder{e}); + _dimension_kpi_insert->add_multi_row(dimension_kpi_binder{_logger, e}); } /** @@ -1866,9 +1861,8 @@ void reporting_stream::_process_pb_dimension_timeperiod( const DimensionTimeperiod& tp = std::static_pointer_cast(e)->obj(); SPDLOG_LOGGER_DEBUG( - log_v2::bam(), - "BAM-BI: processing pb declaration of timeperiod {} ('{}')", tp.id(), - tp.name()); + _logger, "BAM-BI: processing pb declaration of timeperiod {} ('{}')", + tp.id(), tp.name()); _dimension_timeperiod_insert.bind_value_as_i32(0, tp.id()); _dimension_timeperiod_insert.bind_value_as_str( 1, misc::string::truncate(tp.name(), @@ -1918,7 +1912,7 @@ void reporting_stream::_process_dimension_timeperiod( std::shared_ptr const& e) { bam::dimension_timeperiod const& tp = *std::static_pointer_cast(e); - SPDLOG_LOGGER_DEBUG(log_v2::bam(), + SPDLOG_LOGGER_DEBUG(_logger, "BAM-BI: processing declaration of timeperiod {} ('{}')", tp.id, tp.name); @@ -1981,7 +1975,7 @@ void reporting_stream::_process_dimension_ba_timeperiod_relation( bam::dimension_ba_timeperiod_relation const& r = *std::static_pointer_cast(e); SPDLOG_LOGGER_DEBUG( - log_v2::bam(), + _logger, "BAM-BI: processing relation of BA {} to timeperiod {} is_default={}", r.ba_id, r.timeperiod_id, r.is_default); @@ -2005,7 +1999,7 @@ void reporting_stream::_process_pb_dimension_ba_timeperiod_relation( std::static_pointer_cast(e) ->obj(); SPDLOG_LOGGER_DEBUG( - log_v2::bam(), + _logger, "BAM-BI: processing relation of BA {} to timeperiod {} is_default={}", r.ba_id(), r.timeperiod_id(), r.is_default()); @@ -2032,7 +2026,7 @@ void reporting_stream::_compute_event_durations(const BaEvent& ev, return; SPDLOG_LOGGER_INFO( - log_v2::bam(), + _logger, "BAM-BI: computing durations of event started at {} and ended at {} on " "BA {}", ev.start_time(), ev.end_time(), ev.ba_id()); @@ -2042,7 +2036,7 @@ void reporting_stream::_compute_event_durations(const BaEvent& ev, _timeperiods.get_timeperiods_by_ba_id(ev.ba_id()); if (timeperiods.empty()) { - SPDLOG_LOGGER_DEBUG(log_v2::bam(), + SPDLOG_LOGGER_DEBUG(_logger, "BAM-BI: no reporting period defined for event " "started at {} and ended " "at {} on BA {}", @@ -2072,7 +2066,7 @@ void reporting_stream::_compute_event_durations(const BaEvent& ev, dur_ev.set_timeperiod_id(tp->get_id()); dur_ev.set_timeperiod_is_default(is_default); SPDLOG_LOGGER_DEBUG( - log_v2::bam(), + _logger, "BAM-BI: durations of event started at {} and ended at {} on BA {} " "were computed for timeperiod {}, duration is {}s, SLA duration is " "{}", @@ -2081,7 +2075,7 @@ void reporting_stream::_compute_event_durations(const BaEvent& ev, visitor->write(to_write); } else SPDLOG_LOGGER_DEBUG( - log_v2::bam(), + _logger, "BAM-BI: event started at {} and ended at {} on BA {} has no " "duration on timeperiod {}", ev.start_time(), ev.end_time(), ev.ba_id(), tp->get_name()); @@ -2098,7 +2092,7 @@ void reporting_stream::_process_rebuild(std::shared_ptr const& e) { const rebuild& r = *std::static_pointer_cast(e); if (r.bas_to_rebuild.empty()) return; - SPDLOG_LOGGER_DEBUG(log_v2::bam(), "BAM-BI: processing rebuild signal"); + SPDLOG_LOGGER_DEBUG(_logger, "BAM-BI: processing rebuild signal"); _update_status("rebuilding: querying ba events"); @@ -2115,8 +2109,7 @@ void reporting_stream::_process_rebuild(std::shared_ptr const& e) { "a.ba_event_id = b.ba_event_id WHERE b.ba_id IN ({})", r.bas_to_rebuild)); - SPDLOG_LOGGER_TRACE(log_v2::bam(), "reporting_stream: query: '{}'", - query); + SPDLOG_LOGGER_TRACE(_logger, "reporting_stream: query: '{}'", query); _mysql.run_query(query, database::mysql_error::delete_ba_durations); } @@ -2130,8 +2123,7 @@ void reporting_stream::_process_rebuild(std::shared_ptr const& e) { r.bas_to_rebuild)); std::promise promise; std::future future = promise.get_future(); - SPDLOG_LOGGER_TRACE(log_v2::bam(), "reporting_stream: query: '{}'", - query); + SPDLOG_LOGGER_TRACE(_logger, "reporting_stream: query: '{}'", query); _mysql.run_query_and_get_result(query, std::move(promise)); try { mysql_result res(future.get()); @@ -2145,7 +2137,7 @@ void reporting_stream::_process_rebuild(std::shared_ptr const& e) { (com::centreon::broker::bam::state)res.value_as_i32(3))); baev->mut_obj().set_in_downtime(res.value_as_bool(4)); ba_events.push_back(baev); - SPDLOG_LOGGER_DEBUG(log_v2::bam(), "BAM-BI: got events of BA {}", + SPDLOG_LOGGER_DEBUG(_logger, "BAM-BI: got events of BA {}", baev->obj().ba_id()); } } catch (std::exception const& e) { @@ -2154,8 +2146,7 @@ void reporting_stream::_process_rebuild(std::shared_ptr const& e) { } } - SPDLOG_LOGGER_INFO(log_v2::bam(), - "BAM-BI: will now rebuild the event durations"); + SPDLOG_LOGGER_INFO(_logger, "BAM-BI: will now rebuild the event durations"); size_t ba_events_num = ba_events.size(); size_t ba_events_curr = 0; @@ -2175,7 +2166,7 @@ void reporting_stream::_process_rebuild(std::shared_ptr const& e) { } SPDLOG_LOGGER_INFO( - log_v2::bam(), + _logger, "BAM-BI: event durations rebuild finished, will rebuild availabilities " "now"); diff --git a/broker/bam/src/service_book.cc b/broker/bam/src/service_book.cc index cbf7447bda2..f80f5c927a4 100644 --- a/broker/bam/src/service_book.cc +++ b/broker/bam/src/service_book.cc @@ -17,7 +17,6 @@ */ #include "com/centreon/broker/bam/service_book.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/bam/internal.hh" #include "com/centreon/broker/neb/downtime.hh" @@ -39,8 +38,8 @@ static constexpr bool time_is_undefined(uint64_t t) { void service_book::listen(uint32_t host_id, uint32_t service_id, service_listener* listnr) { - log_v2::bam()->trace("BAM: service ({}, {}) added to service book", host_id, - service_id); + _logger->trace("BAM: service ({}, {}) added to service book", host_id, + service_id); auto found = _book.find(std::make_pair(host_id, service_id)); if (found == _book.end()) { service_state_listeners sl{{listnr}, @@ -241,7 +240,7 @@ void service_book::save_to_cache(persistent_cache& cache) const { * @param state A ServicesBookState get from the cache. */ void service_book::apply_services_state(const ServicesBookState& state) { - log_v2::bam()->trace("BAM: applying services state from cache"); + _logger->trace("BAM: applying services state from cache"); for (auto& svc : state.service()) { auto found = _book.find(std::make_pair(svc.host_id(), svc.service_id())); if (found == _book.end()) @@ -255,5 +254,5 @@ void service_book::apply_services_state(const ServicesBookState& state) { for (auto l : found->second.listeners) l->service_update(svc_state); } - log_v2::bam()->trace("BAM: Services state applied from cache"); + _logger->trace("BAM: Services state applied from cache"); } diff --git a/broker/bam/src/service_listener.cc b/broker/bam/src/service_listener.cc index 46aa9ccce93..61f60b9564f 100644 --- a/broker/bam/src/service_listener.cc +++ b/broker/bam/src/service_listener.cc @@ -36,11 +36,8 @@ void service_listener::service_update(const service_state& state * @param[out] visitor Visitor. */ void service_listener::service_update( - std::shared_ptr const& status, - io::stream* visitor) { - (void)status; - (void)visitor; -} + const std::shared_ptr& status [[maybe_unused]], + io::stream* visitor [[maybe_unused]]) {} /** * Notify of a service status update. @@ -49,11 +46,8 @@ void service_listener::service_update( * @param[out] visitor Visitor. */ void service_listener::service_update( - const std::shared_ptr& status, - io::stream* visitor) { - (void)status; - (void)visitor; -} + const std::shared_ptr& status [[maybe_unused]], + io::stream* visitor [[maybe_unused]]) {} /** * Notify of a service status update. @@ -62,11 +56,8 @@ void service_listener::service_update( * @param[out] visitor Visitor. */ void service_listener::service_update( - const std::shared_ptr& status, - io::stream* visitor) { - (void)status; - (void)visitor; -} + const std::shared_ptr& status [[maybe_unused]], + io::stream* visitor [[maybe_unused]]) {} /** * Notify of a protobuf acknowledgement. @@ -75,11 +66,8 @@ void service_listener::service_update( * @param[out] visitor Visitor. */ void service_listener::service_update( - const std::shared_ptr& ack, - io::stream* visitor) { - (void)ack; - (void)visitor; -} + const std::shared_ptr& ack [[maybe_unused]], + io::stream* visitor [[maybe_unused]]) {} /** * Notify of an acknowledgement. @@ -88,11 +76,8 @@ void service_listener::service_update( * @param[out] visitor Visitor. */ void service_listener::service_update( - std::shared_ptr const& ack, - io::stream* visitor) { - (void)ack; - (void)visitor; -} + const std::shared_ptr& ack [[maybe_unused]], + io::stream* visitor [[maybe_unused]]) {} /** * Notify of a downtime. @@ -100,11 +85,9 @@ void service_listener::service_update( * @param[in] dt Downtime. * @param[out] visitor Visitor. */ -void service_listener::service_update(std::shared_ptr const& dt, - io::stream* visitor) { - (void)dt; - (void)visitor; -} +void service_listener::service_update(const std::shared_ptr& dt + [[maybe_unused]], + io::stream* visitor [[maybe_unused]]) {} /** * Notify of a downtime (protobuf). @@ -113,8 +96,5 @@ void service_listener::service_update(std::shared_ptr const& dt, * @param[out] visitor Visitor. */ void service_listener::service_update( - const std::shared_ptr& dt, - io::stream* visitor) { - (void)dt; - (void)visitor; -} + const std::shared_ptr& dt [[maybe_unused]], + io::stream* visitor [[maybe_unused]]) {} diff --git a/broker/bam/src/timeperiod_map.cc b/broker/bam/src/timeperiod_map.cc index afe03e4b14e..8a70dc40ceb 100644 --- a/broker/bam/src/timeperiod_map.cc +++ b/broker/bam/src/timeperiod_map.cc @@ -17,13 +17,15 @@ */ #include "com/centreon/broker/bam/timeperiod_map.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::bam; +using com::centreon::common::log_v2::log_v2; + /** * Default constructor. */ @@ -139,7 +141,7 @@ timeperiod_map::get_timeperiods_by_ba_id(uint32_t ba_id) const { bool is_default = found.first->second.second; time::timeperiod::ptr tp = get_timeperiod(tp_id); if (!tp) { - SPDLOG_LOGGER_ERROR(log_v2::bam(), + SPDLOG_LOGGER_ERROR(log_v2::instance().get(log_v2::BAM), "BAM-BI: could not find the timeperiod {} in cache " "for ba {}, check timeperiod table in conf db", tp_id, ba_id); diff --git a/broker/bam/test/ba/kpi_ba.cc b/broker/bam/test/ba/kpi_ba.cc index 73b02558c5c..6ed5cdf1b62 100644 --- a/broker/bam/test/ba/kpi_ba.cc +++ b/broker/bam/test/ba/kpi_ba.cc @@ -29,23 +29,27 @@ #include "com/centreon/broker/neb/acknowledgement.hh" #include "com/centreon/broker/neb/downtime.hh" #include "com/centreon/broker/neb/service_status.hh" +#include "common/log_v2/log_v2.hh" #include "test-visitor.hh" using namespace com::centreon::broker; +using com::centreon::common::log_v2::log_v2; class KpiBA : public ::testing::Test { protected: std::unique_ptr _aply_state; std::unique_ptr _state; std::unique_ptr _visitor; + std::shared_ptr _logger; public: void SetUp() override { // Initialization. + _logger = log_v2::instance().get(log_v2::BAM); config::applier::init(0, "test_broker", 0); - _aply_state = std::make_unique(); - _state = std::make_unique(); + _aply_state = std::make_unique(_logger); + _state = std::make_unique(_logger); _visitor = std::make_unique("test-visitor"); } @@ -65,13 +69,13 @@ class KpiBA : public ::testing::Test { TEST_F(KpiBA, KpiBa) { /* Construction of BA1 */ std::shared_ptr test_ba{ - std::make_shared(1, 5, 13, true)}; + std::make_shared(1, 5, 13, true, _logger)}; test_ba->set_name("test-ba"); test_ba->set_downtime_behaviour(bam::configuration::ba::dt_inherit); /* Construction of BA2 */ std::shared_ptr test_ba_child{std::make_shared( - 2, 5, 14, bam::configuration::ba::state_source_worst)}; + 2, 5, 14, bam::configuration::ba::state_source_worst, _logger)}; test_ba_child->set_name("test-ba-child"); test_ba_child->set_downtime_behaviour(bam::configuration::ba::dt_inherit); @@ -79,8 +83,8 @@ TEST_F(KpiBA, KpiBa) { /* Construction of kpi_services */ for (int i = 0; i < 2; i++) { - auto s = std::make_shared(i + 1, 2, 3, 1 + i, - fmt::format("service {}", i)); + auto s = std::make_shared( + i + 1, 2, 3, 1 + i, fmt::format("service {}", i), _logger); s->set_downtimed(false); s->set_impact_critical(100); s->set_impact_unknown(0); @@ -94,11 +98,11 @@ TEST_F(KpiBA, KpiBa) { } /* Construction of kpi_ba */ - auto kpi_ba_child = std::make_shared(3, 2, "ba 2"); + auto kpi_ba_child = std::make_shared(3, 2, "ba 2", _logger); kpi_ba_child->set_impact_critical(100); kpi_ba_child->set_impact_warning(75); - auto kpi_ba = std::make_shared(4, 1, "ba 1"); + auto kpi_ba = std::make_shared(4, 1, "ba 1", _logger); kpi_ba->set_impact_critical(100); kpi_ba->set_impact_warning(75); @@ -173,13 +177,13 @@ TEST_F(KpiBA, KpiBa) { TEST_F(KpiBA, KpiBaPb) { /* Construction of BA1 */ std::shared_ptr test_ba{std::make_shared( - 1, 5, 13, bam::configuration::ba::state_source_worst)}; + 1, 5, 13, bam::configuration::ba::state_source_worst, _logger)}; test_ba->set_name("test-ba"); test_ba->set_downtime_behaviour(bam::configuration::ba::dt_inherit); /* Construction of BA2 */ std::shared_ptr test_ba_child{std::make_shared( - 2, 5, 14, bam::configuration::ba::state_source_worst)}; + 2, 5, 14, bam::configuration::ba::state_source_worst, _logger)}; test_ba_child->set_name("test-ba-child"); test_ba_child->set_downtime_behaviour(bam::configuration::ba::dt_inherit); @@ -187,8 +191,8 @@ TEST_F(KpiBA, KpiBaPb) { /* Construction of kpi_services */ for (int i = 0; i < 2; i++) { - auto s = std::make_shared(i + 1, 2, 3, 1 + i, - fmt::format("service {}", i)); + auto s = std::make_shared( + i + 1, 2, 3, 1 + i, fmt::format("service {}", i), _logger); s->set_downtimed(false); s->set_impact_critical(100); s->set_impact_unknown(0); @@ -202,11 +206,11 @@ TEST_F(KpiBA, KpiBaPb) { } /* Construction of kpi_ba */ - auto kpi_ba_child = std::make_shared(3, 2, "ba 2"); + auto kpi_ba_child = std::make_shared(3, 2, "ba 2", _logger); kpi_ba_child->set_impact_critical(100); kpi_ba_child->set_impact_warning(75); - auto kpi_ba = std::make_shared(4, 1, "ba 1"); + auto kpi_ba = std::make_shared(4, 1, "ba 1", _logger); kpi_ba->set_impact_critical(100); kpi_ba->set_impact_warning(75); @@ -276,21 +280,21 @@ TEST_F(KpiBA, KpiBaPb) { TEST_F(KpiBA, KpiBaDt) { /* Construction of BA1 */ std::shared_ptr test_ba{std::make_shared( - 1, 5, 13, bam::configuration::ba::state_source_worst)}; + 1, 5, 13, bam::configuration::ba::state_source_worst, _logger)}; test_ba->set_name("test-ba"); test_ba->set_downtime_behaviour(bam::configuration::ba::dt_inherit); /* Construction of BA2 */ std::shared_ptr test_ba_child{std::make_shared( - 2, 5, 14, bam::configuration::ba::state_source_worst)}; + 2, 5, 14, bam::configuration::ba::state_source_worst, _logger)}; test_ba_child->set_name("test-ba-child"); test_ba_child->set_downtime_behaviour(bam::configuration::ba::dt_inherit); absl::FixedArray, 2> kpis{ std::make_shared(1, 2, 3, 1, - fmt::format("service {}", 0)), + fmt::format("service {}", 0), _logger), std::make_shared(2, 2, 3, 2, - fmt::format("service {}", 1)), + fmt::format("service {}", 1), _logger), }; /* Construction of kpi_services */ @@ -307,11 +311,11 @@ TEST_F(KpiBA, KpiBaDt) { } /* Construction of kpi_ba */ - auto kpi_ba_child = std::make_shared(3, 2, "ba 2"); + auto kpi_ba_child = std::make_shared(3, 2, "ba 2", _logger); kpi_ba_child->set_impact_critical(100); kpi_ba_child->set_impact_warning(75); - auto kpi_ba = std::make_shared(4, 1, "ba 1"); + auto kpi_ba = std::make_shared(4, 1, "ba 1", _logger); kpi_ba->set_impact_critical(100); kpi_ba->set_impact_warning(75); @@ -391,13 +395,13 @@ TEST_F(KpiBA, KpiBaDt) { TEST_F(KpiBA, KpiBaDtPb) { /* Construction of BA1 */ std::shared_ptr test_ba{std::make_shared( - 1, 5, 13, bam::configuration::ba::state_source_worst)}; + 1, 5, 13, bam::configuration::ba::state_source_worst, _logger)}; test_ba->set_name("test-ba"); test_ba->set_downtime_behaviour(bam::configuration::ba::dt_inherit); /* Construction of BA2 */ std::shared_ptr test_ba_child{std::make_shared( - 2, 5, 14, bam::configuration::ba::state_source_worst)}; + 2, 5, 14, bam::configuration::ba::state_source_worst, _logger)}; test_ba_child->set_name("test-ba-child"); test_ba_child->set_downtime_behaviour(bam::configuration::ba::dt_inherit); @@ -405,8 +409,8 @@ TEST_F(KpiBA, KpiBaDtPb) { /* Construction of kpi_services */ for (int i = 0; i < 2; i++) { - auto s = std::make_shared(i + 1, 2, 3, 1 + i, - fmt::format("service {}", i)); + auto s = std::make_shared( + i + 1, 2, 3, 1 + i, fmt::format("service {}", i), _logger); s->set_downtimed(false); s->set_impact_critical(100); s->set_impact_unknown(0); @@ -420,11 +424,11 @@ TEST_F(KpiBA, KpiBaDtPb) { } /* Construction of kpi_ba */ - auto kpi_ba_child = std::make_shared(3, 2, "ba 2"); + auto kpi_ba_child = std::make_shared(3, 2, "ba 2", _logger); kpi_ba_child->set_impact_critical(100); kpi_ba_child->set_impact_warning(75); - auto kpi_ba = std::make_shared(4, 1, "ba 1"); + auto kpi_ba = std::make_shared(4, 1, "ba 1", _logger); kpi_ba->set_impact_critical(100); kpi_ba->set_impact_warning(75); @@ -503,13 +507,13 @@ TEST_F(KpiBA, KpiBaDtPb) { TEST_F(KpiBA, KpiBaDtOff) { /* Construction of BA1 */ std::shared_ptr test_ba{std::make_shared( - 1, 5, 13, bam::configuration::ba::state_source_worst)}; + 1, 5, 13, bam::configuration::ba::state_source_worst, _logger)}; test_ba->set_name("test-ba"); test_ba->set_downtime_behaviour(bam::configuration::ba::dt_inherit); /* Construction of BA2 */ std::shared_ptr test_ba_child{std::make_shared( - 2, 5, 14, bam::configuration::ba::state_source_worst)}; + 2, 5, 14, bam::configuration::ba::state_source_worst, _logger)}; test_ba_child->set_name("test-ba-child"); test_ba_child->set_downtime_behaviour(bam::configuration::ba::dt_inherit); @@ -517,8 +521,8 @@ TEST_F(KpiBA, KpiBaDtOff) { /* Construction of kpi_services */ for (int i = 0; i < 2; i++) { - auto s = std::make_shared(i + 1, 2, 3, 1 + i, - fmt::format("service {}", i)); + auto s = std::make_shared( + i + 1, 2, 3, 1 + i, fmt::format("service {}", i), _logger); s->set_downtimed(false); s->set_impact_critical(100); s->set_impact_unknown(0); @@ -532,11 +536,11 @@ TEST_F(KpiBA, KpiBaDtOff) { } /* Construction of kpi_ba */ - auto kpi_ba_child = std::make_shared(3, 2, "ba 2"); + auto kpi_ba_child = std::make_shared(3, 2, "ba 2", _logger); kpi_ba_child->set_impact_critical(100); kpi_ba_child->set_impact_warning(75); - auto kpi_ba = std::make_shared(4, 1, "ba 1"); + auto kpi_ba = std::make_shared(4, 1, "ba 1", _logger); kpi_ba->set_impact_critical(100); kpi_ba->set_impact_warning(75); @@ -624,13 +628,13 @@ TEST_F(KpiBA, KpiBaDtOff) { TEST_F(KpiBA, KpiBaDtOffPb) { /* Construction of BA1 */ std::shared_ptr test_ba{std::make_shared( - 1, 5, 13, bam::configuration::ba::state_source_worst)}; + 1, 5, 13, bam::configuration::ba::state_source_worst, _logger)}; test_ba->set_name("test-ba"); test_ba->set_downtime_behaviour(bam::configuration::ba::dt_inherit); /* Construction of BA2 */ std::shared_ptr test_ba_child{std::make_shared( - 2, 5, 14, bam::configuration::ba::state_source_worst)}; + 2, 5, 14, bam::configuration::ba::state_source_worst, _logger)}; test_ba_child->set_name("test-ba-child"); test_ba_child->set_downtime_behaviour(bam::configuration::ba::dt_inherit); @@ -638,8 +642,8 @@ TEST_F(KpiBA, KpiBaDtOffPb) { /* Construction of kpi_services */ for (int i = 0; i < 2; i++) { - auto s = std::make_shared(i + 1, 2, 3, 1 + i, - fmt::format("service {}", i)); + auto s = std::make_shared( + i + 1, 2, 3, 1 + i, fmt::format("service {}", i), _logger); s->set_downtimed(false); s->set_impact_critical(100); s->set_impact_unknown(0); @@ -653,11 +657,11 @@ TEST_F(KpiBA, KpiBaDtOffPb) { } /* Construction of kpi_ba */ - auto kpi_ba_child = std::make_shared(3, 2, "ba 2"); + auto kpi_ba_child = std::make_shared(3, 2, "ba 2", _logger); kpi_ba_child->set_impact_critical(100); kpi_ba_child->set_impact_warning(75); - auto kpi_ba = std::make_shared(4, 1, "ba 1"); + auto kpi_ba = std::make_shared(4, 1, "ba 1", _logger); kpi_ba->set_impact_critical(100); kpi_ba->set_impact_warning(75); @@ -751,13 +755,13 @@ TEST_F(KpiBA, KpiBaDtOffPb) { TEST_F(KpiBA, KpiBaOkDtOff) { /* Construction of BA1 */ std::shared_ptr test_ba{std::make_shared( - 1, 5, 13, bam::configuration::ba::state_source_worst)}; + 1, 5, 13, bam::configuration::ba::state_source_worst, _logger)}; test_ba->set_name("test-ba"); test_ba->set_downtime_behaviour(bam::configuration::ba::dt_inherit); /* Construction of BA2 */ std::shared_ptr test_ba_child{std::make_shared( - 2, 5, 14, bam::configuration::ba::state_source_worst)}; + 2, 5, 14, bam::configuration::ba::state_source_worst, _logger)}; test_ba_child->set_name("test-ba-child"); test_ba_child->set_downtime_behaviour(bam::configuration::ba::dt_inherit); @@ -765,8 +769,8 @@ TEST_F(KpiBA, KpiBaOkDtOff) { /* Construction of kpi_services */ for (int i = 0; i < 2; i++) { - auto s = std::make_shared(i + 1, 2, 3, 1 + i, - fmt::format("service {}", i)); + auto s = std::make_shared( + i + 1, 2, 3, 1 + i, fmt::format("service {}", i), _logger); s->set_downtimed(false); s->set_impact_critical(100); s->set_impact_unknown(0); @@ -780,11 +784,11 @@ TEST_F(KpiBA, KpiBaOkDtOff) { } /* Construction of kpi_ba */ - auto kpi_ba_child = std::make_shared(3, 2, "ba 2"); + auto kpi_ba_child = std::make_shared(3, 2, "ba 2", _logger); kpi_ba_child->set_impact_critical(100); kpi_ba_child->set_impact_warning(75); - auto kpi_ba = std::make_shared(4, 1, "ba 1"); + auto kpi_ba = std::make_shared(4, 1, "ba 1", _logger); kpi_ba->set_impact_critical(100); kpi_ba->set_impact_warning(75); @@ -856,13 +860,13 @@ TEST_F(KpiBA, KpiBaOkDtOff) { TEST_F(KpiBA, KpiBaOkDtOffPb) { /* Construction of BA1 */ std::shared_ptr test_ba{std::make_shared( - 1, 5, 13, bam::configuration::ba::state_source_worst)}; + 1, 5, 13, bam::configuration::ba::state_source_worst, _logger)}; test_ba->set_name("test-ba"); test_ba->set_downtime_behaviour(bam::configuration::ba::dt_inherit); /* Construction of BA2 */ std::shared_ptr test_ba_child{std::make_shared( - 2, 5, 14, bam::configuration::ba::state_source_worst)}; + 2, 5, 14, bam::configuration::ba::state_source_worst, _logger)}; test_ba_child->set_name("test-ba-child"); test_ba_child->set_downtime_behaviour(bam::configuration::ba::dt_inherit); @@ -870,8 +874,8 @@ TEST_F(KpiBA, KpiBaOkDtOffPb) { /* Construction of kpi_services */ for (int i = 0; i < 2; i++) { - auto s = std::make_shared(i + 1, 2, 3, 1 + i, - fmt::format("service {}", i)); + auto s = std::make_shared( + i + 1, 2, 3, 1 + i, fmt::format("service {}", i), _logger); s->set_downtimed(false); s->set_impact_critical(100); s->set_impact_unknown(0); @@ -885,11 +889,11 @@ TEST_F(KpiBA, KpiBaOkDtOffPb) { } /* Construction of kpi_ba */ - auto kpi_ba_child = std::make_shared(3, 2, "ba 2"); + auto kpi_ba_child = std::make_shared(3, 2, "ba 2", _logger); kpi_ba_child->set_impact_critical(100); kpi_ba_child->set_impact_warning(75); - auto kpi_ba = std::make_shared(4, 1, "ba 1"); + auto kpi_ba = std::make_shared(4, 1, "ba 1", _logger); kpi_ba->set_impact_critical(100); kpi_ba->set_impact_warning(75); @@ -967,7 +971,7 @@ TEST_F(KpiBA, KpiBaOkDtOffPb) { TEST_F(KpiBA, KpiBaWorstImpact) { /* Construction of BA1 */ std::shared_ptr test_ba{std::make_shared( - 1, 5, 13, bam::configuration::ba::state_source_impact)}; + 1, 5, 13, bam::configuration::ba::state_source_impact, _logger)}; test_ba->set_name("test-ba"); test_ba->set_level_critical(0); test_ba->set_level_warning(25); @@ -975,7 +979,7 @@ TEST_F(KpiBA, KpiBaWorstImpact) { /* Construction of BA2 */ std::shared_ptr test_ba_child{std::make_shared( - 2, 5, 14, bam::configuration::ba::state_source_worst)}; + 2, 5, 14, bam::configuration::ba::state_source_worst, _logger)}; test_ba_child->set_name("test-ba-child"); test_ba_child->set_level_critical(0); test_ba_child->set_level_warning(25); @@ -985,8 +989,8 @@ TEST_F(KpiBA, KpiBaWorstImpact) { /* Construction of kpi_services */ for (int i = 0; i < 2; i++) { - auto s = std::make_shared(i + 1, 2, 3, 1 + i, - fmt::format("service {}", i)); + auto s = std::make_shared( + i + 1, 2, 3, 1 + i, fmt::format("service {}", i), _logger); s->set_downtimed(false); s->set_impact_critical(100); s->set_impact_unknown(0); @@ -998,12 +1002,12 @@ TEST_F(KpiBA, KpiBaWorstImpact) { } /* Construction of kpi_ba */ - auto kpi_ba_child = std::make_shared(3, 2, "ba 2"); + auto kpi_ba_child = std::make_shared(3, 2, "ba 2", _logger); kpi_ba_child->set_impact_critical(100); kpi_ba_child->set_impact_warning(75); kpi_ba_child->set_impact_unknown(27); - auto kpi_ba = std::make_shared(4, 1, "ba 1"); + auto kpi_ba = std::make_shared(4, 1, "ba 1", _logger); kpi_ba->set_impact_critical(100); kpi_ba->set_impact_warning(75); @@ -1066,7 +1070,7 @@ TEST_F(KpiBA, KpiBaWorstImpact) { TEST_F(KpiBA, KpiBaWorstImpactPb) { /* Construction of BA1 */ std::shared_ptr test_ba{std::make_shared( - 1, 5, 13, bam::configuration::ba::state_source_impact)}; + 1, 5, 13, bam::configuration::ba::state_source_impact, _logger)}; test_ba->set_name("test-ba"); test_ba->set_level_critical(100); test_ba->set_level_warning(75); @@ -1074,7 +1078,7 @@ TEST_F(KpiBA, KpiBaWorstImpactPb) { /* Construction of BA2 */ std::shared_ptr test_ba_child{std::make_shared( - 2, 5, 14, bam::configuration::ba::state_source_worst)}; + 2, 5, 14, bam::configuration::ba::state_source_worst, _logger)}; test_ba_child->set_name("test-ba-child"); test_ba_child->set_downtime_behaviour(bam::configuration::ba::dt_inherit); @@ -1082,8 +1086,8 @@ TEST_F(KpiBA, KpiBaWorstImpactPb) { /* Construction of kpi_services */ for (int i = 0; i < 2; i++) { - auto s = std::make_shared(i + 1, 2, 3, 1 + i, - fmt::format("service {}", i)); + auto s = std::make_shared( + i + 1, 2, 3, 1 + i, fmt::format("service {}", i), _logger); s->set_downtimed(false); s->set_impact_critical(100); s->set_impact_unknown(0); @@ -1095,12 +1099,12 @@ TEST_F(KpiBA, KpiBaWorstImpactPb) { } /* Construction of kpi_ba */ - auto kpi_ba_child = std::make_shared(3, 2, "ba 2"); + auto kpi_ba_child = std::make_shared(3, 2, "ba 2", _logger); kpi_ba_child->set_impact_critical(100); kpi_ba_child->set_impact_warning(75); kpi_ba_child->set_impact_unknown(27); - auto kpi_ba = std::make_shared(4, 1, "ba 1"); + auto kpi_ba = std::make_shared(4, 1, "ba 1", _logger); kpi_ba->set_impact_critical(100); kpi_ba->set_impact_warning(75); diff --git a/broker/bam/test/ba/kpi_service.cc b/broker/bam/test/ba/kpi_service.cc index c4a0ce24cd2..71bad246e20 100644 --- a/broker/bam/test/ba/kpi_service.cc +++ b/broker/bam/test/ba/kpi_service.cc @@ -1,20 +1,20 @@ /** -* Copyright 2014, 2021 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2014, 2021 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/bam/kpi_service.hh" #include @@ -32,6 +32,7 @@ #include "com/centreon/broker/neb/acknowledgement.hh" #include "com/centreon/broker/neb/downtime.hh" #include "com/centreon/broker/neb/service_status.hh" +#include "common/log_v2/log_v2.hh" #include "test-visitor.hh" using namespace com::centreon::broker; @@ -42,14 +43,16 @@ class BamBA : public ::testing::Test { std::unique_ptr _aply_state; std::unique_ptr _state; std::unique_ptr _visitor; + std::shared_ptr _logger; public: void SetUp() override { // Initialization. + _logger = log_v2::instance().get(log_v2::BAM); config::applier::init(0, "test_broker", 0); - _aply_state = std::make_unique(); - _state = std::make_unique(); + _aply_state = std::make_unique(_logger); + _state = std::make_unique(_logger); _visitor = std::make_unique("test-visitor"); } @@ -66,12 +69,12 @@ class BamBA : public ::testing::Test { TEST_F(BamBA, KpiServiceRecompute) { // Build BAM objects. std::shared_ptr test_ba{ - std::make_shared(1, 1, 1, true)}; + std::make_shared(1, 1, 1, true, _logger)}; test_ba->set_level_critical(0); test_ba->set_level_warning(25); std::shared_ptr kpi{ - std::make_shared(1, 1, 1, 1, "host_1/serv_1")}; + std::make_shared(1, 1, 1, 1, "host_1/serv_1", _logger)}; kpi->set_impact_critical(100.0); kpi->set_state_hard(bam::state_ok); @@ -120,14 +123,14 @@ TEST_F(BamBA, KpiServiceRecompute) { TEST_F(BamBA, KpiServiceImpactState) { // Build BAM objects. std::shared_ptr test_ba{ - std::make_shared(1, 1, 2, true)}; + std::make_shared(1, 1, 2, true, _logger)}; std::vector> kpis; std::vector results{0, 0, 1, 1, 1, 2}; for (int i = 0; i < 3; i++) { auto s = std::make_shared( - i + 1, 1, i + 1, 1, fmt::format("host_{}/serv_1", i + 1)); + i + 1, 1, i + 1, 1, fmt::format("host_{}/serv_1", i + 1), _logger); s->set_impact_warning(10); s->set_impact_critical(20); s->set_state_hard(bam::state_ok); @@ -241,14 +244,14 @@ TEST_F(BamBA, KpiServiceImpactState) { TEST_F(BamBA, KpiServiceBestState) { // Build BAM objects. std::shared_ptr test_ba{ - std::make_shared(1, 1, 3, true)}; + std::make_shared(1, 1, 3, true, _logger)}; std::vector> kpis; std::vector results{0, 0, 1, 1, 1, 2}; for (size_t i = 0; i < 3; i++) { - auto s = std::make_shared(i + 1, 1, i + 1, 1, - fmt::format("service {}", i)); + auto s = std::make_shared( + i + 1, 1, i + 1, 1, fmt::format("service {}", i), _logger); s->set_state_hard(bam::state_ok); s->set_state_soft(s->get_state_hard()); test_ba->add_impact(s); @@ -299,14 +302,14 @@ TEST_F(BamBA, KpiServiceBestState) { TEST_F(BamBA, KpiServiceWorstState) { // Build BAM objects. std::shared_ptr test_ba{ - std::make_shared(1, 1, 4, true)}; + std::make_shared(1, 1, 4, true, _logger)}; std::vector> kpis; std::vector results{1, 1, 1, 2, 2, 2}; for (int i = 0; i < 3; i++) { - auto s = std::make_shared(i + 1, 1, i + 1, 1, - fmt::format("service {}", i)); + auto s = std::make_shared( + i + 1, 1, i + 1, 1, fmt::format("service {}", i), _logger); s->set_impact_warning(10); s->set_impact_critical(20); s->set_state_hard(bam::state_ok); @@ -396,7 +399,7 @@ TEST_F(BamBA, KpiServiceWorstState) { TEST_F(BamBA, KpiServiceRatioNum) { // Build BAM objects. std::shared_ptr test_ba{ - std::make_shared(1, 1, 4, true)}; + std::make_shared(1, 1, 4, true, _logger)}; test_ba->set_level_critical(4); test_ba->set_level_warning(2); @@ -404,8 +407,8 @@ TEST_F(BamBA, KpiServiceRatioNum) { std::stack results{{2, 1, 1, 0}}; for (int i = 0; i < 4; i++) { - auto s = std::make_shared(i + 1, 1, i + 1, 1, - fmt::format("service {}", i)); + auto s = std::make_shared( + i + 1, 1, i + 1, 1, fmt::format("service {}", i), _logger); s->set_state_hard(bam::state_ok); s->set_state_soft(s->get_state_hard()); test_ba->add_impact(s); @@ -453,7 +456,7 @@ TEST_F(BamBA, KpiServiceRatioNum) { TEST_F(BamBA, KpiServiceRatioPercent) { // Build BAM objects. std::shared_ptr test_ba{ - std::make_shared(1, 1, 4, true)}; + std::make_shared(1, 1, 4, true, _logger)}; test_ba->set_level_critical(100); test_ba->set_level_warning(75); @@ -461,8 +464,8 @@ TEST_F(BamBA, KpiServiceRatioPercent) { std::stack results({2, 1, 0, 0}); for (int i = 0; i < 4; i++) { - auto s = std::make_shared(i + 1, 1, i + 1, 1, - fmt::format("service {}", i)); + auto s = std::make_shared( + i + 1, 1, i + 1, 1, fmt::format("service {}", i), _logger); s->set_state_hard(bam::state_ok); s->set_state_soft(s->get_state_hard()); test_ba->add_impact(s); @@ -494,7 +497,7 @@ TEST_F(BamBA, KpiServiceRatioPercent) { TEST_F(BamBA, KpiServiceDtInheritAllCritical) { std::shared_ptr test_ba{ - std::make_shared(1, 1, 4, true)}; + std::make_shared(1, 1, 4, true, _logger)}; test_ba->set_level_critical(100); test_ba->set_level_warning(75); test_ba->set_downtime_behaviour(bam::configuration::ba::dt_inherit); @@ -503,8 +506,8 @@ TEST_F(BamBA, KpiServiceDtInheritAllCritical) { std::stack results({true, false, false, false}); for (int i = 0; i < 4; i++) { - auto s = std::make_shared(i + 1, 1, i + 1, 1, - fmt::format("service {}", i)); + auto s = std::make_shared( + i + 1, 1, i + 1, 1, fmt::format("service {}", i), _logger); s->set_state_hard(bam::state_critical); s->set_state_soft(s->get_state_hard()); test_ba->add_impact(s); @@ -542,7 +545,7 @@ TEST_F(BamBA, KpiServiceDtInheritAllCritical) { TEST_F(BamBA, KpiServiceDtInheritAllCriticalPb) { std::shared_ptr test_ba{ - std::make_shared(1, 1, 4, true)}; + std::make_shared(1, 1, 4, true, _logger)}; test_ba->set_level_critical(100); test_ba->set_level_warning(75); test_ba->set_downtime_behaviour(bam::configuration::ba::dt_inherit); @@ -551,8 +554,8 @@ TEST_F(BamBA, KpiServiceDtInheritAllCriticalPb) { std::stack results({true, false, false, false}); for (int i = 0; i < 4; i++) { - auto s = std::make_shared(i + 1, 1, i + 1, 1, - fmt::format("service {}", i)); + auto s = std::make_shared( + i + 1, 1, i + 1, 1, fmt::format("service {}", i), _logger); s->set_state_hard(bam::state_critical); s->set_state_soft(s->get_state_hard()); test_ba->add_impact(s); @@ -592,7 +595,7 @@ TEST_F(BamBA, KpiServiceDtInheritAllCriticalPb) { TEST_F(BamBA, KpiServiceDtInheritOneOK) { std::shared_ptr test_ba{ - std::make_shared(1, 1, 4, true)}; + std::make_shared(1, 1, 4, true, _logger)}; test_ba->set_level_critical(100); test_ba->set_level_warning(90); test_ba->set_downtime_behaviour(bam::configuration::ba::dt_inherit); @@ -601,8 +604,8 @@ TEST_F(BamBA, KpiServiceDtInheritOneOK) { std::stack results({false, false, false, false}); for (int i = 0; i < 4; i++) { - auto s = std::make_shared(i + 1, 1, i + 1, 1, - fmt::format("service {}", i)); + auto s = std::make_shared( + i + 1, 1, i + 1, 1, fmt::format("service {}", i), _logger); if (i == 0) s->set_state_hard(bam::state_ok); else @@ -648,7 +651,7 @@ TEST_F(BamBA, KpiServiceDtInheritOneOK) { TEST_F(BamBA, KpiServiceDtInheritOneOKPb) { std::shared_ptr test_ba{ - std::make_shared(1, 1, 4, true)}; + std::make_shared(1, 1, 4, true, _logger)}; test_ba->set_level_critical(100); test_ba->set_level_warning(90); test_ba->set_downtime_behaviour(bam::configuration::ba::dt_inherit); @@ -657,8 +660,8 @@ TEST_F(BamBA, KpiServiceDtInheritOneOKPb) { std::stack results({false, false, false, false}); for (int i = 0; i < 4; i++) { - auto s = std::make_shared(i + 1, 1, i + 1, 1, - fmt::format("service {}", i)); + auto s = std::make_shared( + i + 1, 1, i + 1, 1, fmt::format("service {}", i), _logger); if (i == 0) s->set_state_hard(bam::state_ok); else @@ -706,7 +709,7 @@ TEST_F(BamBA, KpiServiceDtInheritOneOKPb) { TEST_F(BamBA, KpiServiceIgnoreDt) { std::shared_ptr test_ba{ - std::make_shared(1, 1, 4, true)}; + std::make_shared(1, 1, 4, true, _logger)}; test_ba->set_level_critical(100); test_ba->set_level_warning(75); test_ba->set_downtime_behaviour(bam::configuration::ba::dt_ignore); @@ -715,8 +718,8 @@ TEST_F(BamBA, KpiServiceIgnoreDt) { std::stack results({false, false, false, false}); for (int i = 0; i < 4; i++) { - auto s = std::make_shared(i + 1, 1, i + 1, 1, - fmt::format("service {}", i)); + auto s = std::make_shared( + i + 1, 1, i + 1, 1, fmt::format("service {}", i), _logger); s->set_state_hard(bam::state_critical); s->set_state_soft(s->get_state_hard()); test_ba->add_impact(s); @@ -754,7 +757,7 @@ TEST_F(BamBA, KpiServiceIgnoreDt) { TEST_F(BamBA, KpiServiceIgnoreDtPb) { std::shared_ptr test_ba{ - std::make_shared(1, 1, 4, true)}; + std::make_shared(1, 1, 4, true, _logger)}; test_ba->set_level_critical(100); test_ba->set_level_warning(75); test_ba->set_downtime_behaviour(bam::configuration::ba::dt_ignore); @@ -763,8 +766,8 @@ TEST_F(BamBA, KpiServiceIgnoreDtPb) { std::stack results({false, false, false, false}); for (int i = 0; i < 4; i++) { - auto s = std::make_shared(i + 1, 1, i + 1, 1, - fmt::format("service {}", i)); + auto s = std::make_shared( + i + 1, 1, i + 1, 1, fmt::format("service {}", i), _logger); s->set_state_hard(bam::state_critical); s->set_state_soft(s->get_state_hard()); test_ba->add_impact(s); @@ -805,7 +808,7 @@ TEST_F(BamBA, KpiServiceIgnoreDtPb) { TEST_F(BamBA, KpiServiceDtIgnoreKpi) { std::shared_ptr test_ba{ - std::make_shared(1, 1, 4, true)}; + std::make_shared(1, 1, 4, true, _logger)}; test_ba->set_level_critical(100); test_ba->set_level_warning(75); test_ba->set_downtime_behaviour(bam::configuration::ba::dt_ignore_kpi); @@ -814,8 +817,8 @@ TEST_F(BamBA, KpiServiceDtIgnoreKpi) { std::stack results({false, false, false, false}); for (int i = 0; i < 4; i++) { - auto s = std::make_shared(i + 1, 1, i + 1, 1, - fmt::format("service {}", i)); + auto s = std::make_shared( + i + 1, 1, i + 1, 1, fmt::format("service {}", i), _logger); s->set_state_hard(bam::state_critical); s->set_state_soft(s->get_state_hard()); test_ba->add_impact(s); @@ -853,7 +856,7 @@ TEST_F(BamBA, KpiServiceDtIgnoreKpi) { TEST_F(BamBA, KpiServiceDtIgnoreKpiPb) { std::shared_ptr test_ba{ - std::make_shared(1, 1, 4, true)}; + std::make_shared(1, 1, 4, true, _logger)}; test_ba->set_level_critical(100); test_ba->set_level_warning(75); test_ba->set_downtime_behaviour(bam::configuration::ba::dt_ignore_kpi); @@ -862,8 +865,8 @@ TEST_F(BamBA, KpiServiceDtIgnoreKpiPb) { std::stack results({false, false, false, false}); for (int i = 0; i < 4; i++) { - auto s = std::make_shared(i + 1, 1, i + 1, 1, - fmt::format("service {}", i)); + auto s = std::make_shared( + i + 1, 1, i + 1, 1, fmt::format("service {}", i), _logger); s->set_state_hard(bam::state_critical); s->set_state_soft(s->get_state_hard()); test_ba->add_impact(s); @@ -904,7 +907,7 @@ TEST_F(BamBA, KpiServiceDtIgnoreKpiPb) { TEST_F(BamBA, KpiServiceDtIgnoreKpiImpact) { std::shared_ptr test_ba{ - std::make_shared(1, 1, 4, true)}; + std::make_shared(1, 1, 4, true, _logger)}; test_ba->set_level_critical(50); test_ba->set_level_warning(75); test_ba->set_downtime_behaviour(bam::configuration::ba::dt_ignore_kpi); @@ -918,8 +921,8 @@ TEST_F(BamBA, KpiServiceDtIgnoreKpiImpact) { results.push(2); for (int i = 0; i < 4; i++) { - auto s = std::make_shared(i + 1, 1, i + 1, 1, - fmt::format("service {}", i)); + auto s = std::make_shared( + i + 1, 1, i + 1, 1, fmt::format("service {}", i), _logger); if (i == 3) s->set_state_hard(bam::state_ok); else @@ -964,7 +967,7 @@ TEST_F(BamBA, KpiServiceDtIgnoreKpiImpact) { TEST_F(BamBA, KpiServiceDtIgnoreKpiImpactPb) { std::shared_ptr test_ba{ - std::make_shared(1, 1, 4, true)}; + std::make_shared(1, 1, 4, true, _logger)}; test_ba->set_level_critical(50); test_ba->set_level_warning(75); test_ba->set_downtime_behaviour(bam::configuration::ba::dt_ignore_kpi); @@ -973,8 +976,8 @@ TEST_F(BamBA, KpiServiceDtIgnoreKpiImpactPb) { std::stack results({0, 0, 1, 2}); for (int i = 0; i < 4; i++) { - auto s = std::make_shared(i + 1, 1, i + 1, 1, - fmt::format("service {}", i)); + auto s = std::make_shared( + i + 1, 1, i + 1, 1, fmt::format("service {}", i), _logger); if (i == 3) s->set_state_hard(bam::state_ok); else @@ -1022,15 +1025,15 @@ TEST_F(BamBA, KpiServiceDtIgnoreKpiImpactPb) { TEST_F(BamBA, KpiServiceDtIgnoreKpiBest) { std::shared_ptr test_ba{ - std::make_shared(1, 1, 4, true)}; + std::make_shared(1, 1, 4, true, _logger)}; test_ba->set_downtime_behaviour(bam::configuration::ba::dt_ignore_kpi); std::vector> kpis; std::stack results({0, 2, 1, 0}); for (int i = 0; i < 4; i++) { - auto s = std::make_shared(i + 1, 1, i + 1, 1, - fmt::format("service {}", i)); + auto s = std::make_shared( + i + 1, 1, i + 1, 1, fmt::format("service {}", i), _logger); switch (i) { case 0: case 1: @@ -1079,15 +1082,15 @@ TEST_F(BamBA, KpiServiceDtIgnoreKpiBest) { TEST_F(BamBA, KpiServiceDtIgnoreKpiBestPb) { std::shared_ptr test_ba{ - std::make_shared(1, 1, 4, true)}; + std::make_shared(1, 1, 4, true, _logger)}; test_ba->set_downtime_behaviour(bam::configuration::ba::dt_ignore_kpi); std::vector> kpis; std::stack results({0, 2, 1, 0}); for (int i = 0; i < 4; i++) { - auto s = std::make_shared(i + 1, 1, i + 1, 1, - fmt::format("service {}", i)); + auto s = std::make_shared( + i + 1, 1, i + 1, 1, fmt::format("service {}", i), _logger); switch (i) { case 0: case 1: @@ -1140,15 +1143,15 @@ TEST_F(BamBA, KpiServiceDtIgnoreKpiBestPb) { TEST_F(BamBA, KpiServiceDtIgnoreKpiWorst) { std::shared_ptr test_ba{ - std::make_shared(1, 1, 4, true)}; + std::make_shared(1, 1, 4, true, _logger)}; test_ba->set_downtime_behaviour(bam::configuration::ba::dt_ignore_kpi); std::vector> kpis; std::stack results({0, 0, 1, 2}); for (int i = 0; i < 4; i++) { - auto s = std::make_shared(i + 1, 1, i + 1, 1, - fmt::format("service {}", i)); + auto s = std::make_shared( + i + 1, 1, i + 1, 1, fmt::format("service {}", i), _logger); switch (i) { case 0: case 1: @@ -1197,15 +1200,15 @@ TEST_F(BamBA, KpiServiceDtIgnoreKpiWorst) { TEST_F(BamBA, KpiServiceDtIgnoreKpiWorstPb) { std::shared_ptr test_ba{ - std::make_shared(1, 1, 4, true)}; + std::make_shared(1, 1, 4, true, _logger)}; test_ba->set_downtime_behaviour(bam::configuration::ba::dt_ignore_kpi); std::vector> kpis; std::stack results({0, 0, 1, 2}); for (int i = 0; i < 4; i++) { - auto s = std::make_shared(i + 1, 1, i + 1, 1, - fmt::format("service {}", i)); + auto s = std::make_shared( + i + 1, 1, i + 1, 1, fmt::format("service {}", i), _logger); switch (i) { case 0: case 1: @@ -1257,7 +1260,7 @@ TEST_F(BamBA, KpiServiceDtIgnoreKpiWorstPb) { TEST_F(BamBA, KpiServiceDtIgnoreKpiRatio) { std::shared_ptr test_ba{ - std::make_shared(1, 1, 4, true)}; + std::make_shared(1, 1, 4, true, _logger)}; test_ba->set_downtime_behaviour(bam::configuration::ba::dt_ignore_kpi); test_ba->set_level_warning(1); test_ba->set_level_critical(2); @@ -1266,8 +1269,8 @@ TEST_F(BamBA, KpiServiceDtIgnoreKpiRatio) { std::stack results({0, 1, 2, 2}); for (int i = 0; i < 4; i++) { - auto s = std::make_shared(i + 1, 1, i + 1, 1, - fmt::format("service {}", i)); + auto s = std::make_shared( + i + 1, 1, i + 1, 1, fmt::format("service {}", i), _logger); s->set_state_hard(bam::state_critical); s->set_state_soft(s->get_state_hard()); test_ba->add_impact(s); @@ -1305,7 +1308,7 @@ TEST_F(BamBA, KpiServiceDtIgnoreKpiRatio) { TEST_F(BamBA, KpiServiceDtIgnoreKpiRatioPb) { std::shared_ptr test_ba{ - std::make_shared(1, 1, 4, true)}; + std::make_shared(1, 1, 4, true, _logger)}; test_ba->set_downtime_behaviour(bam::configuration::ba::dt_ignore_kpi); test_ba->set_level_warning(1); test_ba->set_level_critical(2); @@ -1314,8 +1317,8 @@ TEST_F(BamBA, KpiServiceDtIgnoreKpiRatioPb) { std::stack results({0, 1, 2, 2}); for (int i = 0; i < 4; i++) { - auto s = std::make_shared(i + 1, 1, i + 1, 1, - fmt::format("service {}", i)); + auto s = std::make_shared( + i + 1, 1, i + 1, 1, fmt::format("service {}", i), _logger); s->set_state_hard(bam::state_critical); s->set_state_soft(s->get_state_hard()); test_ba->add_impact(s); @@ -1357,7 +1360,7 @@ TEST_F(BamBA, KpiServiceDtIgnoreKpiRatioPb) { TEST_F(BamBA, KpiServiceDt) { std::shared_ptr test_ba{ - std::make_shared(1, 1, 4, true)}; + std::make_shared(1, 1, 4, true, _logger)}; test_ba->set_level_critical(100); test_ba->set_level_warning(75); test_ba->set_downtime_behaviour(bam::configuration::ba::dt_inherit); @@ -1366,8 +1369,8 @@ TEST_F(BamBA, KpiServiceDt) { std::vector results{false, false, false, true}; for (int i = 0; i < 4; i++) { - auto s = std::make_shared(i + 1, 1, i + 1, 1, - fmt::format("service {}", i)); + auto s = std::make_shared( + i + 1, 1, i + 1, 1, fmt::format("service {}", i), _logger); s->set_state_hard(bam::state_critical); s->set_state_soft(s->get_state_hard()); test_ba->add_impact(s); @@ -1518,7 +1521,7 @@ TEST_F(BamBA, KpiServiceDt) { TEST_F(BamBA, KpiServiceDtPb) { std::shared_ptr test_ba{ - std::make_shared(1, 1, 4, true)}; + std::make_shared(1, 1, 4, true, _logger)}; test_ba->set_level_critical(100); test_ba->set_level_warning(75); test_ba->set_downtime_behaviour(bam::configuration::ba::dt_inherit); @@ -1527,8 +1530,8 @@ TEST_F(BamBA, KpiServiceDtPb) { std::vector results{false, false, false, true}; for (int i = 0; i < 4; i++) { - auto s = std::make_shared(i + 1, 1, i + 1, 1, - fmt::format("service {}", i)); + auto s = std::make_shared( + i + 1, 1, i + 1, 1, fmt::format("service {}", i), _logger); s->set_state_hard(bam::state_critical); s->set_state_soft(s->get_state_hard()); test_ba->add_impact(s); @@ -1682,7 +1685,7 @@ TEST_F(BamBA, KpiServiceDtPb) { TEST_F(BamBA, KpiServiceDtInherited_set) { std::shared_ptr test_ba{ - std::make_shared(1, 1, 4, true)}; + std::make_shared(1, 1, 4, true, _logger)}; test_ba->set_level_critical(100); test_ba->set_level_warning(75); test_ba->set_downtime_behaviour(bam::configuration::ba::dt_inherit); @@ -1691,8 +1694,8 @@ TEST_F(BamBA, KpiServiceDtInherited_set) { std::vector results{false, false, false, true}; for (int i = 0; i < 4; i++) { - auto s = std::make_shared(i + 1, 1, i + 1, 1, - fmt::format("service {}", i)); + auto s = std::make_shared( + i + 1, 1, i + 1, 1, fmt::format("service {}", i), _logger); s->set_state_hard(bam::state_critical); s->set_state_soft(s->get_state_hard()); test_ba->add_impact(s); @@ -1741,7 +1744,7 @@ TEST_F(BamBA, KpiServiceDtInherited_set) { TEST_F(BamBA, KpiServiceDtInherited_setPb) { std::shared_ptr test_ba{ - std::make_shared(1, 1, 4, true)}; + std::make_shared(1, 1, 4, true, _logger)}; test_ba->set_level_critical(100); test_ba->set_level_warning(75); test_ba->set_downtime_behaviour(bam::configuration::ba::dt_inherit); @@ -1750,8 +1753,8 @@ TEST_F(BamBA, KpiServiceDtInherited_setPb) { std::vector results{false, false, false, true}; for (int i = 0; i < 4; i++) { - auto s = std::make_shared(i + 1, 1, i + 1, 1, - fmt::format("service {}", i)); + auto s = std::make_shared( + i + 1, 1, i + 1, 1, fmt::format("service {}", i), _logger); s->set_state_hard(bam::state_critical); s->set_state_soft(s->get_state_hard()); test_ba->add_impact(s); @@ -1803,7 +1806,7 @@ TEST_F(BamBA, KpiServiceDtInherited_setPb) { TEST_F(BamBA, KpiServiceDtInherited_unset) { std::shared_ptr test_ba{ - std::make_shared(1, 2, 4, true)}; + std::make_shared(1, 2, 4, true, _logger)}; test_ba->set_level_critical(100); test_ba->set_level_warning(75); test_ba->set_downtime_behaviour(bam::configuration::ba::dt_inherit); @@ -1811,8 +1814,8 @@ TEST_F(BamBA, KpiServiceDtInherited_unset) { std::vector> kpis; for (int i = 0; i < 4; i++) { - auto s = std::make_shared(i + 1, 1, i + 1, 1, - fmt::format("service {}", i)); + auto s = std::make_shared( + i + 1, 1, i + 1, 1, fmt::format("service {}", i), _logger); s->set_state_hard(bam::state_critical); s->set_state_soft(s->get_state_hard()); test_ba->add_impact(s); @@ -1849,7 +1852,7 @@ TEST_F(BamBA, KpiServiceDtInherited_unset) { TEST_F(BamBA, KpiServiceDtInherited_unsetPb) { std::shared_ptr test_ba{ - std::make_shared(1, 2, 4, true)}; + std::make_shared(1, 2, 4, true, _logger)}; test_ba->set_level_critical(100); test_ba->set_level_warning(75); test_ba->set_downtime_behaviour(bam::configuration::ba::dt_inherit); @@ -1857,8 +1860,8 @@ TEST_F(BamBA, KpiServiceDtInherited_unsetPb) { std::vector> kpis; for (int i = 0; i < 4; i++) { - auto s = std::make_shared(i + 1, 1, i + 1, 1, - fmt::format("service {}", i)); + auto s = std::make_shared( + i + 1, 1, i + 1, 1, fmt::format("service {}", i), _logger); s->set_state_hard(bam::state_critical); s->set_state_soft(s->get_state_hard()); test_ba->add_impact(s); @@ -1896,7 +1899,7 @@ TEST_F(BamBA, KpiServiceDtInherited_unsetPb) { TEST_F(BamBA, KpiServiceAcknowledgement) { std::shared_ptr test_ba{ - std::make_shared(1, 2, 4, true)}; + std::make_shared(1, 2, 4, true, _logger)}; test_ba->set_level_critical(100); test_ba->set_level_warning(75); test_ba->set_downtime_behaviour(bam::configuration::ba::dt_inherit); @@ -1904,8 +1907,8 @@ TEST_F(BamBA, KpiServiceAcknowledgement) { std::vector> kpis; for (int i = 0; i < 4; i++) { - auto s = std::make_shared(i + 1, 1, i + 1, 1, - fmt::format("service {}", i)); + auto s = std::make_shared( + i + 1, 1, i + 1, 1, fmt::format("service {}", i), _logger); s->set_state_hard(bam::state_critical); s->set_state_soft(s->get_state_hard()); test_ba->add_impact(s); @@ -1944,7 +1947,7 @@ TEST_F(BamBA, KpiServiceAcknowledgement) { TEST_F(BamBA, KpiServiceAcknowledgementPb) { std::shared_ptr test_ba{ - std::make_shared(1, 2, 4, true)}; + std::make_shared(1, 2, 4, true, _logger)}; test_ba->set_level_critical(100); test_ba->set_level_warning(75); test_ba->set_downtime_behaviour(bam::configuration::ba::dt_inherit); @@ -1952,8 +1955,8 @@ TEST_F(BamBA, KpiServiceAcknowledgementPb) { std::vector> kpis; for (int i = 0; i < 4; i++) { - auto s = std::make_shared(i + 1, 1, i + 1, 1, - fmt::format("service {}", i)); + auto s = std::make_shared( + i + 1, 1, i + 1, 1, fmt::format("service {}", i), _logger); s->set_state_hard(bam::state_critical); s->set_state_soft(s->get_state_hard()); test_ba->add_impact(s); diff --git a/broker/bam/test/configuration/applier-boolexp.cc b/broker/bam/test/configuration/applier-boolexp.cc index 3211ae726ac..a39b7322316 100644 --- a/broker/bam/test/configuration/applier-boolexp.cc +++ b/broker/bam/test/configuration/applier-boolexp.cc @@ -21,17 +21,20 @@ #include "com/centreon/broker/bam/configuration/bool_expression.hh" #include "com/centreon/broker/bam/configuration/kpi.hh" #include "com/centreon/broker/config/applier/init.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; +using log_v2 = com::centreon::common::log_v2::log_v2; class ApplierBoolexp : public ::testing::Test { public: void SetUp() override { // Initialization. config::applier::init(0, "test_broker", 0); + auto logger = log_v2::instance().get(log_v2::BAM); - _aply_state = std::make_unique(); - _state = std::make_unique(); + _aply_state = std::make_unique(logger); + _state = std::make_unique(logger); } void TearDown() override { diff --git a/broker/bam/test/exp_builder/availability_builder.cc b/broker/bam/test/exp_builder/availability_builder.cc index 9f92361f8e4..4e34b1da1e3 100644 --- a/broker/bam/test/exp_builder/availability_builder.cc +++ b/broker/bam/test/exp_builder/availability_builder.cc @@ -1,24 +1,26 @@ /** -* Copyright 2021 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2021 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/bam/availability_builder.hh" #include +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; +using log_v2 = com::centreon::common::log_v2::log_v2; TEST(BamAvailabilityBuilder, Simple) { /* mon. 29 mars 2021 15:59:18 CEST */ @@ -26,16 +28,17 @@ TEST(BamAvailabilityBuilder, Simple) { /* mon. 29 mars 2021 15:04:18 CEST */ time_t start_time = 1617023058u; - time::timeperiod::ptr period{std::make_shared( + time::timeperiod::ptr period = std::make_shared( 4, "test_timeperiod", "test_alias", "08:00-20:00", "08:00-20:00", "08:00-20:00", "08:00-20:00", "08:00-20:00", "08:00-20:00", - "08:00-20:00")}; + "08:00-20:00"); ASSERT_TRUE(period->is_valid(end_time)); bam::availability_builder builder(end_time, start_time); ASSERT_EQ(builder.get_available(), 0); - builder.add_event(0, start_time, end_time, false, period); + auto logger = log_v2::instance().get(log_v2::BAM); + builder.add_event(0, start_time, end_time, false, period, logger); /* The availability here is the duration from start_time to end_time: 3300 */ ASSERT_EQ(builder.get_available(), 3300); diff --git a/broker/bam/test/exp_builder/exp_builder.cc b/broker/bam/test/exp_builder/exp_builder.cc index 153c0d3bede..f44f3e12db9 100644 --- a/broker/bam/test/exp_builder/exp_builder.cc +++ b/broker/bam/test/exp_builder/exp_builder.cc @@ -28,23 +28,26 @@ #include "com/centreon/broker/bam/service_book.hh" #include "com/centreon/broker/config/applier/init.hh" #include "com/centreon/broker/config/applier/modules.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/neb/service_status.hh" +#include "common/log_v2/log_v2.hh" #include "test-visitor.hh" using namespace com::centreon::broker; +using log_v2 = com::centreon::common::log_v2::log_v2; class BamExpBuilder : public ::testing::Test { protected: std::unique_ptr _visitor; + std::shared_ptr _logger; public: void SetUp() override { + _logger = log_v2::instance().get(log_v2::BAM); try { config::applier::init(0, "test_broker", 0); - log_v2::bam()->set_level(spdlog::level::debug); - log_v2::bam()->flush_on(spdlog::level::debug); + _logger->set_level(spdlog::level::debug); + _logger->flush_on(spdlog::level::debug); } catch (std::exception const& e) { (void)e; } @@ -59,8 +62,8 @@ class BamExpBuilder : public ::testing::Test { TEST_F(BamExpBuilder, Valid1) { bam::exp_parser p("OK IS OK"); - bam::hst_svc_mapping mapping; - bam::exp_builder builder(p.get_postfix(), mapping); + bam::hst_svc_mapping mapping(_logger); + bam::exp_builder builder(p.get_postfix(), mapping, _logger); ASSERT_EQ(builder.get_calls().size(), 0u); ASSERT_EQ(builder.get_services().size(), 0u); bam::bool_value::ptr b(builder.get_tree()); @@ -71,8 +74,8 @@ TEST_F(BamExpBuilder, Valid1) { TEST_F(BamExpBuilder, Valid2) { bam::exp_parser p("OK IS NOT OK"); - bam::hst_svc_mapping mapping; - bam::exp_builder builder(p.get_postfix(), mapping); + bam::hst_svc_mapping mapping(_logger); + bam::exp_builder builder(p.get_postfix(), mapping, _logger); ASSERT_EQ(builder.get_calls().size(), 0u); ASSERT_EQ(builder.get_services().size(), 0u); bam::bool_value::ptr b(builder.get_tree()); @@ -83,8 +86,8 @@ TEST_F(BamExpBuilder, Valid2) { TEST_F(BamExpBuilder, Valid3) { bam::exp_parser p("OK AND CRITICAL"); - bam::hst_svc_mapping mapping; - bam::exp_builder builder(p.get_postfix(), mapping); + bam::hst_svc_mapping mapping(_logger); + bam::exp_builder builder(p.get_postfix(), mapping, _logger); ASSERT_EQ(builder.get_calls().size(), 0u); ASSERT_EQ(builder.get_services().size(), 0u); bam::bool_value::ptr b(builder.get_tree()); @@ -95,8 +98,8 @@ TEST_F(BamExpBuilder, Valid3) { TEST_F(BamExpBuilder, Valid4) { bam::exp_parser p("OK OR CRITICAL"); - bam::hst_svc_mapping mapping; - bam::exp_builder builder(p.get_postfix(), mapping); + bam::hst_svc_mapping mapping(_logger); + bam::exp_builder builder(p.get_postfix(), mapping, _logger); ASSERT_EQ(builder.get_calls().size(), 0u); ASSERT_EQ(builder.get_services().size(), 0u); bam::bool_value::ptr b(builder.get_tree()); @@ -107,8 +110,8 @@ TEST_F(BamExpBuilder, Valid4) { TEST_F(BamExpBuilder, Valid5) { bam::exp_parser p("OK XOR CRITICAL"); - bam::hst_svc_mapping mapping; - bam::exp_builder builder(p.get_postfix(), mapping); + bam::hst_svc_mapping mapping(_logger); + bam::exp_builder builder(p.get_postfix(), mapping, _logger); ASSERT_EQ(builder.get_calls().size(), 0u); ASSERT_EQ(builder.get_services().size(), 0u); bam::bool_value::ptr b(builder.get_tree()); @@ -119,8 +122,8 @@ TEST_F(BamExpBuilder, Valid5) { TEST_F(BamExpBuilder, Valid6) { bam::exp_parser p("2 + 3 * 2 == 8"); - bam::hst_svc_mapping mapping; - bam::exp_builder builder(p.get_postfix(), mapping); + bam::hst_svc_mapping mapping(_logger); + bam::exp_builder builder(p.get_postfix(), mapping, _logger); ASSERT_EQ(builder.get_calls().size(), 0u); ASSERT_EQ(builder.get_services().size(), 0u); bam::bool_value::ptr b(builder.get_tree()); @@ -131,8 +134,8 @@ TEST_F(BamExpBuilder, Valid6) { TEST_F(BamExpBuilder, Valid7) { bam::exp_parser p("2 - 3 * (2 - 6 / 3) == 2"); - bam::hst_svc_mapping mapping; - bam::exp_builder builder(p.get_postfix(), mapping); + bam::hst_svc_mapping mapping(_logger); + bam::exp_builder builder(p.get_postfix(), mapping, _logger); ASSERT_EQ(builder.get_calls().size(), 0u); ASSERT_EQ(builder.get_services().size(), 0u); bam::bool_value::ptr b(builder.get_tree()); @@ -143,8 +146,8 @@ TEST_F(BamExpBuilder, Valid7) { TEST_F(BamExpBuilder, Valid8) { bam::exp_parser p("2 % 3 == 20 % 6"); - bam::hst_svc_mapping mapping; - bam::exp_builder builder(p.get_postfix(), mapping); + bam::hst_svc_mapping mapping(_logger); + bam::exp_builder builder(p.get_postfix(), mapping, _logger); ASSERT_EQ(builder.get_calls().size(), 0u); ASSERT_EQ(builder.get_services().size(), 0u); bam::bool_value::ptr b(builder.get_tree()); @@ -154,39 +157,39 @@ TEST_F(BamExpBuilder, Valid8) { } TEST_F(BamExpBuilder, UnknownService1) { - config::applier::modules modules; + config::applier::modules modules(_logger); modules.load_file("./broker/neb/10-neb.so"); bam::exp_parser p("{host_1 service_1} {IS} {OK}"); - bam::hst_svc_mapping mapping; + bam::hst_svc_mapping mapping(_logger); mapping.set_service("host_1", "service_1", 1, 1, true); - bam::exp_builder builder(p.get_postfix(), mapping); + bam::exp_builder builder(p.get_postfix(), mapping, _logger); bam::bool_value::ptr b(builder.get_tree()); ASSERT_FALSE(b->state_known()); ASSERT_FALSE(b->boolean_value()); } TEST_F(BamExpBuilder, UnknownService2) { - config::applier::modules modules; + config::applier::modules modules(_logger); modules.load_file("./broker/neb/10-neb.so"); bam::exp_parser p("{host_1 service_1} {IS} {CRITICAL}"); - bam::hst_svc_mapping mapping; + bam::hst_svc_mapping mapping(_logger); mapping.set_service("host_1", "service_1", 1, 1, true); - bam::exp_builder builder(p.get_postfix(), mapping); + bam::exp_builder builder(p.get_postfix(), mapping, _logger); bam::bool_value::ptr b(builder.get_tree()); ASSERT_FALSE(b->state_known()); ASSERT_FALSE(b->boolean_value()); } TEST_F(BamExpBuilder, OkService2) { - config::applier::modules modules; + config::applier::modules modules(_logger); modules.load_file("./broker/neb/10-neb.so"); bam::exp_parser p("{host_1 service_1} {IS} {CRITICAL}"); - bam::hst_svc_mapping mapping; + bam::hst_svc_mapping mapping(_logger); mapping.set_service("host_1", "service_1", 1, 1, true); - bam::exp_builder builder(p.get_postfix(), mapping); + bam::exp_builder builder(p.get_postfix(), mapping, _logger); bam::bool_value::ptr b(builder.get_tree()); - bam::service_book book; + bam::service_book book(_logger); for (auto& svc : builder.get_services()) book.listen(svc->get_host_id(), svc->get_service_id(), svc.get()); @@ -203,15 +206,15 @@ TEST_F(BamExpBuilder, OkService2) { } TEST_F(BamExpBuilder, CritService2) { - config::applier::modules modules; + config::applier::modules modules(_logger); modules.load_file("./broker/neb/10-neb.so"); bam::exp_parser p("{host_1 service_1} {IS} {CRITICAL}"); - bam::hst_svc_mapping mapping; + bam::hst_svc_mapping mapping(_logger); mapping.set_service("host_1", "service_1", 1, 1, true); - bam::exp_builder builder(p.get_postfix(), mapping); + bam::exp_builder builder(p.get_postfix(), mapping, _logger); bam::bool_value::ptr b(builder.get_tree()); - bam::service_book book; + bam::service_book book(_logger); for (auto& svc : builder.get_services()) book.listen(svc->get_host_id(), svc->get_service_id(), svc.get()); @@ -228,17 +231,17 @@ TEST_F(BamExpBuilder, CritService2) { } TEST_F(BamExpBuilder, CritOkService1) { - config::applier::modules modules; + config::applier::modules modules(_logger); modules.load_file("./broker/neb/10-neb.so"); bam::exp_parser p( "{host_1 service_1} {IS} {CRITICAL} {OR} {host_1 service_2} {IS} {OK}"); - bam::hst_svc_mapping mapping; + bam::hst_svc_mapping mapping(_logger); mapping.set_service("host_1", "service_1", 1, 1, true); mapping.set_service("host_1", "service_2", 1, 2, true); - bam::exp_builder builder(p.get_postfix(), mapping); + bam::exp_builder builder(p.get_postfix(), mapping, _logger); bam::bool_value::ptr b(builder.get_tree()); - bam::service_book book; + bam::service_book book(_logger); for (auto& svc : builder.get_services()) book.listen(svc->get_host_id(), svc->get_service_id(), svc.get()); @@ -269,17 +272,17 @@ TEST_F(BamExpBuilder, CritOkService1) { } TEST_F(BamExpBuilder, CritOkService2) { - config::applier::modules modules; + config::applier::modules modules(_logger); modules.load_file("./broker/neb/10-neb.so"); bam::exp_parser p( "{host_1 service_1} {IS} {CRITICAL} {OR} {host_1 service_2} {IS} {OK}"); - bam::hst_svc_mapping mapping; + bam::hst_svc_mapping mapping(_logger); mapping.set_service("host_1", "service_1", 1, 1, true); mapping.set_service("host_1", "service_2", 1, 2, true); - bam::exp_builder builder(p.get_postfix(), mapping); + bam::exp_builder builder(p.get_postfix(), mapping, _logger); bam::bool_value::ptr b(builder.get_tree()); - bam::service_book book; + bam::service_book book(_logger); for (auto& svc : builder.get_services()) book.listen(svc->get_host_id(), svc->get_service_id(), svc.get()); @@ -317,17 +320,17 @@ TEST_F(BamExpBuilder, CritOkService2) { } TEST_F(BamExpBuilder, CritOkService3) { - config::applier::modules modules; + config::applier::modules modules(_logger); modules.load_file("./broker/neb/10-neb.so"); bam::exp_parser p( "{host_1 service_1} {IS} {CRITICAL} {OR} {host_1 service_2} {IS} {OK}"); - bam::hst_svc_mapping mapping; + bam::hst_svc_mapping mapping(_logger); mapping.set_service("host_1", "service_1", 1, 1, true); mapping.set_service("host_1", "service_2", 1, 2, true); - bam::exp_builder builder(p.get_postfix(), mapping); + bam::exp_builder builder(p.get_postfix(), mapping, _logger); bam::bool_value::ptr b(builder.get_tree()); - bam::service_book book; + bam::service_book book(_logger); for (auto& svc : builder.get_services()) book.listen(svc->get_host_id(), svc->get_service_id(), svc.get()); @@ -365,17 +368,17 @@ TEST_F(BamExpBuilder, CritOkService3) { } TEST_F(BamExpBuilder, CritAndOkService1) { - config::applier::modules modules; + config::applier::modules modules(_logger); modules.load_file("./broker/neb/10-neb.so"); bam::exp_parser p( "{host_1 service_1} {IS} {CRITICAL} {AND} {host_1 service_2} {IS} {OK}"); - bam::hst_svc_mapping mapping; + bam::hst_svc_mapping mapping(_logger); mapping.set_service("host_1", "service_1", 1, 1, true); mapping.set_service("host_1", "service_2", 1, 2, true); - bam::exp_builder builder(p.get_postfix(), mapping); + bam::exp_builder builder(p.get_postfix(), mapping, _logger); bam::bool_value::ptr b(builder.get_tree()); - bam::service_book book; + bam::service_book book(_logger); for (auto& svc : builder.get_services()) book.listen(svc->get_host_id(), svc->get_service_id(), svc.get()); @@ -414,17 +417,17 @@ TEST_F(BamExpBuilder, CritAndOkService1) { } TEST_F(BamExpBuilder, CritAndOkService2) { - config::applier::modules modules; + config::applier::modules modules(_logger); modules.load_file("./broker/neb/10-neb.so"); bam::exp_parser p( "{host_1 service_1} {IS} {CRITICAL} {AND} {host_1 service_2} {IS} {OK}"); - bam::hst_svc_mapping mapping; + bam::hst_svc_mapping mapping(_logger); mapping.set_service("host_1", "service_1", 1, 1, true); mapping.set_service("host_1", "service_2", 1, 2, true); - bam::exp_builder builder(p.get_postfix(), mapping); + bam::exp_builder builder(p.get_postfix(), mapping, _logger); bam::bool_value::ptr b(builder.get_tree()); - bam::service_book book; + bam::service_book book(_logger); for (auto& svc : builder.get_services()) book.listen(svc->get_host_id(), svc->get_service_id(), svc.get()); @@ -462,17 +465,17 @@ TEST_F(BamExpBuilder, CritAndOkService2) { } TEST_F(BamExpBuilder, CritAndOkService3) { - config::applier::modules modules; + config::applier::modules modules(_logger); modules.load_file("./broker/neb/10-neb.so"); bam::exp_parser p( "{host_1 service_1} {IS} {CRITICAL} {AND} {host_1 service_2} {IS} {OK}"); - bam::hst_svc_mapping mapping; + bam::hst_svc_mapping mapping(_logger); mapping.set_service("host_1", "service_1", 1, 1, true); mapping.set_service("host_1", "service_2", 1, 2, true); - bam::exp_builder builder(p.get_postfix(), mapping); + bam::exp_builder builder(p.get_postfix(), mapping, _logger); bam::bool_value::ptr b(builder.get_tree()); - bam::service_book book; + bam::service_book book(_logger); for (auto& svc : builder.get_services()) book.listen(svc->get_host_id(), svc->get_service_id(), svc.get()); @@ -510,15 +513,15 @@ TEST_F(BamExpBuilder, CritAndOkService3) { } TEST_F(BamExpBuilder, NotCritService3) { - config::applier::modules modules; + config::applier::modules modules(_logger); modules.load_file("./broker/neb/10-neb.so"); bam::exp_parser p("({host_1 service_1} {NOT} {CRITICAL})"); - bam::hst_svc_mapping mapping; + bam::hst_svc_mapping mapping(_logger); mapping.set_service("host_1", "service_1", 1, 1, true); - bam::exp_builder builder(p.get_postfix(), mapping); + bam::exp_builder builder(p.get_postfix(), mapping, _logger); bam::bool_value::ptr b(builder.get_tree()); - bam::service_book book; + bam::service_book book(_logger); for (auto& svc : builder.get_services()) book.listen(svc->get_host_id(), svc->get_service_id(), svc.get()); @@ -546,18 +549,18 @@ TEST_F(BamExpBuilder, NotCritService3) { } TEST_F(BamExpBuilder, ExpressionWithService) { - config::applier::modules modules; + config::applier::modules modules(_logger); modules.load_file("./broker/neb/10-neb.so"); bam::exp_parser p("({host_1 service_1} {NOT} {CRITICAL})"); - bam::hst_svc_mapping mapping; + bam::hst_svc_mapping mapping(_logger); mapping.set_service("host_1", "service_1", 1, 1, true); - bam::exp_builder builder(p.get_postfix(), mapping); + bam::exp_builder builder(p.get_postfix(), mapping, _logger); bam::bool_value::ptr b(builder.get_tree()); - bam::bool_expression exp(1, true); + bam::bool_expression exp(1, true, _logger); exp.set_expression(b); - bam::service_book book; + bam::service_book book(_logger); for (auto& svc : builder.get_services()) book.listen(svc->get_host_id(), svc->get_service_id(), svc.get()); @@ -585,18 +588,18 @@ TEST_F(BamExpBuilder, ExpressionWithService) { } TEST_F(BamExpBuilder, ReverseExpressionWithService) { - config::applier::modules modules; + config::applier::modules modules(_logger); modules.load_file("./broker/neb/10-neb.so"); bam::exp_parser p("({host_1 service_1} {NOT} {CRITICAL})"); - bam::hst_svc_mapping mapping; + bam::hst_svc_mapping mapping(_logger); mapping.set_service("host_1", "service_1", 1, 1, true); - bam::exp_builder builder(p.get_postfix(), mapping); + bam::exp_builder builder(p.get_postfix(), mapping, _logger); bam::bool_value::ptr b(builder.get_tree()); - bam::bool_expression exp(1, false); + bam::bool_expression exp(1, false, _logger); exp.set_expression(b); - bam::service_book book; + bam::service_book book(_logger); for (auto& svc : builder.get_services()) book.listen(svc->get_host_id(), svc->get_service_id(), svc.get()); @@ -624,23 +627,24 @@ TEST_F(BamExpBuilder, ReverseExpressionWithService) { } TEST_F(BamExpBuilder, KpiBoolexpWithService) { - config::applier::modules modules; + config::applier::modules modules(_logger); modules.load_file("./broker/neb/10-neb.so"); bam::exp_parser p("({host_1 service_1} {NOT} {CRITICAL})"); - bam::hst_svc_mapping mapping; + bam::hst_svc_mapping mapping(_logger); mapping.set_service("host_1", "service_1", 1, 1, true); - bam::exp_builder builder(p.get_postfix(), mapping); + bam::exp_builder builder(p.get_postfix(), mapping, _logger); bam::bool_value::ptr b(builder.get_tree()); - auto exp = std::make_shared(1, true); + auto exp = std::make_shared(1, true, _logger); exp->set_expression(b); b->add_parent(exp); - auto kpi = std::make_shared(1, 1, "test_boool_exp"); + auto kpi = + std::make_shared(1, 1, "test_boool_exp", _logger); kpi->link_boolexp(exp); exp->add_parent(kpi); - bam::service_book book; + bam::service_book book(_logger); for (auto& svc : builder.get_services()) book.listen(svc->get_host_id(), svc->get_service_id(), svc.get()); @@ -668,23 +672,24 @@ TEST_F(BamExpBuilder, KpiBoolexpWithService) { } TEST_F(BamExpBuilder, KpiBoolexpReversedImpactWithService) { - config::applier::modules modules; + config::applier::modules modules(_logger); modules.load_file("./broker/neb/10-neb.so"); bam::exp_parser p("({host_1 service_1} {NOT} {CRITICAL})"); - bam::hst_svc_mapping mapping; + bam::hst_svc_mapping mapping(_logger); mapping.set_service("host_1", "service_1", 1, 1, true); - bam::exp_builder builder(p.get_postfix(), mapping); + bam::exp_builder builder(p.get_postfix(), mapping, _logger); bam::bool_value::ptr b(builder.get_tree()); - auto exp = std::make_shared(1, false); + auto exp = std::make_shared(1, false, _logger); exp->set_expression(b); b->add_parent(exp); - auto kpi = std::make_shared(1, 1, "test_boool_exp"); + auto kpi = + std::make_shared(1, 1, "test_boool_exp", _logger); kpi->link_boolexp(exp); exp->add_parent(kpi); - bam::service_book book; + bam::service_book book(_logger); for (auto& svc : builder.get_services()) book.listen(svc->get_host_id(), svc->get_service_id(), svc.get()); @@ -710,18 +715,18 @@ TEST_F(BamExpBuilder, KpiBoolexpReversedImpactWithService) { } TEST_F(BamExpBuilder, BoolexpServiceXorService) { - config::applier::modules modules; + config::applier::modules modules(_logger); modules.load_file("./broker/neb/10-neb.so"); bam::exp_parser p( "({host_1 service_1} {IS} {CRITICAL}) {XOR} ({host_1 service_2} {IS} " "{CRITICAL})"); - bam::hst_svc_mapping mapping; + bam::hst_svc_mapping mapping(_logger); mapping.set_service("host_1", "service_1", 1, 1, true); mapping.set_service("host_1", "service_2", 1, 2, true); - bam::exp_builder builder(p.get_postfix(), mapping); + bam::exp_builder builder(p.get_postfix(), mapping, _logger); bam::bool_value::ptr b(builder.get_tree()); - bam::service_book book; + bam::service_book book(_logger); for (auto& svc : builder.get_services()) book.listen(svc->get_host_id(), svc->get_service_id(), svc.get()); @@ -766,16 +771,16 @@ TEST_F(BamExpBuilder, BoolexpServiceXorService) { } TEST_F(BamExpBuilder, BoolexpLTWithServiceStatus) { - config::applier::modules modules; + config::applier::modules modules(_logger); modules.load_file("./broker/neb/10-neb.so"); bam::exp_parser p("{host_1 service_1} < {host_1 service_2}"); - bam::hst_svc_mapping mapping; + bam::hst_svc_mapping mapping(_logger); mapping.set_service("host_1", "service_1", 1, 1, true); mapping.set_service("host_1", "service_2", 1, 2, true); - bam::exp_builder builder(p.get_postfix(), mapping); + bam::exp_builder builder(p.get_postfix(), mapping, _logger); bam::bool_value::ptr b(builder.get_tree()); - bam::service_book book; + bam::service_book book(_logger); for (auto& svc : builder.get_services()) book.listen(svc->get_host_id(), svc->get_service_id(), svc.get()); @@ -820,18 +825,18 @@ TEST_F(BamExpBuilder, BoolexpLTWithServiceStatus) { } TEST_F(BamExpBuilder, BoolexpKpiService) { - config::applier::modules modules; + config::applier::modules modules(_logger); modules.load_file("./broker/neb/10-neb.so"); bam::exp_parser p( "{host_1 service_1} {IS} {CRITICAL} {OR} {host_1 service_2} {IS} " "{CRITICAL}"); - bam::hst_svc_mapping mapping; + bam::hst_svc_mapping mapping(_logger); mapping.set_service("host_1", "service_1", 1, 1, true); mapping.set_service("host_1", "service_2", 1, 2, true); - bam::exp_builder builder(p.get_postfix(), mapping); + bam::exp_builder builder(p.get_postfix(), mapping, _logger); bam::bool_value::ptr b(builder.get_tree()); - bam::service_book book; + bam::service_book book(_logger); for (auto& svc : builder.get_services()) book.listen(svc->get_host_id(), svc->get_service_id(), svc.get()); @@ -885,34 +890,35 @@ TEST_F(BamExpBuilder, BoolexpKpiService) { /* Same test as BoolexpKpiService but with the point of view of a boolean * expression. */ TEST_F(BamExpBuilder, BoolexpKpiServiceAndBoolExpression) { - config::applier::modules modules; + config::applier::modules modules(_logger); modules.load_file("./broker/neb/10-neb.so"); bam::exp_parser p( "{host_1 service_1} {IS} {CRITICAL} {OR} {host_1 service_2} {IS} " "{CRITICAL}"); - bam::hst_svc_mapping mapping; + bam::hst_svc_mapping mapping(_logger); mapping.set_service("host_1", "service_1", 1, 1, true); mapping.set_service("host_1", "service_2", 1, 2, true); - bam::exp_builder builder(p.get_postfix(), mapping); + bam::exp_builder builder(p.get_postfix(), mapping, _logger); bam::bool_value::ptr b(builder.get_tree()); - auto exp = std::make_shared(1, true); + auto exp = std::make_shared(1, true, _logger); exp->set_expression(b); b->add_parent(exp); - auto kpi = std::make_shared(1, 1, "test_boool_exp"); + auto kpi = + std::make_shared(1, 1, "test_boool_exp", _logger); kpi->set_impact(100); kpi->link_boolexp(exp); exp->add_parent(kpi); - auto ba = std::make_shared(1, 30, 300, false); + auto ba = std::make_shared(1, 30, 300, false, _logger); ba->set_name("ba-kpi-service"); ba->set_level_warning(70); ba->set_level_warning(80); ba->add_impact(kpi); kpi->add_parent(ba); - bam::service_book book; + bam::service_book book(_logger); for (auto& svc : builder.get_services()) book.listen(svc->get_host_id(), svc->get_service_id(), svc.get()); @@ -991,34 +997,35 @@ TEST_F(BamExpBuilder, BoolexpKpiServiceAndBoolExpression) { /* Same test as BoolexpKpiServiceAndBoolExpression but with AND operator and * with impact_if set to false. */ TEST_F(BamExpBuilder, BoolexpKpiServiceAndBoolExpressionAndOperator) { - config::applier::modules modules; + config::applier::modules modules(_logger); modules.load_file("./broker/neb/10-neb.so"); bam::exp_parser p( "{host_1 service_1} {IS} {CRITICAL} {AND} {host_1 service_2} {IS} " "{CRITICAL}"); - bam::hst_svc_mapping mapping; + bam::hst_svc_mapping mapping(_logger); mapping.set_service("host_1", "service_1", 1, 1, true); mapping.set_service("host_1", "service_2", 1, 2, true); - bam::exp_builder builder(p.get_postfix(), mapping); + bam::exp_builder builder(p.get_postfix(), mapping, _logger); bam::bool_value::ptr b(builder.get_tree()); - auto exp = std::make_shared(1, false); + auto exp = std::make_shared(1, false, _logger); exp->set_expression(b); b->add_parent(exp); - auto kpi = std::make_shared(1, 1, "test_boool_exp"); + auto kpi = + std::make_shared(1, 1, "test_boool_exp", _logger); kpi->set_impact(100); kpi->link_boolexp(exp); exp->add_parent(kpi); - auto ba = std::make_shared(1, 30, 300, false); + auto ba = std::make_shared(1, 30, 300, false, _logger); ba->set_name("ba-kpi-service"); ba->set_level_warning(70); ba->set_level_warning(80); ba->add_impact(kpi); kpi->add_parent(ba); - bam::service_book book; + bam::service_book book(_logger); for (auto& svc : builder.get_services()) book.listen(svc->get_host_id(), svc->get_service_id(), svc.get()); diff --git a/broker/bam/test/monitoring_stream.cc b/broker/bam/test/monitoring_stream.cc index 7877e2d4957..1c9b0e64d04 100644 --- a/broker/bam/test/monitoring_stream.cc +++ b/broker/bam/test/monitoring_stream.cc @@ -1,20 +1,20 @@ /** -* Copyright 2014 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2014, 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/bam/monitoring_stream.hh" diff --git a/broker/core/inc/com/centreon/broker/bbdo/internal.hh b/broker/core/inc/com/centreon/broker/bbdo/internal.hh index 440ce2e182f..82d46e774f9 100644 --- a/broker/core/inc/com/centreon/broker/bbdo/internal.hh +++ b/broker/core/inc/com/centreon/broker/bbdo/internal.hh @@ -1,5 +1,5 @@ /** - * Copyright 2013,2017,2020-2023 Centreon + * Copyright 2013,2017,2020-2024 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,7 +29,8 @@ #define BBDO_VERSION_PATCH 0 constexpr uint32_t BBDO_HEADER_SIZE = 16u; -namespace com::centreon::broker::bbdo { +namespace com::centreon::broker { +namespace bbdo { using pb_welcome = com::centreon::broker::io::protobuf; -using pb_bench = - com::centreon::broker::io::protobuf; +using pb_bench = com::centreon::broker::io:: + protobuf; // Load/unload of BBDO protocol. void load(); void unload(); -} // namespace com::centreon::broker::bbdo +} // namespace bbdo + +namespace local { +using pb_stop = com::centreon::broker::io:: + protobuf; +} + +} // namespace com::centreon::broker #endif // !CCB_BBDO_INTERNAL_HH diff --git a/broker/core/inc/com/centreon/broker/bbdo/stream.hh b/broker/core/inc/com/centreon/broker/bbdo/stream.hh index 264e0b4e440..065690617f3 100644 --- a/broker/core/inc/com/centreon/broker/bbdo/stream.hh +++ b/broker/core/inc/com/centreon/broker/bbdo/stream.hh @@ -21,6 +21,7 @@ #include "bbdo/bbdo/bbdo_version.hh" #include "com/centreon/broker/io/extension.hh" +#include "com/centreon/broker/io/raw.hh" #include "com/centreon/broker/io/stream.hh" namespace com::centreon::broker::bbdo { @@ -62,7 +63,9 @@ class stream : public io::stream { std::deque> _buf; public: - buffer(uint32_t event_id, uint32_t source_id, uint32_t dest_id, + buffer(uint32_t event_id, + uint32_t source_id, + uint32_t dest_id, std::vector&& v) : _event_id(event_id), _source_id(source_id), _dest_id(dest_id) { _buf.push_back(v); @@ -86,7 +89,8 @@ class stream : public io::stream { } ~buffer() noexcept = default; - bool matches(uint32_t event_id, uint32_t source_id, + bool matches(uint32_t event_id, + uint32_t source_id, uint32_t dest_id) const noexcept { return event_id == _event_id && source_id == _source_id && dest_id == _dest_id; @@ -94,10 +98,12 @@ class stream : public io::stream { std::vector to_vector() { size_t s = 0; - for (auto& v : _buf) s += v.size(); + for (auto& v : _buf) + s += v.size(); std::vector retval; retval.reserve(s); - for (auto& v : _buf) retval.insert(retval.end(), v.begin(), v.end()); + for (auto& v : _buf) + retval.insert(retval.end(), v.begin(), v.end()); _buf.clear(); return retval; } @@ -147,17 +153,27 @@ class stream : public io::stream { std::list> _extensions; bbdo::bbdo_version _bbdo_version; + /* bbdo logger */ + std::shared_ptr _logger; + void _write(std::shared_ptr const& d); bool _read_any(std::shared_ptr& d, time_t deadline); void _send_event_stop_and_wait_for_ack(); std::string _get_extension_names(bool mandatory) const; std::string _poller_name; uint64_t _poller_id = 0u; + io::data* unserialize(uint32_t event_type, + uint32_t source_id, + uint32_t destination_id, + const char* buffer, + uint32_t size); + io::raw* serialize(const io::data& e); public: enum negotiation_type { negotiate_first = 1, negotiate_second, negotiated }; - stream(bool is_input, bool grpc_serialized = false, + stream(bool is_input, + bool grpc_serialized = false, const std::list>& extensions = {}); ~stream(); stream(const stream&) = delete; diff --git a/broker/core/inc/com/centreon/broker/cache/global_cache.hh b/broker/core/inc/com/centreon/broker/cache/global_cache.hh index a5981da910b..58a12960287 100644 --- a/broker/core/inc/com/centreon/broker/cache/global_cache.hh +++ b/broker/core/inc/com/centreon/broker/cache/global_cache.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_GLOBAL_CACHE_HH #define CCB_GLOBAL_CACHE_HH @@ -141,11 +141,14 @@ class global_cache : public std::enable_shared_from_this { protected: const std::string _file_path; + std::shared_ptr _logger; + std::unique_ptr _file; mutable absl::Mutex _protect; - global_cache(const std::string& file_path); + global_cache(const std::string& file_path, + const std::shared_ptr& logger); void allocation_exception_handler(); diff --git a/broker/core/inc/com/centreon/broker/cache/global_cache_data.hh b/broker/core/inc/com/centreon/broker/cache/global_cache_data.hh index 2a59da41ef4..02a8307c9ed 100644 --- a/broker/core/inc/com/centreon/broker/cache/global_cache_data.hh +++ b/broker/core/inc/com/centreon/broker/cache/global_cache_data.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_GLOBAL_CACHE_DATA_HH #define CCB_GLOBAL_CACHE_DATA_HH @@ -27,9 +27,12 @@ #include #include #include +#include "common/log_v2/log_v2.hh" #include "global_cache.hh" +using com::centreon::common::log_v2::log_v2; + namespace com::centreon::broker { namespace cache { @@ -227,7 +230,8 @@ class global_cache_data : public global_cache { void managed_map(bool create) override; public: - global_cache_data(const std::string& file_path) : global_cache(file_path) {} + global_cache_data(const std::string& file_path) + : global_cache(file_path, log_v2::instance().get(log_v2::CORE)) {} void set_metric_info(uint64_t metric_id, uint64_t index_id, diff --git a/broker/core/inc/com/centreon/broker/compression/stream.hh b/broker/core/inc/com/centreon/broker/compression/stream.hh index 4c97ede35e4..21c10e47e36 100644 --- a/broker/core/inc/com/centreon/broker/compression/stream.hh +++ b/broker/core/inc/com/centreon/broker/compression/stream.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2011-2013,2015,2017, 2020-2021 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2011-2013,2015,2017, 2020-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_COMPRESSION_STREAM_HH #define CCB_COMPRESSION_STREAM_HH @@ -38,6 +38,9 @@ class stream : public io::stream { size_t _size; std::vector _wbuffer; + /* The stream logger */ + std::shared_ptr _logger; + void _flush(); void _get_data(int size, time_t timeout); diff --git a/broker/core/inc/com/centreon/broker/config/applier/endpoint.hh b/broker/core/inc/com/centreon/broker/config/applier/endpoint.hh index a4baacd7a2a..30099ecac64 100644 --- a/broker/core/inc/com/centreon/broker/config/applier/endpoint.hh +++ b/broker/core/inc/com/centreon/broker/config/applier/endpoint.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2011-2012,2015 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2011-2012,2015-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_CONFIG_APPLIER_ENDPOINT_HH #define CCB_CONFIG_APPLIER_ENDPOINT_HH @@ -51,6 +51,8 @@ class endpoint { std::timed_mutex _endpointsm; std::atomic_bool _discarding; + std::shared_ptr _logger; + endpoint(); ~endpoint(); void _discard(); diff --git a/broker/core/inc/com/centreon/broker/config/applier/modules.hh b/broker/core/inc/com/centreon/broker/config/applier/modules.hh index e370d74f841..5a6fea67f7d 100644 --- a/broker/core/inc/com/centreon/broker/config/applier/modules.hh +++ b/broker/core/inc/com/centreon/broker/config/applier/modules.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2011-2012, 2021 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2011-2012, 2021-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_CONFIG_APPLIER_MODULES_HH #define CCB_CONFIG_APPLIER_MODULES_HH @@ -34,6 +34,7 @@ namespace applier { * Load modules as per the configuration. */ class modules { + std::shared_ptr _logger; std::map> _handles; mutable std::mutex _m_modules; @@ -42,7 +43,7 @@ class modules { public: typedef std::map>::iterator iterator; - modules() = default; + modules(const std::shared_ptr& logger) : _logger(logger) {} ~modules() noexcept = default; modules(const modules&) = delete; modules& operator=(const modules&) = delete; diff --git a/broker/core/inc/com/centreon/broker/config/applier/state.hh b/broker/core/inc/com/centreon/broker/config/applier/state.hh index 54e5edcc289..6e11f52b6b9 100644 --- a/broker/core/inc/com/centreon/broker/config/applier/state.hh +++ b/broker/core/inc/com/centreon/broker/config/applier/state.hh @@ -55,7 +55,7 @@ class state { absl::flat_hash_map _connected_pollers; mutable std::mutex _connected_pollers_m; - state(); + state(const std::shared_ptr& logger); ~state() noexcept = default; public: diff --git a/broker/core/inc/com/centreon/broker/config/state.hh b/broker/core/inc/com/centreon/broker/config/state.hh index 1893013ff28..2b724d2459e 100644 --- a/broker/core/inc/com/centreon/broker/config/state.hh +++ b/broker/core/inc/com/centreon/broker/config/state.hh @@ -1,29 +1,29 @@ -/* -** Copyright 2011-2012,2017, 2021 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2011-2012,2017, 2021-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_CONFIG_STATE_HH #define CCB_CONFIG_STATE_HH -#include #include #include "bbdo/bbdo/bbdo_version.hh" #include "com/centreon/broker/config/endpoint.hh" +#include "common/log_v2/config.hh" namespace com::centreon::broker::config { @@ -54,19 +54,7 @@ class state { std::string _poller_name; size_t _pool_size; - struct log { - std::string directory; - std::string filename; - std::size_t max_size; - uint32_t flush_period; - bool log_pid; - bool log_source; - absl::flat_hash_map loggers; - - std::string log_path() const { - return fmt::format("{}/{}", directory, filename); - } - } _log_conf; + common::log_v2::config _log_conf; public: /** @@ -142,8 +130,8 @@ class state { int pool_size() const noexcept; void poller_name(std::string const& name); std::string const& poller_name() const noexcept; - log& mut_log_conf(); - const log& log_conf() const; + common::log_v2::config& mut_log_conf(); + const common::log_v2::config& log_conf() const; stats_exporter_conf& mut_stats_exporter(); const stats_exporter_conf& get_stats_exporter() const; }; diff --git a/broker/core/inc/com/centreon/broker/file/stream.hh b/broker/core/inc/com/centreon/broker/file/stream.hh index cb79de092b6..a776f1a5e22 100644 --- a/broker/core/inc/com/centreon/broker/file/stream.hh +++ b/broker/core/inc/com/centreon/broker/file/stream.hh @@ -22,6 +22,7 @@ #include "broker.pb.h" #include "com/centreon/broker/file/splitter.hh" #include "com/centreon/broker/io/stream.hh" +#include "com/centreon/broker/stats/center.hh" namespace com::centreon::broker::file { /** @@ -41,12 +42,15 @@ class stream : public io::stream { std::array, 10> _stats_perc; size_t _stats_idx; size_t _stats_size; + std::shared_ptr _center; void _update_stats(); public: - stream(const std::string& path, QueueFileStats* s, - uint32_t max_file_size = 100000000u, bool auto_delete = false); + stream(const std::string& path, + QueueFileStats* s, + uint32_t max_file_size = 100000000u, + bool auto_delete = false); ~stream() noexcept = default; stream(const stream&) = delete; stream& operator=(const stream&) = delete; diff --git a/broker/core/inc/com/centreon/broker/io/endpoint.hh b/broker/core/inc/com/centreon/broker/io/endpoint.hh index 35577ceb934..5117d15316d 100644 --- a/broker/core/inc/com/centreon/broker/io/endpoint.hh +++ b/broker/core/inc/com/centreon/broker/io/endpoint.hh @@ -41,15 +41,27 @@ namespace io { class endpoint { bool _is_acceptor; /* The mandatory filters for the stream configured from this endpoint to - * correctly work. This object can be empty. It filters categories and - * elements. */ - const multiplexing::muxer_filter _stream_mandatory_filter; + * correctly work. It filters categories and elements the following way: + * * if configured with all events, the filters configured in the stream are + * used as such. + * * otherwise, the filters configured in the stream are replaced by the + * mandatory ones. + */ + multiplexing::muxer_filter _stream_mandatory_filter; + + /* The forbidden filters for the stream configured from this endpoint to + * correctly work. All filters given here must not be set into the stream, + * otherwise it will work badly. + */ + multiplexing::muxer_filter _stream_forbidden_filter; protected: std::shared_ptr _from; public: - endpoint(bool is_accptr, const multiplexing::muxer_filter& filter); + endpoint(bool is_accptr, + const multiplexing::muxer_filter& mandatory_filter, + const multiplexing::muxer_filter& forbidden_filter); endpoint(const endpoint& other); virtual ~endpoint() noexcept = default; endpoint& operator=(const endpoint& other) = delete; @@ -62,13 +74,25 @@ class endpoint { /** * @brief accessor to the filter wanted by the stream used by this endpoint. - * This filter is defined by the stream itself and cannot change. + * This filter is defined by the stream itself and cannot change. It lists + * categories/elements that are mandatory for the stream to work. * * @return A multiplexing::muxer_filter reference. */ const multiplexing::muxer_filter& get_stream_mandatory_filter() const { return _stream_mandatory_filter; } + + /** + * @brief accessor to the filter forbidden by the stream used by this + * endpoint. This filter is defined by the stream itself and cannot change. It + * lists categories/elements that are mandatory for the stream to work. + * + * @return A multiplexing::muxer_filter reference. + */ + const multiplexing::muxer_filter& get_stream_forbidden_filter() const { + return _stream_forbidden_filter; + } }; } // namespace io diff --git a/broker/core/inc/com/centreon/broker/io/limit_endpoint.hh b/broker/core/inc/com/centreon/broker/io/limit_endpoint.hh index a3453578141..b9658d87bf4 100644 --- a/broker/core/inc/com/centreon/broker/io/limit_endpoint.hh +++ b/broker/core/inc/com/centreon/broker/io/limit_endpoint.hh @@ -1,29 +1,27 @@ -/* -** Copyright 2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_IO_LIMIT_ENDPOINT_HH #define CCB_IO_LIMIT_ENDPOINT_HH #include "endpoint.hh" -namespace com::centreon::broker { - -namespace io { +namespace com::centreon::broker::io { class limit_endpoint : public endpoint { protected: @@ -33,8 +31,19 @@ class limit_endpoint : public endpoint { mutable std::time_t _is_ready_now; public: - limit_endpoint(bool is_accptr, const multiplexing::muxer_filter& filter) - : endpoint(is_accptr, filter), _is_ready_count(0), _is_ready_now(0) {} + /** + * @brief Constructor of a limit_endpoint. + * + * @param is_accptr A boolean to tell if this endpoint is an acceptor. + * @param mandatory_filter Mandatory filters for the stream. + * @param forbidden_filter Forbidden filters for the stream. + */ + limit_endpoint(bool is_accptr, + const multiplexing::muxer_filter& mandatory_filter, + const multiplexing::muxer_filter& forbidden_filter) + : endpoint(is_accptr, mandatory_filter, forbidden_filter), + _is_ready_count(0), + _is_ready_now(0) {} std::shared_ptr open() override; bool is_ready() const override; @@ -42,8 +51,6 @@ class limit_endpoint : public endpoint { virtual std::shared_ptr create_stream() = 0; }; -} // namespace io - -} +} // namespace com::centreon::broker::io #endif // !CCB_IO_LIMIT_ENDPOINT_HH diff --git a/broker/core/inc/com/centreon/broker/io/protobuf.hh b/broker/core/inc/com/centreon/broker/io/protobuf.hh index ecd105d816e..63004d9ec60 100644 --- a/broker/core/inc/com/centreon/broker/io/protobuf.hh +++ b/broker/core/inc/com/centreon/broker/io/protobuf.hh @@ -212,8 +212,8 @@ template void protobuf::dump(std::ostream& s) const { data::dump(s); std::string dump{this->obj().ShortDebugString()}; - if (dump.size() > 200) { - dump.resize(200); + if (dump.size() > 2000) { + dump.resize(2000); s << fmt::format(" content:'{}...'", dump); } else s << " content:'" << dump << '\''; diff --git a/broker/core/inc/com/centreon/broker/log_v2.hh b/broker/core/inc/com/centreon/broker/log_v2.hh deleted file mode 100644 index 4869ce9a7d0..00000000000 --- a/broker/core/inc/com/centreon/broker/log_v2.hh +++ /dev/null @@ -1,158 +0,0 @@ -/** - * Copyright 2020-2023 Centreon - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * For more information : contact@centreon.com - */ -#ifndef CENTREON_BROKER_CORE_INC_COM_CENTREON_BROKER_LOG_V2_HH_ -#define CENTREON_BROKER_CORE_INC_COM_CENTREON_BROKER_LOG_V2_HH_ - -#include "com/centreon/broker/config/state.hh" -#include "com/centreon/engine/log_v2_base.hh" - -namespace com::centreon::broker { - -class log_v2 : public com::centreon::engine::log_v2_base { - std::atomic_bool _running; - asio::system_timer _flush_timer; - std::mutex _flush_timer_m; - bool _flush_timer_active; - std::shared_ptr _io_context; - - static std::shared_ptr _instance; - - enum logger { - log_bam, - log_bbdo, - log_config, - log_core, - log_graphite, - log_grpc, - log_influxdb, - log_lua, - log_neb, - log_notification, - log_perfdata, - log_processing, - log_rrd, - log_sql, - log_stats, - log_tcp, - log_tls, - log_victoria_metrics, - log_max // used only to size the array - }; - std::array, log_max> _log; - - std::mutex _load_m; - - log_v2(const std::shared_ptr& io_context); - - std::shared_ptr get_logger(logger log_type, - const char* log_str); - - void start_flush_timer(spdlog::sink_ptr sink); - - public: - ~log_v2() noexcept; - - void stop_flush_timer(); - void apply(const config::state& conf); - - static void load(const std::shared_ptr& io_context); - - static std::shared_ptr instance(); - void set_flush_interval(unsigned second_flush_interval); - - static inline std::shared_ptr bam() { - return _instance->get_logger(log_bam, "bam"); - } - - static inline std::shared_ptr bbdo() { - return _instance->get_logger(log_bbdo, "bbdo"); - } - - static inline std::shared_ptr config() { - return _instance->get_logger(log_config, "config"); - } - - static inline std::shared_ptr core() { - return _instance->get_logger(log_core, "core"); - } - - static inline std::shared_ptr influxdb() { - return _instance->get_logger(log_influxdb, "influxdb"); - } - - static inline std::shared_ptr graphite() { - return _instance->get_logger(log_graphite, "graphite"); - } - - static inline std::shared_ptr notification() { - return _instance->get_logger(log_notification, "notification"); - } - - static inline std::shared_ptr rrd() { - return _instance->get_logger(log_rrd, "rrd"); - } - - static inline std::shared_ptr stats() { - return _instance->get_logger(log_stats, "stats"); - } - - static inline std::shared_ptr lua() { - return _instance->get_logger(log_lua, "lua"); - } - - static inline std::shared_ptr neb() { - return _instance->get_logger(log_neb, "neb"); - } - - static inline std::shared_ptr perfdata() { - return _instance->get_logger(log_perfdata, "perfdata"); - } - - static inline std::shared_ptr processing() { - return _instance->get_logger(log_processing, "processing"); - } - - static inline std::shared_ptr sql() { - return _instance->get_logger(log_sql, "sql"); - } - - static inline std::shared_ptr tcp() { - return _instance->get_logger(log_tcp, "tcp"); - } - - static inline std::shared_ptr tls() { - return _instance->get_logger(log_tls, "tls"); - } - - static inline std::shared_ptr grpc() { - return _instance->get_logger(log_grpc, "grpc"); - } - - static inline std::shared_ptr victoria_metrics() { - return _instance->get_logger(log_victoria_metrics, "victoria_metrics"); - } - - static bool contains_logger(const std::string& logger); - static bool contains_level(const std::string& level); - std::vector> levels() const; - void set_level(const std::string& logger, const std::string& level); -}; - -} // namespace com::centreon::broker - -#endif // CENTREON_BROKER_CORE_INC_COM_CENTREON_BROKER_LOG_V2_HH_ diff --git a/broker/core/inc/com/centreon/broker/misc/diagnostic.hh b/broker/core/inc/com/centreon/broker/misc/diagnostic.hh index 7119f8f71ff..8a91b60323d 100644 --- a/broker/core/inc/com/centreon/broker/misc/diagnostic.hh +++ b/broker/core/inc/com/centreon/broker/misc/diagnostic.hh @@ -1,25 +1,24 @@ -/* -** Copyright 2013 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2013, 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_MISC_DIAGNOSTIC_HH #define CCB_MISC_DIAGNOSTIC_HH - namespace com::centreon::broker { namespace misc { @@ -30,17 +29,19 @@ namespace misc { * Generate diagnostic files to resolve Centreon Broker issues. */ class diagnostic { + std::shared_ptr _logger; + public: diagnostic(); - diagnostic(diagnostic const& right); - ~diagnostic() throw(); - diagnostic& operator=(diagnostic const& right); + diagnostic(diagnostic const&) = delete; + ~diagnostic() noexcept = default; + diagnostic& operator=(diagnostic const&) = delete; void generate(std::vector const& cfg_files, std::string const& out_file = ""); static int exec_process(char const** argv, bool wait_for_completion); }; } // namespace misc -} +} // namespace com::centreon::broker #endif // !CCB_MISC_DIAGNOSTIC_HH diff --git a/broker/core/inc/com/centreon/broker/misc/misc.hh b/broker/core/inc/com/centreon/broker/misc/misc.hh index f862f9f6c1f..a8ccb9f64d0 100644 --- a/broker/core/inc/com/centreon/broker/misc/misc.hh +++ b/broker/core/inc/com/centreon/broker/misc/misc.hh @@ -30,8 +30,11 @@ std::string exec(std::string const& cmd); int32_t exec_process(char const** argv, bool wait_for_completion); std::vector from_hex(std::string const& str); std::string dump_filters(const multiplexing::muxer_filter& filters); -std::list parse_perfdata(uint32_t host_id, uint32_t service_id, - const char* str); +std::list parse_perfdata( + uint32_t host_id, + uint32_t service_id, + const char* str, + const std::shared_ptr& logger); #if DEBUG_ROBOT void debug(const std::string& content); #endif diff --git a/broker/core/inc/com/centreon/broker/modules/handle.hh b/broker/core/inc/com/centreon/broker/modules/handle.hh index 04cf2998f2d..5daf5175bfc 100644 --- a/broker/core/inc/com/centreon/broker/modules/handle.hh +++ b/broker/core/inc/com/centreon/broker/modules/handle.hh @@ -1,5 +1,5 @@ /** - * Copyright 2011-2013, 2021-2023 Centreon + * Copyright 2011-2013, 2021-2024 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,6 +32,7 @@ namespace com::centreon::broker::modules { class handle { const std::string _filename; void* _handle; + std::shared_ptr _logger; void _init(const void* arg = nullptr); void _check_version(); diff --git a/broker/core/inc/com/centreon/broker/persistent_cache.hh b/broker/core/inc/com/centreon/broker/persistent_cache.hh index 792d4d9849e..804d206ad20 100644 --- a/broker/core/inc/com/centreon/broker/persistent_cache.hh +++ b/broker/core/inc/com/centreon/broker/persistent_cache.hh @@ -19,6 +19,7 @@ #ifndef CCB_PERSISTENT_CACHE_HH #define CCB_PERSISTENT_CACHE_HH +#include #include "com/centreon/broker/io/stream.hh" namespace com::centreon::broker { @@ -36,19 +37,29 @@ class persistent_cache { std::shared_ptr _read_file; std::shared_ptr _write_file; + protected: + /* Logger */ + std::shared_ptr _logger; + + private: std::string _new_file() const; std::string _old_file() const; void _open(); public: - persistent_cache(const std::string& cache_file); - ~persistent_cache(); + persistent_cache(const std::string& cache_file, + const std::shared_ptr& logger); + /** + * Destructor. + */ + ~persistent_cache() noexcept = default; persistent_cache(const persistent_cache&) = delete; persistent_cache& operator=(const persistent_cache&) = delete; void add(std::shared_ptr const& d); void commit(); void get(std::shared_ptr& d); void transaction(); + std::shared_ptr logger() const; const std::string& get_cache_file() const; }; diff --git a/broker/core/inc/com/centreon/broker/processing/failover.hh b/broker/core/inc/com/centreon/broker/processing/failover.hh index 3b533c5d216..294580ba8f4 100644 --- a/broker/core/inc/com/centreon/broker/processing/failover.hh +++ b/broker/core/inc/com/centreon/broker/processing/failover.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2011-2013,2015-2017 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2011-2013,2015-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_PROCESSING_FAILOVER_HH #define CCB_PROCESSING_FAILOVER_HH @@ -23,6 +23,7 @@ #include "com/centreon/broker/io/endpoint.hh" #include "com/centreon/broker/io/stream.hh" #include "com/centreon/broker/multiplexing/muxer.hh" + #include "com/centreon/broker/processing/acceptor.hh" #include "com/centreon/broker/processing/endpoint.hh" @@ -54,6 +55,8 @@ class failover : public endpoint { _running_state _state; mutable std::mutex _state_m; std::condition_variable _state_cv; + std::shared_ptr _logger; + void _run(); public: @@ -109,6 +112,6 @@ class failover : public endpoint { }; } // namespace processing -} +} // namespace com::centreon::broker #endif // !CCB_PROCESSING_FAILOVER_HH diff --git a/broker/core/inc/com/centreon/broker/processing/feeder.hh b/broker/core/inc/com/centreon/broker/processing/feeder.hh index 2d265be775e..71e6636b11c 100644 --- a/broker/core/inc/com/centreon/broker/processing/feeder.hh +++ b/broker/core/inc/com/centreon/broker/processing/feeder.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2011-2012, 2020-2023 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2011-2012, 2020-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_PROCESSING_FEEDER_HH #define CCB_PROCESSING_FEEDER_HH @@ -54,6 +54,7 @@ class feeder : public stat_visitable, std::shared_ptr _io_context; mutable std::timed_mutex _protect; + std::shared_ptr _logger; protected: feeder(const std::string& name, @@ -73,13 +74,12 @@ class feeder : public stat_visitable, void _start_read_from_stream_timer(); void _read_from_stream_timer_handler(const boost::system::error_code& err); - void _read_from_muxer(); unsigned _write_to_client( const std::vector>& events); void _stop_no_lock(); - void _ack_event_to_muxer(unsigned count) noexcept; + void _ack_events_on_muxer(uint32_t count) noexcept; public: static std::shared_ptr create( @@ -101,6 +101,6 @@ class feeder : public stat_visitable, }; } // namespace processing -} +} // namespace com::centreon::broker #endif // !CCB_PROCESSING_FEEDER_HH diff --git a/broker/core/inc/com/centreon/broker/stats/center.hh b/broker/core/inc/com/centreon/broker/stats/center.hh index eb5e732fe4a..d474fc77040 100644 --- a/broker/core/inc/com/centreon/broker/stats/center.hh +++ b/broker/core/inc/com/centreon/broker/stats/center.hh @@ -1,24 +1,25 @@ /** -* Copyright 2020-2023 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2020-2023 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_STATS_CENTER_HH #define CCB_STATS_CENTER_HH +#include #include "broker.pb.h" namespace com::centreon::broker::stats { @@ -47,44 +48,56 @@ namespace com::centreon::broker::stats { * value value. */ class center { - static center* _instance; - BrokerStats _stats; - mutable std::mutex _stats_m; + static std::shared_ptr

_instance; + BrokerStats _stats ABSL_GUARDED_BY(_stats_m); + mutable absl::Mutex _stats_m; int _json_stats_file_creation; + public: center(); - public: - static center& instance(); + static std::shared_ptr
instance_ptr(); static void load(); static void unload(); - std::string to_string(); - - EngineStats* register_engine(); - ConflictManagerStats* register_conflict_manager(); - void unregister_muxer(const std::string& name); - void update_muxer(std::string name, std::string queue_file, uint32_t size, - uint32_t unack); - void init_queue_file(std::string muxer, std::string queue_file, - uint32_t max_file_size); - - bool muxer_stats(const std::string& name, MuxerStats* response); - MuxerStats* muxer_stats(const std::string& name); - void clear_muxer_queue_file(const std::string& name); - - bool get_sql_connection_stats(uint32_t index, SqlConnectionStats* response); + std::string to_string() ABSL_LOCKS_EXCLUDED(_stats_m); + + EngineStats* register_engine() ABSL_LOCKS_EXCLUDED(_stats_m); + ConflictManagerStats* register_conflict_manager() + ABSL_LOCKS_EXCLUDED(_stats_m); + void unregister_muxer(const std::string& name) ABSL_LOCKS_EXCLUDED(_stats_m); + void update_muxer(std::string name, + std::string queue_file, + uint32_t size, + uint32_t unack) ABSL_LOCKS_EXCLUDED(_stats_m); + void init_queue_file(std::string muxer, + std::string queue_file, + uint32_t max_file_size) ABSL_LOCKS_EXCLUDED(_stats_m); + + bool muxer_stats(const std::string& name, MuxerStats* response) + ABSL_LOCKS_EXCLUDED(_stats_m); + MuxerStats* muxer_stats(const std::string& name) + ABSL_LOCKS_EXCLUDED(_stats_m); + void clear_muxer_queue_file(const std::string& name) + ABSL_LOCKS_EXCLUDED(_stats_m); + + bool get_sql_connection_stats(uint32_t index, SqlConnectionStats* response) + ABSL_LOCKS_EXCLUDED(_stats_m); void get_conflict_manager_stats(ConflictManagerStats* response); - void get_sql_manager_stats(SqlManagerStats* response, int32_t id = -1); + void get_sql_manager_stats(SqlManagerStats* response, int32_t id = -1) + ABSL_LOCKS_EXCLUDED(_stats_m); SqlConnectionStats* connection(size_t idx); - SqlConnectionStats* add_connection(); - void remove_connection(SqlConnectionStats* stats); + SqlConnectionStats* add_connection() ABSL_LOCKS_EXCLUDED(_stats_m); + void remove_connection(SqlConnectionStats* stats) + ABSL_LOCKS_EXCLUDED(_stats_m); int get_json_stats_file_creation(void); - void get_sql_connection_size(GenericSize* response); - void get_processing_stats(ProcessingStats* response); + void get_sql_connection_size(GenericSize* response) + ABSL_LOCKS_EXCLUDED(_stats_m); + void get_processing_stats(ProcessingStats* response) + ABSL_LOCKS_EXCLUDED(_stats_m); const BrokerStats& stats() const; - void lock(); - void unlock(); + void lock() ABSL_EXCLUSIVE_LOCK_FUNCTION(_stats); + void unlock() ABSL_UNLOCK_FUNCTION(_stats); /** * @brief Set the value pointed by ptr to the value value. @@ -94,25 +107,11 @@ class center { * @param value The value of type T to set. */ template - void update(T* ptr, T value) { - std::lock_guard lck(_stats_m); + void update(T* ptr, T value) ABSL_LOCKS_EXCLUDED(_stats_m) { + absl::MutexLock lck(&_stats_m); *ptr = std::move(value); } - /** - * @brief Almost the same function as in the previous case, but with a - * Timestamp object. And we can directly set a time_t value. - * - * @param ptr A pointer to object of type Timestamp. - * @param value The value of type time_t to set. - */ - // void update(google::protobuf::Timestamp* ptr, time_t value) { - // _strand.post([ptr, value] { - // ptr->Clear(); - // ptr->set_seconds(value); - // }); - //} - /** * @brief Sometimes with protobuf, we can not access to a mutable pointer. * For example with int32 values. We have instead a setter member function. @@ -125,19 +124,19 @@ class center { * @param value The value to set. */ template - void update(void (U::*f)(T), U* ptr, T value) { - std::lock_guard lck(_stats_m); + void update(void (U::*f)(T), U* ptr, T value) ABSL_LOCKS_EXCLUDED(_stats_m) { + absl::MutexLock lck(&_stats_m); (ptr->*f)(value); } - void execute(std::function&& f) { - std::lock_guard lck(_stats_m); + void execute(std::function&& f) ABSL_LOCKS_EXCLUDED(_stats_m) { + absl::MutexLock lck(&_stats_m); f(); } template - const T& get(T (U::*f)() const, const U* ptr) { - std::lock_guard lck(_stats_m); + const T& get(T (U::*f)() const, const U* ptr) ABSL_LOCKS_EXCLUDED(_stats_m) { + absl::MutexLock lck(&_stats_m); return (ptr->*f)(); } }; diff --git a/broker/core/multiplexing/CMakeLists.txt b/broker/core/multiplexing/CMakeLists.txt index 5e6dabb6f58..23b824c008d 100644 --- a/broker/core/multiplexing/CMakeLists.txt +++ b/broker/core/multiplexing/CMakeLists.txt @@ -36,7 +36,13 @@ target_link_libraries(multiplexing spdlog::spdlog) if(WITH_TESTING) set(TESTS_SOURCES - ${TESTS_SOURCES} ${TESTS_DIR}/engine/start_stop.cc - ${TESTS_DIR}/muxer/muxer_filter.cc ${TESTS_DIR}/muxer/read.cc - ${TESTS_DIR}/publisher/read.cc ${TESTS_DIR}/publisher/write.cc) + ${TESTS_SOURCES} + ${TESTS_DIR}/engine/start_stop.cc + ${TESTS_DIR}/muxer/read.cc + ${TESTS_DIR}/publisher/read.cc + ${TESTS_DIR}/publisher/write.cc + PARENT_SCOPE) + message(STATUS "&&&&&&&&&&&&&&&") + message(STATUS "${TESTS_SOURCES}") + message(STATUS "&&&&&&&&&&&&&&&") endif(WITH_TESTING) diff --git a/broker/core/multiplexing/inc/com/centreon/broker/multiplexing/engine.hh b/broker/core/multiplexing/inc/com/centreon/broker/multiplexing/engine.hh index 0b3e0f6c9eb..102efe6ffe5 100644 --- a/broker/core/multiplexing/inc/com/centreon/broker/multiplexing/engine.hh +++ b/broker/core/multiplexing/inc/com/centreon/broker/multiplexing/engine.hh @@ -1,5 +1,5 @@ /** - * Copyright 2009-2012,2015,2019-2023 Centreon + * Copyright 2009-2012,2015,2019-2024 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ #ifndef CCB_MULTIPLEXING_ENGINE_HH #define CCB_MULTIPLEXING_ENGINE_HH +#include #include "com/centreon/broker/persistent_cache.hh" #include "com/centreon/broker/stats/center.hh" @@ -61,54 +62,56 @@ class callback_caller; * @see muxer */ class engine { - static std::mutex _load_m; + static absl::Mutex _load_m; static std::shared_ptr _instance; enum state { not_started, running, stopped }; using send_to_mux_callback_type = std::function; - state _state; - std::unique_ptr _cache_file; - // Mutex to lock _kiew and _state - std::mutex _engine_m; - - // Data queue. - std::deque> _kiew; + // Data queue _kiew and engine state _state are protected by _kiew_m. + absl::Mutex _kiew_m; + state _state ABSL_GUARDED_BY(_kiew_m); + std::deque> _kiew ABSL_GUARDED_BY(_kiew_m); + uint32_t _unprocessed_events ABSL_GUARDED_BY(_kiew_m); // Subscriber. - std::vector> _muxers; + std::vector> _muxers ABSL_GUARDED_BY(_kiew_m); // Statistics. + std::shared_ptr _center; EngineStats* _stats; - uint32_t _unprocessed_events; std::atomic_bool _sending_to_subscribers; - engine(); + std::shared_ptr _logger; + + engine(const std::shared_ptr& logger); std::string _cache_file_path() const; bool _send_to_subscribers(send_to_mux_callback_type&& callback); friend class detail::callback_caller; public: - static void load(); - static void unload(); + static void load() ABSL_LOCKS_EXCLUDED(_load_m); + static void unload() ABSL_LOCKS_EXCLUDED(_load_m); static std::shared_ptr instance_ptr(); engine(const engine&) = delete; engine& operator=(const engine&) = delete; ~engine() noexcept; - void clear(); - void publish(const std::shared_ptr& d); - void publish(const std::deque>& to_publish); - void start(); - void stop(); - void subscribe(const std::shared_ptr& subscriber); - void unsubscribe_muxer(const muxer* subscriber); + void clear() ABSL_LOCKS_EXCLUDED(_kiew_m); + void publish(const std::shared_ptr& d) ABSL_LOCKS_EXCLUDED(_kiew_m); + void publish(const std::deque>& to_publish) + ABSL_LOCKS_EXCLUDED(_kiew_m); + void start() ABSL_LOCKS_EXCLUDED(_kiew_m); + void stop() ABSL_LOCKS_EXCLUDED(_kiew_m); + void subscribe(const std::shared_ptr& subscriber) + ABSL_LOCKS_EXCLUDED(_kiew_m); + void unsubscribe_muxer(const muxer* subscriber) ABSL_LOCKS_EXCLUDED(_kiew_m); }; } // namespace com::centreon::broker::multiplexing diff --git a/broker/core/multiplexing/inc/com/centreon/broker/multiplexing/muxer.hh b/broker/core/multiplexing/inc/com/centreon/broker/multiplexing/muxer.hh index 55480354b7b..bc7b6d959a2 100644 --- a/broker/core/multiplexing/inc/com/centreon/broker/multiplexing/muxer.hh +++ b/broker/core/multiplexing/inc/com/centreon/broker/multiplexing/muxer.hh @@ -1,5 +1,5 @@ /** - * Copyright 2009-2017-2023 Centreon + * Copyright 2009-2017,2023 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,9 @@ #ifndef CCB_MULTIPLEXING_MUXER_HH #define CCB_MULTIPLEXING_MUXER_HH +#include #include +#include #include "com/centreon/broker/multiplexing/engine.hh" #include "com/centreon/broker/multiplexing/muxer_filter.hh" @@ -48,10 +50,7 @@ namespace com::centreon::broker::multiplexing { * * @see engine */ -class muxer : public io::stream { - public: - using read_handler = std::function; - +class muxer : public io::stream, public std::enable_shared_from_this { private: static uint32_t _event_queue_max_size; @@ -63,28 +62,45 @@ class muxer : public io::stream { std::string _read_filters_str; std::string _write_filters_str; const bool _persistent; - read_handler _read_handler; - - std::unique_ptr _file; - std::condition_variable _cv; - mutable std::mutex _mutex; - std::list> _events; - size_t _events_size; - std::list>::iterator _pos; + + std::function>&)> _data_handler; + std::atomic_bool _reader_running = false; + + /** Events are stacked into _events or into _file. Because several threads + * access to them, they are protected by a mutex _events_m. */ + mutable absl::Mutex _events_m; + std::list> _events ABSL_GUARDED_BY(_events_m); + size_t _events_size ABSL_GUARDED_BY(_events_m); + std::list>::iterator _pos + ABSL_GUARDED_BY(_events_m); + std::unique_ptr _file ABSL_GUARDED_BY(_events_m); + absl::CondVar _no_event_cv; + + std::shared_ptr _center; std::time_t _last_stats; - static std::mutex _running_muxers_m; - static absl::flat_hash_map> _running_muxers; + /* The map of running muxers with the mutex to protect it. */ + static absl::Mutex _running_muxers_m; + static absl::flat_hash_map> _running_muxers + ABSL_GUARDED_BY(_running_muxers_m); + + /* The logger of the muxer. */ + std::shared_ptr _logger; - void _clean(); - void _get_event_from_file(std::shared_ptr& event); - void _push_to_queue(std::shared_ptr const& event); + void _clean() ABSL_EXCLUSIVE_LOCKS_REQUIRED(_events_m); + void _get_event_from_file(std::shared_ptr& event) + ABSL_EXCLUSIVE_LOCKS_REQUIRED(_events_m); + void _push_to_queue(std::shared_ptr const& event) + ABSL_EXCLUSIVE_LOCKS_REQUIRED(_events_m); - void _update_stats(void) noexcept; + void _update_stats(void) noexcept ABSL_EXCLUSIVE_LOCKS_REQUIRED(_events_m); - muxer(std::string name, const std::shared_ptr& parent, - const muxer_filter& r_filter, const muxer_filter& w_filter, + muxer(std::string name, + const std::shared_ptr& parent, + const muxer_filter& r_filter, + const muxer_filter& w_filter, bool persistent = false); + void _execute_reader_if_needed(); public: static std::string queue_file(const std::string& name); @@ -104,14 +120,16 @@ class muxer : public io::stream { void publish(const std::deque>& event); bool read(std::shared_ptr& event, time_t deadline) override; template - bool read(container& to_fill, size_t max_to_read, - read_handler&& handler) noexcept; + bool read(container& to_fill, size_t max_to_read) noexcept + ABSL_LOCKS_EXCLUDED(_events_m); const std::string& read_filters_as_str() const; const std::string& write_filters_as_str() const; - uint32_t get_event_queue_size() const; - void nack_events(); + uint32_t get_event_queue_size() const ABSL_LOCKS_EXCLUDED(_events_m); + void nack_events() ABSL_LOCKS_EXCLUDED(_events_m) + ABSL_LOCKS_EXCLUDED(_events_m); void remove_queue_files(); - void statistics(nlohmann::json& tree) const override; + void statistics(nlohmann::json& tree) const override + ABSL_LOCKS_EXCLUDED(_events_m); void wake(); int32_t write(std::shared_ptr const& d) override; void write(std::deque>& to_publish); @@ -121,6 +139,10 @@ class muxer : public io::stream { void set_write_filter(const muxer_filter& w_filter); void clear_read_handler(); void unsubscribe(); + void set_action_on_new_data( + std::function>)>&& + data_handler) ABSL_LOCKS_EXCLUDED(_events_m); + void clear_action_on_new_data() ABSL_LOCKS_EXCLUDED(_events_m); }; /** @@ -132,14 +154,14 @@ class muxer : public io::stream { * @tparam container list> or * vector> * @param to_fill container to fill - * @param max_to_read max events to read from muxer and to push_back in to_fill - * @param handler handler that will be called if we can't read max_to_read - * events as soon as data will be available + * @param max_to_read max events to read from muxer and to push_back in to_fill. + * + * @return A boolean if there are still events to read. */ template -bool muxer::read(container& to_fill, size_t max_to_read, - read_handler&& handler) noexcept { - std::unique_lock lock(_mutex); +bool muxer::read(container& to_fill, size_t max_to_read) noexcept { + _logger->debug("muxer::read ({}) call", _name); + absl::MutexLock lck(&_events_m); size_t nb_read = 0; while (_pos != _events.end() && nb_read < max_to_read) { @@ -149,11 +171,14 @@ bool muxer::read(container& to_fill, size_t max_to_read, } // no more data => store handler to call when data will be available if (_pos == _events.end()) { - _read_handler = std::move(handler); _update_stats(); + _logger->debug("muxer::read ({}) no more data to handle", _name); return false; } else { _update_stats(); + _logger->debug( + "muxer::read ({}) still some data but max count of data reached", + _name); return true; } } diff --git a/broker/core/multiplexing/inc/com/centreon/broker/multiplexing/muxer_filter.hh b/broker/core/multiplexing/inc/com/centreon/broker/multiplexing/muxer_filter.hh index 38aa5301b36..def59166bbc 100644 --- a/broker/core/multiplexing/inc/com/centreon/broker/multiplexing/muxer_filter.hh +++ b/broker/core/multiplexing/inc/com/centreon/broker/multiplexing/muxer_filter.hh @@ -1,5 +1,5 @@ /** - * Copyright 2023 Centreon + * Copyright 2023-2024 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,7 +59,7 @@ class muxer_filter { struct zero_init {}; /** - * @brief constructor witch only initialize all to zero + * @brief constructor which only initializes all to zero * */ constexpr muxer_filter(const zero_init&) : _mask{0} { @@ -137,14 +137,13 @@ class muxer_filter { constexpr muxer_filter& operator|=(const muxer_filter& other) { const uint64_t* to_or = other._mask; for (uint64_t* to_fill = _mask; to_fill < _mask + max_filter_category; - ++to_fill, ++to_or) { + ++to_fill, ++to_or) *to_fill |= *to_or; - } return *this; } /** - * @brief do a and with the filter passed as an argument + * @brief do an *and* with the filter passed as an argument * * @param other * @return const muxer_filter& @@ -158,6 +157,62 @@ class muxer_filter { return *this; } + /** + * @brief Remove events that appears in other filter. + * + * @param other A filter. + * + * @return a reference on the current filter. + */ + constexpr muxer_filter& operator-=(const muxer_filter& other) { + const uint64_t* to_remove = other._mask; + for (uint64_t* to_fill = _mask; to_fill < _mask + max_filter_category; + ++to_fill, ++to_remove) + *to_fill &= ~(*to_remove); + return *this; + } + + /** + * @brief reverse the filter, allowed events becomes forbidden and vice versa. + * + * @return A reference to the filter. + */ + constexpr muxer_filter& reverse() { + for (uint64_t* m = _mask; m < _mask + max_filter_category; ++m) + *m = ~*m; + return *this; + } + + /** + * @brief Remove all the events of a given category. + * + * @param category A category given by its integer value. + * + * @return A reference to the muxer_filter we work on. + */ + constexpr muxer_filter& remove_category(uint16_t category) { + if (category < io::max_data_category) + _mask[category] = 0; + else if (category == io::internal) + _mask[0] = 0; + return *this; + } + + /** + * @brief Add all the events of a given category. + * + * @param category A category given by its integer value. + * + * @return A reference to the muxer_filter we work on. + */ + constexpr muxer_filter& add_category(uint16_t category) { + if (category < io::max_data_category) + _mask[category] = detail::all_events; + else if (category == io::internal) + _mask[0] = detail::all_events; + return *this; + } + /** * @brief Equals operator. * @@ -168,7 +223,8 @@ class muxer_filter { const uint64_t* other_mask = other._mask; for (uint64_t* to_compare = _mask; to_compare < _mask + max_filter_category; ++to_compare, ++other_mask) { - if (*to_compare != *other_mask) return false; + if (*to_compare != *other_mask) + return false; } return true; } @@ -191,8 +247,18 @@ class muxer_filter { return true; } + constexpr bool contains_some_of(const muxer_filter& other) const { + const uint64_t* o = other._mask; + for (const uint64_t* cat = _mask; cat < _mask + max_filter_category; + ++cat, ++o) { + if (*cat & *o) + return true; + } + return false; + } + /** - * @brief return true if filter allows all events + * @brief return true if filter allows all events. * * @return true * @return false @@ -200,15 +266,14 @@ class muxer_filter { constexpr bool allows_all() const { for (const uint64_t* cat = _mask; cat < _mask + max_filter_category; ++cat) { - if (*cat != detail::all_events) { + if (*cat != detail::all_events) return false; - } } return true; } /** - * @brief list all categories for witch at least one event is allowed + * @brief list all categories for which at least one event is allowed. * * @return std::string */ diff --git a/broker/core/multiplexing/src/engine.cc b/broker/core/multiplexing/src/engine.cc index 9a0cd2309ef..dcad82f1336 100644 --- a/broker/core/multiplexing/src/engine.cc +++ b/broker/core/multiplexing/src/engine.cc @@ -1,5 +1,5 @@ /** - * Copyright 2009-2013,2015, 2020-2021 Centreon + * Copyright 2009-2013,2015, 2020-2024 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,23 +18,25 @@ #include "com/centreon/broker/multiplexing/engine.hh" +#include #include #include #include "com/centreon/broker/config/applier/state.hh" #include "com/centreon/broker/io/events.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/misc.hh" #include "com/centreon/broker/multiplexing/muxer.hh" #include "com/centreon/common/pool.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::multiplexing; +using log_v2 = com::centreon::common::log_v2::log_v2; // Class instance. std::shared_ptr engine::_instance{nullptr}; -std::mutex engine::_load_m; +absl::Mutex engine::_load_m; /** * Get engine instance. @@ -50,28 +52,46 @@ std::shared_ptr engine::instance_ptr() { * queue files. */ void engine::load() { - SPDLOG_LOGGER_TRACE(log_v2::core(), "multiplexing: loading engine"); - std::lock_guard lk(_load_m); + auto logger = log_v2::instance().get(log_v2::CORE); + SPDLOG_LOGGER_TRACE(logger, "multiplexing: loading engine"); + absl::MutexLock lk(&_load_m); if (!_instance) - _instance.reset(new engine); + _instance.reset(new engine(logger)); } /** - * Unload class instance. + * @brief Unload the engine class instance. */ void engine::unload() { - if (!_instance) - return; - if (_instance->_state != stopped) - _instance->stop(); + SPDLOG_LOGGER_TRACE(log_v2::instance().get(log_v2::CORE), + "multiplexing: unloading engine"); + auto instance = instance_ptr(); + if (instance) { + { + absl::ReleasableMutexLock lck(&instance->_kiew_m); + /* Here we wait for all the subscriber muxers to be stopped and removed + * from the muxers array. Even if they execute asynchronous functions, + * they have finished after that. */ + auto muxers_empty = [&m = instance->_muxers, + logger = instance->_logger]() { + logger->debug("Still {} muxers configured in Broker engine", m.size()); + return m.empty(); + }; + instance->_logger->info("Waiting for the destruction of subscribers"); + instance->_kiew_m.Await(absl::Condition(&muxers_empty)); + } - SPDLOG_LOGGER_TRACE(log_v2::core(), "multiplexing: unloading engine"); - std::lock_guard lk(_load_m); - // Commit the cache file, if needed. - if (_instance && _instance->_cache_file) - _instance->_cache_file->commit(); + absl::MutexLock lck(&_load_m); + instance->stop(); - _instance.reset(); + // Commit the cache file, if needed. + if (instance->_cache_file) { + // In case of muxers removed from the Engine and still events in _kiew + instance->publish(instance->_kiew); + instance->_cache_file->commit(); + } + _instance.reset(); + } } /** @@ -80,25 +100,21 @@ void engine::unload() { * @param[in] e Event to publish. */ void engine::publish(const std::shared_ptr& e) { - // Lock mutex. bool have_to_send = false; { - std::lock_guard lock(_engine_m); + absl::MutexLock lck(&_kiew_m); switch (_state) { case stopped: - SPDLOG_LOGGER_TRACE(log_v2::core(), - "engine::publish one event to file"); + SPDLOG_LOGGER_TRACE(_logger, "engine::publish one event to file"); _cache_file->add(e); _unprocessed_events++; break; case not_started: - SPDLOG_LOGGER_TRACE(log_v2::core(), - "engine::publish one event to queue"); + SPDLOG_LOGGER_TRACE(_logger, "engine::publish one event to queue"); _kiew.push_back(e); break; default: - SPDLOG_LOGGER_TRACE(log_v2::core(), - "engine::publish one event to queue_"); + SPDLOG_LOGGER_TRACE(_logger, "engine::publish one event to queue_"); _kiew.push_back(e); have_to_send = true; break; @@ -112,10 +128,10 @@ void engine::publish(const std::shared_ptr& e) { void engine::publish(const std::deque>& to_publish) { bool have_to_send = false; { - std::lock_guard lock(_engine_m); + absl::MutexLock lck(&_kiew_m); switch (_state) { case stopped: - SPDLOG_LOGGER_TRACE(log_v2::core(), "engine::publish {} event to file", + SPDLOG_LOGGER_TRACE(_logger, "engine::publish {} event to file", to_publish.size()); for (auto& e : to_publish) { _cache_file->add(e); @@ -123,14 +139,13 @@ void engine::publish(const std::deque>& to_publish) { } break; case not_started: - SPDLOG_LOGGER_TRACE(log_v2::core(), "engine::publish {} event to queue", + SPDLOG_LOGGER_TRACE(_logger, "engine::publish {} event to queue", to_publish.size()); for (auto& e : to_publish) _kiew.push_back(e); break; default: - SPDLOG_LOGGER_TRACE(log_v2::core(), - "engine::publish {} event to queue_", + SPDLOG_LOGGER_TRACE(_logger, "engine::publish {} event to queue_", to_publish.size()); for (auto& e : to_publish) _kiew.push_back(e); @@ -150,19 +165,18 @@ void engine::publish(const std::deque>& to_publish) { void engine::start() { bool have_to_send = false; { - std::lock_guard lock(_engine_m); + absl::MutexLock lck(&_kiew_m); if (_state == not_started) { // Set writing method. - SPDLOG_LOGGER_DEBUG(log_v2::core(), "multiplexing: engine starting"); + SPDLOG_LOGGER_DEBUG(_logger, "multiplexing: engine starting"); _state = running; - stats::center::instance().update(&EngineStats::set_mode, _stats, - EngineStats::RUNNING); + _center->update(&EngineStats::set_mode, _stats, EngineStats::RUNNING); // Local queue. std::deque> kiew; // Get events from the cache file to the local queue. try { - persistent_cache cache(_cache_file_path()); + persistent_cache cache(_cache_file_path(), _logger); std::shared_ptr d; for (;;) { cache.get(d); @@ -171,7 +185,7 @@ void engine::start() { kiew.push_back(d); } } catch (const std::exception& e) { - SPDLOG_LOGGER_ERROR(log_v2::core(), + SPDLOG_LOGGER_ERROR(_logger, "multiplexing: engine couldn't read cache file: {}", e.what()); } @@ -187,10 +201,10 @@ void engine::start() { have_to_send = true; } } - if (have_to_send) { + if (have_to_send) _send_to_subscribers(nullptr); - } - SPDLOG_LOGGER_INFO(log_v2::core(), "multiplexing: engine started"); + + SPDLOG_LOGGER_INFO(_logger, "multiplexing: engine started"); } /** @@ -199,51 +213,38 @@ void engine::start() { * will be handled at the next cbd start. */ void engine::stop() { - std::unique_lock lock(_engine_m); + absl::ReleasableMutexLock lck(&_kiew_m); + if (_state != stopped) { + // Set writing method. + _state = stopped; + _center->update(&EngineStats::set_mode, _stats, EngineStats::STOPPED); + lck.Release(); // Notify hooks of multiplexing loop end. - SPDLOG_LOGGER_INFO(log_v2::core(), "multiplexing: stopping engine"); - - do { - // Make sure that no more data is available. - if (!_sending_to_subscribers) { - SPDLOG_LOGGER_INFO( - log_v2::core(), - "multiplexing: sending events to muxers for the last time {} " - "events to send", - _kiew.size()); - _sending_to_subscribers = true; - lock.unlock(); - std::promise promise; - if (_send_to_subscribers([&promise]() { promise.set_value(); })) { - promise.get_future().get(); - } else { // nothing to send or no muxer - break; - } - lock.lock(); - } - } while (!_kiew.empty()); + SPDLOG_LOGGER_INFO(_logger, "multiplexing: stopping engine"); + + std::promise promise; + if (_send_to_subscribers([&promise]() { promise.set_value(); })) { + promise.get_future().get(); + } // nothing to send or no muxer + + absl::MutexLock l(&_kiew_m); // Open the cache file and start the transaction. // The cache file is used to cache all the events produced // while the engine is stopped. It will be replayed next time // the engine is started. try { - _cache_file = std::make_unique(_cache_file_path()); + _cache_file = + std::make_unique(_cache_file_path(), _logger); _cache_file->transaction(); } catch (const std::exception& e) { - log_v2::perfdata()->error("multiplexing: could not open cache file: {}", - e.what()); + _logger->error("multiplexing: could not open cache file: {}", e.what()); _cache_file.reset(); } - // Set writing method. - _state = stopped; - stats::center::instance().update(&EngineStats::set_mode, _stats, - EngineStats::STOPPED); + SPDLOG_LOGGER_DEBUG(_logger, "multiplexing: engine stopped"); } - SPDLOG_LOGGER_DEBUG(log_v2::core(), "multiplexing: engine stopped"); - DEBUG(fmt::format("STOP engine {:p}", static_cast(this))); } /** @@ -252,13 +253,11 @@ void engine::stop() { * @param[in] subscriber A muxer. */ void engine::subscribe(const std::shared_ptr& subscriber) { - log_v2::config()->debug("engine: muxer {} subscribes to engine", - subscriber->name()); - std::lock_guard l(_engine_m); + _logger->debug("engine: muxer {} subscribes to engine", subscriber->name()); + absl::MutexLock lck(&_kiew_m); for (auto& m : _muxers) if (m.lock() == subscriber) { - log_v2::config()->debug("engine: muxer {} already subscribed", - subscriber->name()); + _logger->debug("engine: muxer {} already subscribed", subscriber->name()); return; } _muxers.push_back(subscriber); @@ -270,12 +269,21 @@ void engine::subscribe(const std::shared_ptr& subscriber) { * @param[in] subscriber Subscriber. */ void engine::unsubscribe_muxer(const muxer* subscriber) { - std::lock_guard l(_engine_m); + std::promise promise; + + if (_send_to_subscribers([&promise]() { promise.set_value(); })) { + promise.get_future().wait(); + } + + absl::MutexLock lck(&_kiew_m); + + auto logger = log_v2::instance().get(log_v2::CONFIG); for (auto it = _muxers.begin(); it != _muxers.end(); ++it) { auto w = it->lock(); if (!w || w.get() == subscriber) { - log_v2::config()->debug("engine: muxer {} unsubscribes to engine", - subscriber->name()); + logger->debug("multiplexing: muxer {} unsubscribed from Engine", + subscriber->name()); + _muxers.erase(it); return; } @@ -285,20 +293,22 @@ void engine::unsubscribe_muxer(const muxer* subscriber) { /** * Default constructor. */ -engine::engine() +engine::engine(const std::shared_ptr& logger) : _state{not_started}, - _stats{stats::center::instance().register_engine()}, _unprocessed_events{0u}, - _sending_to_subscribers{false} { - DEBUG(fmt::format("CONSTRUCTOR engine {:p}", static_cast(this))); - stats::center::instance().update(&EngineStats::set_mode, _stats, - EngineStats::NOT_STARTED); + _center{stats::center::instance_ptr()}, + _stats{_center->register_engine()}, + _sending_to_subscribers{false}, + _logger{logger} { + _center->update(&EngineStats::set_mode, _stats, EngineStats::NOT_STARTED); + absl::SetMutexDeadlockDetectionMode(absl::OnDeadlockCycle::kAbort); + absl::EnableMutexInvariantDebugging(true); } engine::~engine() noexcept { /* Muxers should be unsubscribed before arriving here. */ assert(_muxers.empty()); - SPDLOG_LOGGER_DEBUG(log_v2::core(), "core: cbd engine destroyed."); + SPDLOG_LOGGER_DEBUG(_logger, "core: cbd engine destroyed."); DEBUG(fmt::format("DESTRUCTOR engine {:p}", static_cast(this))); } @@ -316,9 +326,10 @@ std::string engine::_cache_file_path() const { namespace com::centreon::broker::multiplexing::detail { /** - * @brief The goal of this class is to do the completion job once all muxer has - * been fed a shared_ptr of one instance of this class is passed to worker. So - * when all workers have finished, destructor is called and do the job + * @brief The goal of this class is to do the completion job once all muxer + * has been fed a shared_ptr of one instance of this class is passed to + * worker. So when all workers have finished, destructor is called and do the + * job * */ class callback_caller { @@ -337,11 +348,11 @@ class callback_caller { ~callback_caller() { // job is done bool expected = true; - _parent->_sending_to_subscribers.compare_exchange_strong(expected, false); - // if another data to publish redo the job - _parent->_send_to_subscribers(nullptr); - if (_callback) { - _callback(); + if (_parent->_sending_to_subscribers.compare_exchange_strong(expected, + false)) { + if (_callback) { + _callback(); + } } } }; @@ -355,7 +366,7 @@ class callback_caller { * the sending of data to each. callback is called only if _kiew is not empty * @param callback * @return true data sent - * @return false nothing to sent or sent in progress + * @return false nothing to send or currently sending. */ bool engine::_send_to_subscribers(send_to_mux_callback_type&& callback) { // is _send_to_subscriber working? (_sending_to_subscribers=false) @@ -363,14 +374,14 @@ bool engine::_send_to_subscribers(send_to_mux_callback_type&& callback) { if (!_sending_to_subscribers.compare_exchange_strong(expected, true)) { return false; } - // now we continue and _sending_to_subscribers = true + // Now we continue and _sending_to_subscribers is true. // Process all queued events. std::shared_ptr>> kiew; std::shared_ptr first_muxer; std::shared_ptr cb; { - std::lock_guard lck(_engine_m); + absl::MutexLock lck(&_kiew_m); if (_muxers.empty() || _kiew.empty()) { // nothing to do true => _sending_to_subscribers bool expected = true; @@ -379,15 +390,14 @@ bool engine::_send_to_subscribers(send_to_mux_callback_type&& callback) { } SPDLOG_LOGGER_TRACE( - log_v2::core(), - "engine::_send_to_subscribers send {} events to {} muxers", + _logger, "engine::_send_to_subscribers send {} events to {} muxers", _kiew.size(), _muxers.size()); kiew = std::make_shared>>(); std::swap(_kiew, *kiew); // completion object - // it will be destroyed at the end of the scope of this function and at the - // end of lambdas posted + // it will be destroyed at the end of the scope of this function and at + // the end of lambdas posted cb = std::make_shared(std::move(callback), _instance); @@ -403,16 +413,15 @@ bool engine::_send_to_subscribers(send_to_mux_callback_type&& callback) { std::shared_ptr mux_to_publish_in_asio = mux.lock(); if (mux_to_publish_in_asio) { com::centreon::common::pool::io_context().post( - [kiew, mux_to_publish_in_asio, cb]() { + [kiew, mux_to_publish_in_asio, cb, logger = _logger]() { try { mux_to_publish_in_asio->publish(*kiew); } // pool threads protection catch (const std::exception& ex) { - SPDLOG_LOGGER_ERROR(log_v2::core(), - "publish caught exception: {}", + SPDLOG_LOGGER_ERROR(logger, "publish caught exception: {}", ex.what()); } catch (...) { - SPDLOG_LOGGER_ERROR(log_v2::core(), + SPDLOG_LOGGER_ERROR(logger, "publish caught unknown exception"); } }); @@ -421,20 +430,19 @@ bool engine::_send_to_subscribers(send_to_mux_callback_type&& callback) { } } if (first_muxer) { - stats::center::instance().update(&EngineStats::set_processed_events, _stats, - static_cast(kiew->size())); + _center->update(&EngineStats::set_processed_events, _stats, + static_cast(kiew->size())); /* The same work but by this thread for the last muxer. */ first_muxer->publish(*kiew); return true; - } else { // no muxer + } else // no muxer return false; - } } /** - * Clear events stored in the multiplexing engine. + * @brief Clear events stored in the multiplexing engine. */ void engine::clear() { - std::lock_guard lck(_engine_m); + absl::MutexLock lck(&_kiew_m); _kiew.clear(); } diff --git a/broker/core/multiplexing/src/muxer.cc b/broker/core/multiplexing/src/muxer.cc index 4ac2c1e7241..c81a955206e 100644 --- a/broker/core/multiplexing/src/muxer.cc +++ b/broker/core/multiplexing/src/muxer.cc @@ -1,5 +1,5 @@ /** - * Copyright 2009-2013,2015-2017,2019-2021 Centreon + * Copyright 2009-2013,2015-2017,2019-2024 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,8 @@ */ #include "com/centreon/broker/multiplexing/muxer.hh" +#include +#include #include @@ -24,16 +26,18 @@ #include "com/centreon/broker/config/applier/state.hh" #include "com/centreon/broker/exceptions/shutdown.hh" #include "com/centreon/broker/io/events.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/misc.hh" #include "com/centreon/broker/misc/string.hh" #include "com/centreon/broker/multiplexing/engine.hh" +#include "com/centreon/common/pool.hh" #include "com/centreon/common/time.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::multiplexing; +using log_v2 = com::centreon::common::log_v2::log_v2; -static std::mutex _add_bench_point_m; +static absl::Mutex _add_bench_point_m; /** * @brief add a bench point to pb_bench event * as several muxers can update it at the same time, it's protected by a mutex @@ -41,10 +45,11 @@ static std::mutex _add_bench_point_m; * @param event * @param tp_name */ -void add_bench_point(bbdo::pb_bench& event, - const std::string& muxer_name, - const char* funct_name) { - std::lock_guard l(_add_bench_point_m); +static void add_bench_point(bbdo::pb_bench& event, + const std::string& muxer_name, + const char* funct_name) + ABSL_LOCKS_EXCLUDED(_add_bench_point_m) { + absl::MutexLock lck(&_add_bench_point_m); com::centreon::broker::TimePoint* muxer_tp = event.mut_obj().add_points(); muxer_tp->set_name(muxer_name); muxer_tp->set_function(funct_name); @@ -54,7 +59,7 @@ void add_bench_point(bbdo::pb_bench& event, uint32_t muxer::_event_queue_max_size = std::numeric_limits::max(); -std::mutex muxer::_running_muxers_m; +absl::Mutex muxer::_running_muxers_m; absl::flat_hash_map> muxer::_running_muxers; /** @@ -85,11 +90,13 @@ muxer::muxer(std::string name, _write_filters_str{misc::dump_filters(w_filter)}, _persistent(persistent), _events_size{0u}, - _last_stats{std::time(nullptr)} { + _center{stats::center::instance_ptr()}, + _last_stats{std::time(nullptr)}, + _logger{log_v2::instance().get(log_v2::CORE)} { + absl::SetMutexDeadlockDetectionMode(absl::OnDeadlockCycle::kAbort); + absl::EnableMutexInvariantDebugging(true); // Load head queue file back in memory. - DEBUG(fmt::format("CONSTRUCTOR muxer {:p} {}", static_cast(this), - _name)); - std::lock_guard lck(_mutex); + absl::MutexLock lck(&_events_m); if (_persistent) { try { auto mf{std::make_unique(memory_file(_name), nullptr)}; @@ -98,7 +105,7 @@ muxer::muxer(std::string name, e.reset(); mf->read(e, 0); if (e) { - _events.push_back(e); + _events.push_back(std::move(e)); ++_events_size; } } @@ -111,8 +118,7 @@ muxer::muxer(std::string name, _pos = _events.begin(); // Load queue file back in memory. try { - QueueFileStats* stats = - stats::center::instance().muxer_stats(_name)->mutable_queue_file(); + QueueFileStats* stats = _center->muxer_stats(_name)->mutable_queue_file(); _file = std::make_unique(_queue_file_name, stats); std::shared_ptr e; // The following do-while might read an extra event from the queue @@ -123,7 +129,7 @@ muxer::muxer(std::string name, _get_event_from_file(e); if (!e) break; - _events.push_back(e); + _events.push_back(std::move(e)); ++_events_size; } while (_events_size < event_queue_max_size()); } catch (const exceptions::shutdown& e) { @@ -135,7 +141,7 @@ muxer::muxer(std::string name, // Log messages. SPDLOG_LOGGER_INFO( - log_v2::core(), + _logger, "multiplexing: '{}' starts with {} in queue and the queue file is {}", _name, _events_size, _file ? "enable" : "disable"); } @@ -162,25 +168,28 @@ std::shared_ptr muxer::create(std::string name, bool persistent) { std::shared_ptr retval; { - std::lock_guard lck(_running_muxers_m); + absl::MutexLock lck(&_running_muxers_m); absl::erase_if(_running_muxers, [](const std::pair>& p) { return p.second.expired(); }); retval = _running_muxers[name].lock(); if (retval) { - log_v2::config()->debug("muxer: muxer '{}' already exists, reusing it", - name); + log_v2::instance() + .get(log_v2::CONFIG) + ->debug("muxer: muxer '{}' already exists, reusing it", name); retval->set_read_filter(r_filter); retval->set_write_filter(w_filter); - SPDLOG_LOGGER_INFO(log_v2::core(), + SPDLOG_LOGGER_INFO(log_v2::instance().get(log_v2::CORE), "multiplexing: reuse '{}' starts with {} in queue and " "the queue file is {}", name, retval->_events_size, retval->_file ? "enable" : "disable"); } else { - log_v2::config()->debug("muxer: muxer '{}' unknown, creating it", name); + log_v2::instance() + .get(log_v2::CONFIG) + ->debug("muxer: muxer '{}' unknown, creating it", name); retval = std::shared_ptr( new muxer(name, parent, r_filter, w_filter, persistent)); _running_muxers[name] = retval; @@ -195,19 +204,22 @@ std::shared_ptr muxer::create(std::string name, * Destructor. */ muxer::~muxer() noexcept { - unsubscribe(); { - std::lock_guard lock(_mutex); - SPDLOG_LOGGER_INFO(log_v2::core(), - "Destroying muxer {}: number of events in the queue: {}", - _name, _events_size); + absl::MutexLock lock(&_events_m); + SPDLOG_LOGGER_INFO( + _logger, "Destroying muxer {:p} {}: number of events in the queue: {}", + static_cast(this), _name, _events_size); _clean(); } - DEBUG( - fmt::format("DESTRUCTOR muxer {:p} {}", static_cast(this), _name)); + /* We must unsubscribe once _clean() is over. This is because _clean() is + * calling the Broker engine and the engine is unloaded once it has no more + * muxer in its array. As the destructor may be called asynchronously, we + * must be sure the Broker engine is used while it exists. */ + unsubscribe(); + // caution, unregister_muxer must be the last center method called at muxer // destruction to avoid re create a muxer stat entry - stats::center::instance().unregister_muxer(_name); + _center->unregister_muxer(_name); } /** @@ -218,30 +230,27 @@ muxer::~muxer() noexcept { void muxer::ack_events(int count) { // Remove acknowledged events. SPDLOG_LOGGER_TRACE( - log_v2::core(), + _logger, "multiplexing: acknowledging {} events from {} event queue size: {}", count, _name, _events_size); if (count) { SPDLOG_LOGGER_DEBUG( - log_v2::core(), - "multiplexing: acknowledging {} events from {} event queue", count, - _name); - std::lock_guard lock(_mutex); + _logger, "multiplexing: acknowledging {} events from {} event queue", + count, _name); + absl::MutexLock lck(&_events_m); for (int i = 0; i < count && !_events.empty(); ++i) { if (_events.begin() == _pos) { - log_v2::core()->error( - "multiplexing: attempt to acknowledge " - "more events than available in {} event queue: {} size: {}, " - "requested, {} " - "acknowledged", + _logger->error( + "multiplexing: attempt to acknowledge more events than available " + "in {} event queue: {} size: {}, requested, {} acknowledged", _name, _events_size, count, i); break; } _events.pop_front(); --_events_size; } - SPDLOG_LOGGER_TRACE(log_v2::core(), + SPDLOG_LOGGER_TRACE(_logger, "multiplexing: still {} events in {} event queue", _events_size, _name); @@ -256,8 +265,8 @@ void muxer::ack_events(int count) { _update_stats(); } else { SPDLOG_LOGGER_TRACE( - log_v2::core(), - "multiplexing: acknowledging no events from {} event queue", _name); + _logger, "multiplexing: acknowledging no events from {} event queue", + _name); } } @@ -267,12 +276,11 @@ void muxer::ack_events(int count) { * @return The number of acknowledged events. */ int32_t muxer::stop() { - SPDLOG_LOGGER_INFO(log_v2::core(), + SPDLOG_LOGGER_INFO(_logger, "Stopping muxer {}: number of events in the queue: {}", _name, _events_size); - std::lock_guard lck(_mutex); + absl::MutexLock lck(&_events_m); _update_stats(); - DEBUG(fmt::format("STOP muxer {:p} {}", static_cast(this), _name)); return 0; } @@ -297,105 +305,135 @@ uint32_t muxer::event_queue_max_size() noexcept { return _event_queue_max_size; } +/** + * @brief Execute the data_handler() method if it exists and if its execution is + * needed, in other words, if there are no data available it is not necessary to + * execute the data handler. + */ +void muxer::_execute_reader_if_needed() { + _logger->debug("muxer '{}' execute reader if needed data_handler: {}", _name, + static_cast(_data_handler)); + if (_data_handler) { + bool expected = false; + if (_reader_running.compare_exchange_strong(expected, true)) { + com::centreon::common::pool::io_context_ptr()->post( + [me = shared_from_this()] { + std::vector> to_fill; + to_fill.reserve(me->_events_size); + bool still_events_to_read = me->read(to_fill, me->_events_size); + uint32_t written = me->_data_handler(to_fill); + if (written > 0) + me->ack_events(written); + if (written != to_fill.size()) { + me->_logger->error( + "Unable to handle all the incoming events in muxer '{}'", + me->_name); + me->clear_action_on_new_data(); + } + me->_reader_running.store(false); + }); + } + } +} + /** * Add a new event to the internal event list. * * @param[in] event Event to add. */ void muxer::publish(const std::deque>& event_queue) { + _logger->debug("muxer {:p}:publish on muxer '{}': {} events", + static_cast(this), _name, event_queue.size()); auto evt = event_queue.begin(); while (evt != event_queue.end()) { bool at_least_one_push_to_queue = false; - read_handler async_handler; { - // we stop this first loop when mux queue is full on order to release - // mutex to let read do his job before write to file - std::lock_guard lock(_mutex); + // we stop this first loop when mux queue is full in order to release + // mutex to let read to do its job before writing to file + absl::MutexLock lck(&_events_m); + _logger->trace( + "muxer::publish ({}) starting the loop to stack events --- " + "events_size = {} <> {}", + _name, _events_size, event_queue_max_size()); for (; evt != event_queue.end() && _events_size < event_queue_max_size(); ++evt) { auto event = *evt; if (!_write_filter.allows(event->type())) { - SPDLOG_LOGGER_TRACE( - log_v2::core(), - "muxer {} event of type {:x} rejected by write filter", _name, - event->type()); + SPDLOG_LOGGER_TRACE(_logger, + "muxer {} event {} rejected by write filter", + _name, *event); continue; } - if (event->type() == bbdo::pb_bench::static_type()) { add_bench_point(*std::static_pointer_cast(event), _name, "publish"); - SPDLOG_LOGGER_INFO(log_v2::core(), "{} bench publish {}", _name, + SPDLOG_LOGGER_INFO(_logger, "{} bench publish {}", _name, io::data::dump_json{*event}); } SPDLOG_LOGGER_TRACE( - log_v2::core(), - "muxer {} event of type {:x} written queue size: {}", _name, - event->type(), _events_size); + _logger, "muxer {} event of type {:x} written --- queue size: {}", + _name, event->type(), _events_size); at_least_one_push_to_queue = true; _push_to_queue(event); } - if (at_least_one_push_to_queue && - _read_handler) { // async handler waiting? - async_handler = std::move(_read_handler); - _read_handler = nullptr; - } - } - if (async_handler) { - async_handler(); + _logger->trace("muxer::publish ({}) loop finished", _name); + if (at_least_one_push_to_queue || + _events_size >= event_queue_max_size()) // async handler waiting? + _execute_reader_if_needed(); } if (evt == event_queue.end()) { - std::lock_guard lock(_mutex); + absl::MutexLock lck(&_events_m); _update_stats(); return; } + // we have stopped insertion because of full queue => retry if (at_least_one_push_to_queue) { continue; } - // nothing pushed => to file - std::lock_guard lock(_mutex); + /* The queue is full. The rest is put in the retention file. */ + absl::MutexLock lck(&_events_m); for (; evt != event_queue.end(); ++evt) { auto event = *evt; if (!_write_filter.allows(event->type())) { SPDLOG_LOGGER_TRACE( - log_v2::core(), - "muxer {} event of type {:x} rejected by write filter", _name, - event->type()); + _logger, "muxer {} event of type {:x} rejected by write filter", + _name, event->type()); continue; } if (event->type() == bbdo::pb_bench::static_type()) { add_bench_point(*std::static_pointer_cast(event), _name, "retention_publish"); - SPDLOG_LOGGER_INFO(log_v2::core(), - "muxer {} bench publish to file {} {}", _name, - _queue_file_name, io::data::dump_json{*event}); + SPDLOG_LOGGER_INFO(_logger, "muxer {} bench publish to file {} {}", + _name, _queue_file_name, + io::data::dump_json{*event}); } if (!_file) { - QueueFileStats* s = - stats::center::instance().muxer_stats(_name)->mutable_queue_file(); + QueueFileStats* s = _center->muxer_stats(_name)->mutable_queue_file(); _file = std::make_unique(_queue_file_name, s); } try { _file->write(event); SPDLOG_LOGGER_TRACE( - log_v2::core(), + _logger, "{} publish one event of type {:x} to file {} queue size:{}", _name, event->type(), _queue_file_name, _events_size); } catch (const std::exception& ex) { // in case of exception, we lost event. It's mandatory to avoid // infinite loop in case of permanent disk problem - SPDLOG_LOGGER_ERROR(log_v2::core(), "{} fail to write event to {}: {}", - _name, _queue_file_name, ex.what()); + SPDLOG_LOGGER_ERROR(_logger, "{} fail to write event to {}: {}", _name, + _queue_file_name, ex.what()); _file.reset(); } } _update_stats(); } + _logger->debug("muxer {:p}:publish on muxer '{}': finished", + static_cast(this), _name); } /** @@ -407,21 +445,20 @@ void muxer::publish(const std::deque>& event_queue) { * @return Respect io::stream::read()'s return value. */ bool muxer::read(std::shared_ptr& event, time_t deadline) { + _logger->trace("muxer {:p}:read() call", static_cast(this)); bool timed_out{false}; - std::unique_lock lock(_mutex); + absl::MutexLock lck(&_events_m); // No data is directly available. if (_pos == _events.end()) { // Wait a while if subscriber was not shutdown. if ((time_t)-1 == deadline) - _cv.wait(lock); - else if (!deadline) { + _no_event_cv.Wait(&_events_m); + else if (!deadline) timed_out = true; - } else { - time_t now(time(nullptr)); - timed_out = _cv.wait_for(lock, std::chrono::seconds(deadline - now)) == - std::cv_status::timeout; - } + else + _no_event_cv.WaitWithDeadline(&_events_m, absl::FromTimeT(deadline)); + if (_pos != _events.end()) { event = *_pos; ++_pos; @@ -439,17 +476,17 @@ bool muxer::read(std::shared_ptr& event, time_t deadline) { _update_stats(); if (event) { - SPDLOG_LOGGER_TRACE(log_v2::core(), "{} read {} queue size {}", _name, - *event, _events_size); + SPDLOG_LOGGER_TRACE(_logger, "{} read {} queue size {}", _name, *event, + _events_size); if (event->type() == bbdo::pb_bench::static_type()) { add_bench_point(*std::static_pointer_cast(event), _name, "read"); - SPDLOG_LOGGER_INFO(log_v2::core(), "{} bench read {}", _name, + SPDLOG_LOGGER_INFO(_logger, "{} bench read {}", _name, io::data::dump_json{*event}); } } else { - SPDLOG_LOGGER_TRACE(log_v2::core(), "{} queue size {} no event available", - _name, _events_size); + SPDLOG_LOGGER_TRACE(_logger, "{} queue size {} no event available", _name, + _events_size); } return !timed_out; } @@ -478,7 +515,7 @@ const std::string& muxer::write_filters_as_str() const { * @return The size of the event queue. */ uint32_t muxer::get_event_queue_size() const { - std::lock_guard lock(_mutex); + absl::MutexLock lck(&_events_m); return _events_size; } @@ -486,11 +523,11 @@ uint32_t muxer::get_event_queue_size() const { * Reprocess non-acknowledged events. */ void muxer::nack_events() { - SPDLOG_LOGGER_DEBUG(log_v2::core(), + SPDLOG_LOGGER_DEBUG(_logger, "multiplexing: reprocessing unacknowledged events from " "{} event queue with {} waiting events", _name, _events_size); - std::lock_guard lock(_mutex); + absl::MutexLock lck(&_events_m); _pos = _events.begin(); _update_stats(); } @@ -502,7 +539,7 @@ void muxer::nack_events() { */ void muxer::statistics(nlohmann::json& tree) const { // Lock object. - std::lock_guard lock(_mutex); + absl::MutexLock lck(&_events_m); // Queue file mode. bool queue_file_enabled(_file.get()); @@ -524,8 +561,7 @@ void muxer::statistics(nlohmann::json& tree) const { * Wake all threads waiting on this subscriber. */ void muxer::wake() { - std::lock_guard lock(_mutex); - _cv.notify_all(); + _no_event_cv.SignalAll(); } /** @@ -534,6 +570,7 @@ void muxer::wake() { * @param[in] d Event to multiplex. */ int muxer::write(std::shared_ptr const& d) { + _logger->debug("write on muxer '{}'", _name); if (!d) { return 1; } @@ -541,12 +578,12 @@ int muxer::write(std::shared_ptr const& d) { if (d->type() == bbdo::pb_bench::static_type()) { add_bench_point(*std::static_pointer_cast(d), _name, "write"); - SPDLOG_LOGGER_INFO(log_v2::core(), "{} bench write {}", _name, + SPDLOG_LOGGER_INFO(_logger, "{} bench write {}", _name, io::data::dump_json{*d}); } _engine->publish(d); } else { - SPDLOG_LOGGER_TRACE(log_v2::core(), + SPDLOG_LOGGER_TRACE(_logger, "muxer {} event of type {:x} rejected by read filter", _name, d->type()); } @@ -559,6 +596,8 @@ int muxer::write(std::shared_ptr const& d) { * @param to_publish list of event where not allowed event will be erased */ void muxer::write(std::deque>& to_publish) { + _logger->debug("write on muxer '{}' {} events (bulk)", _name, + to_publish.size()); for (auto list_iter = to_publish.begin(); !to_publish.empty() && list_iter != to_publish.end();) { const std::shared_ptr& d = *list_iter; @@ -566,7 +605,7 @@ void muxer::write(std::deque>& to_publish) { if (d->type() == bbdo::pb_bench::static_type()) { add_bench_point(*std::static_pointer_cast(d), _name, "write"); - SPDLOG_LOGGER_INFO(log_v2::core(), "{} bench write {}", _name, + SPDLOG_LOGGER_INFO(_logger, "{} bench write {}", _name, io::data::dump_json{*d}); } ++list_iter; @@ -581,17 +620,14 @@ void muxer::write(std::deque>& to_publish) { /** * Release all events stored within the internal list. - * Warning: _mutex must be locked to call this function. + * Warning: _events_m must be locked to call this function. */ void muxer::_clean() { _file.reset(); - stats::center::instance().clear_muxer_queue_file(_name); - // stats::center::instance().execute([name=this->_name] { - // stats::center::instance().muxer_stats(name)->mutable_queue_file()->Clear(); - // }); + _center->clear_muxer_queue_file(_name); if (_persistent && !_events.empty()) { try { - SPDLOG_LOGGER_TRACE(log_v2::core(), "muxer: sending {} events to {}", + SPDLOG_LOGGER_TRACE(_logger, "muxer: sending {} events to {}", _events_size, memory_file(_name)); auto mf{std::make_unique(memory_file(_name), nullptr)}; while (!_events.empty()) { @@ -600,9 +636,8 @@ void muxer::_clean() { --_events_size; } } catch (std::exception const& e) { - log_v2::core()->error( - "multiplexing: could not backup memory queue of '{}': {}", _name, - e.what()); + _logger->error("multiplexing: could not backup memory queue of '{}': {}", + _name, e.what()); } } _events.clear(); @@ -613,7 +648,7 @@ void muxer::_clean() { /** * Get event from retention file. - * Warning: lock _mutex before using this function. + * Warning: lock _events_m before using this function. * * @param[out] event Last event available. Null if none is available. */ @@ -629,7 +664,7 @@ void muxer::_get_event_from_file(std::shared_ptr& event) { // The file end was reach. (void)e; _file.reset(); - stats::center::instance().clear_muxer_queue_file(_name); + _center->clear_muxer_queue_file(_name); } } } @@ -661,38 +696,37 @@ std::string muxer::queue_file(std::string const& name) { } /** - * Push event to queue (_mutex is locked when this method is called). + * Push event to queue (_events_m is locked when this method is called). * * @param[in] event New event. */ void muxer::_push_to_queue(std::shared_ptr const& event) { bool pos_has_no_more_to_read(_pos == _events.end()); - SPDLOG_LOGGER_TRACE(log_v2::core(), "muxer {} event of type {:x} pushed", - _name, event->type()); + SPDLOG_LOGGER_TRACE(_logger, "muxer {} event of type {:x} pushed", _name, + event->type()); _events.push_back(event); ++_events_size; if (pos_has_no_more_to_read) { _pos = --_events.end(); - _cv.notify_one(); + _no_event_cv.Signal(); } } /** * @brief Fill statistics if it happened more than 1 second ago * - * Warning: _mutex must be locked before while calling this function. + * Warning: _events_m must be locked before while calling this function. */ void muxer::_update_stats() noexcept { std::time_t now{std::time(nullptr)}; if (now - _last_stats > 0) { _last_stats = now; - /* Since _mutex is locked, we can get interesting values and copy them + /* Since _events_m is locked, we can get interesting values and copy them * in the capture. Then the execute() function can put them in the stats * object asynchronously. */ - stats::center::instance().update_muxer( - _name, _file ? _queue_file_name : "", _events_size, - std::distance(_events.begin(), _pos)); + _center->update_muxer(_name, _file ? _queue_file_name : "", _events_size, + std::distance(_events.begin(), _pos)); } } @@ -700,12 +734,10 @@ void muxer::_update_stats() noexcept { * Remove all the queue files attached to this muxer. */ void muxer::remove_queue_files() { - SPDLOG_LOGGER_INFO(log_v2::core(), "multiplexing: '{}' removed", - _queue_file_name); + SPDLOG_LOGGER_INFO(_logger, "multiplexing: '{}' removed", _queue_file_name); /* Here _file is already destroyed */ - QueueFileStats* stats = - stats::center::instance().muxer_stats(_name)->mutable_queue_file(); + QueueFileStats* stats = _center->muxer_stats(_name)->mutable_queue_file(); persistent_file file(_queue_file_name, stats); file.remove_all_files(); } @@ -726,7 +758,7 @@ const std::string& muxer::name() const { * @param r_filter The read filter. */ void muxer::set_read_filter(const muxer_filter& r_filter) { - log_v2::config()->trace("multiplexing: '{}' set read filter...", _name); + _logger->trace("multiplexing: '{}' set read filter...", _name); _read_filter = r_filter; _read_filters_str = misc::dump_filters(r_filter); } @@ -738,23 +770,27 @@ void muxer::set_read_filter(const muxer_filter& r_filter) { * @param r_filter The write filter. */ void muxer::set_write_filter(const muxer_filter& w_filter) { - log_v2::config()->trace("multiplexing: '{}' set write filter...", _name); + _logger->trace("multiplexing: '{}' set write filter...", _name); _write_filter = w_filter; _write_filters_str = misc::dump_filters(w_filter); } -/** - * @brief clear readhandler in case of caller owning this object has terminate - * - */ -void muxer::clear_read_handler() { - std::unique_lock lock(_mutex); - _read_handler = nullptr; -} - /** * @brief Unsubscribe this muxer from the parent engine. */ void muxer::unsubscribe() { + _logger->debug("multiplexing: unsubscribe '{}'", _name); _engine->unsubscribe_muxer(this); } + +void muxer::set_action_on_new_data( + std::function>)>&& + data_handler) { + absl::MutexLock lck(&_events_m); + _data_handler = data_handler; +} + +void muxer::clear_action_on_new_data() { + absl::MutexLock lck(&_events_m); + _data_handler = nullptr; +} diff --git a/broker/core/multiplexing/test/engine/start_stop.cc b/broker/core/multiplexing/test/engine/start_stop.cc index 7d5bc2969c7..cdeca4860f3 100644 --- a/broker/core/multiplexing/test/engine/start_stop.cc +++ b/broker/core/multiplexing/test/engine/start_stop.cc @@ -54,9 +54,10 @@ TEST_F(StartStop, MultiplexingWorks) { try { // Subscriber. - absl::flat_hash_set filters{io::raw::static_type()}; - std::shared_ptr mux(multiplexing::muxer::create("core_multiplexing_engine_start_stop", filters, - filters, false)); + multiplexing::muxer_filter filters{io::raw::static_type()}; + std::shared_ptr mux(multiplexing::muxer::create( + "core_multiplexing_engine_start_stop", + multiplexing::engine::instance_ptr(), filters, filters, false)); // Send events through engine. std::array messages{MSG1, MSG2}; diff --git a/broker/core/multiplexing/test/muxer/read.cc b/broker/core/multiplexing/test/muxer/read.cc index 3c54b2e4756..ef87d83990a 100644 --- a/broker/core/multiplexing/test/muxer/read.cc +++ b/broker/core/multiplexing/test/muxer/read.cc @@ -22,6 +22,7 @@ #include "com/centreon/broker/config/applier/init.hh" #include "com/centreon/broker/io/raw.hh" #include "com/centreon/broker/multiplexing/muxer.hh" +#include "com/centreon/broker/multiplexing/muxer_filter.hh" using namespace com::centreon::broker; @@ -46,8 +47,9 @@ class MultiplexingMuxerRead : public ::testing::Test { } void setup(std::string const& name) { - multiplexing::muxer::filters f{io::raw::static_type()}; - _m = multiplexing::muxer::create(name, f, f, false); + multiplexing::muxer_filter f{io::raw::static_type()}; + _m = multiplexing::muxer::create(name, multiplexing::engine::instance_ptr(), + f, f, false); } void publish_events(int count = 10000) { diff --git a/broker/core/multiplexing/test/publisher/write.cc b/broker/core/multiplexing/test/publisher/write.cc index 26e68f90233..b3bea3898b4 100644 --- a/broker/core/multiplexing/test/publisher/write.cc +++ b/broker/core/multiplexing/test/publisher/write.cc @@ -50,9 +50,10 @@ TEST_F(PublisherWrite, Write) { multiplexing::publisher p; // Subscriber. - absl::flat_hash_set filters{io::raw::static_type()}; + multiplexing::muxer_filter filters{io::raw::static_type()}; std::shared_ptr mux(multiplexing::muxer::create( - "core_multiplexing_publisher_write", filters, filters, true)); + "core_multiplexing_publisher_write", + multiplexing::engine::instance_ptr(), filters, filters, true)); // Publish event. { diff --git a/broker/core/sql/inc/com/centreon/broker/sql/database_config.hh b/broker/core/sql/inc/com/centreon/broker/sql/database_config.hh index f9afd89149f..0636df9d79d 100644 --- a/broker/core/sql/inc/com/centreon/broker/sql/database_config.hh +++ b/broker/core/sql/inc/com/centreon/broker/sql/database_config.hh @@ -1,25 +1,24 @@ -/* -** Copyright 2014-2015 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2014-2015 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_DATABASE_CONFIG_HH #define CCB_DATABASE_CONFIG_HH - namespace com::centreon::broker { // Forward declaration. @@ -110,7 +109,7 @@ class database_config { std::ostream& operator<<(std::ostream& s, const database_config cfg); -} +} // namespace com::centreon::broker namespace fmt { // formatter specializations for fmt diff --git a/broker/core/sql/inc/com/centreon/broker/sql/mysql.hh b/broker/core/sql/inc/com/centreon/broker/sql/mysql.hh index 1cdba2159a4..1f8c370e9b2 100644 --- a/broker/core/sql/inc/com/centreon/broker/sql/mysql.hh +++ b/broker/core/sql/inc/com/centreon/broker/sql/mysql.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2018 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2018-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_MYSQL_HH #define CCB_MYSQL_HH @@ -30,6 +30,20 @@ using my_error = database::mysql_error; * Here is a binding to the C MySQL connector. */ class mysql { + static std::atomic_int _count_ref; + + const database_config _db_cfg; + int _pending_queries; + + std::vector> _connection; + int _current_connection; + std::unordered_map _connection_by_name; + std::string _server_version; + bool _support_bulk_statement; + + /* Logger */ + std::shared_ptr _logger; + public: mysql(database_config const& db_cfg); ~mysql(); @@ -89,19 +103,8 @@ class mysql { static void _initialize_mysql(); void _check_errors(); void _get_server_infos(); - - static std::atomic_int _count_ref; - - const database_config _db_cfg; - int _pending_queries; - - std::vector> _connection; - int _current_connection; - std::unordered_map _connection_by_name; - std::string _server_version; - bool _support_bulk_statement; }; -} +} // namespace com::centreon::broker #endif // CCB_MYSQL_HH diff --git a/broker/core/sql/inc/com/centreon/broker/sql/mysql_bind.hh b/broker/core/sql/inc/com/centreon/broker/sql/mysql_bind.hh index d58485f5e63..a50c5747a83 100644 --- a/broker/core/sql/inc/com/centreon/broker/sql/mysql_bind.hh +++ b/broker/core/sql/inc/com/centreon/broker/sql/mysql_bind.hh @@ -45,16 +45,15 @@ class mysql_bind : public mysql_bind_base { /** * @brief Default constructor */ - mysql_bind() = default; + mysql_bind(const std::shared_ptr& logger) + : mysql_bind_base(logger) {} + /** * @brief Constructor * * @param size Number of columns in this bind - * @param length Size to reserve for each column's buffer. This is useful when - * the column contains strings. By default, this value is 0 and - * no reservation are made. */ - mysql_bind(int size); //, int length = 0); + mysql_bind(int size, const std::shared_ptr& logger); ~mysql_bind() noexcept = default; /** diff --git a/broker/core/sql/inc/com/centreon/broker/sql/mysql_bind_base.hh b/broker/core/sql/inc/com/centreon/broker/sql/mysql_bind_base.hh index 59c516fb5c3..e4f6bdde00a 100644 --- a/broker/core/sql/inc/com/centreon/broker/sql/mysql_bind_base.hh +++ b/broker/core/sql/inc/com/centreon/broker/sql/mysql_bind_base.hh @@ -34,6 +34,7 @@ class mysql_bind_base { protected: std::vector _bind; + std::shared_ptr _logger; bool _prepared(size_t range) const; void _set_typed(uint32_t range); @@ -42,8 +43,9 @@ class mysql_bind_base { /** * @brief Default constructor */ - mysql_bind_base() = default; - mysql_bind_base(int size); + mysql_bind_base(const std::shared_ptr& logger) + : _logger{logger} {} + mysql_bind_base(int size, const std::shared_ptr& logger); /** * @brief Destructor */ diff --git a/broker/core/sql/inc/com/centreon/broker/sql/mysql_bind_result.hh b/broker/core/sql/inc/com/centreon/broker/sql/mysql_bind_result.hh index 3c594f746ce..26798d3e3e6 100644 --- a/broker/core/sql/inc/com/centreon/broker/sql/mysql_bind_result.hh +++ b/broker/core/sql/inc/com/centreon/broker/sql/mysql_bind_result.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2023 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2023-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_MYSQL_BIND_RESULT_HH #define CCB_MYSQL_BIND_RESULT_HH @@ -47,8 +47,11 @@ class mysql_bind_result : public mysql_bind_base { * @param length Size to reserve for each column's buffer. This is useful when * the column contains strings. By default, this value is 0 and * no reservation is made. + * @param logger The logger to use by this object. */ - mysql_bind_result(int size, int length); + mysql_bind_result(int size, + int length, + const std::shared_ptr& logger); ~mysql_bind_result() noexcept = default; /** @@ -287,6 +290,6 @@ class mysql_bind_result : public mysql_bind_base { } // namespace database -} +} // namespace com::centreon::broker #endif // CCB_MYSQL_BIND_RESULT_HH diff --git a/broker/core/sql/inc/com/centreon/broker/sql/mysql_bulk_bind.hh b/broker/core/sql/inc/com/centreon/broker/sql/mysql_bulk_bind.hh index ce0d3f0ac32..ff354ebeb55 100644 --- a/broker/core/sql/inc/com/centreon/broker/sql/mysql_bulk_bind.hh +++ b/broker/core/sql/inc/com/centreon/broker/sql/mysql_bulk_bind.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2018, 2021 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2018, 2021-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_MYSQL_BULK_BIND_HH #define CCB_MYSQL_BULK_BIND_HH @@ -37,9 +37,12 @@ class mysql_bulk_bind : public mysql_bind_base { public: /** - * @brief Default constructor + * @brief Base constructor. It just needs a logger. + * + * @param logger The logger to use within. */ - mysql_bulk_bind() = default; + mysql_bulk_bind(const std::shared_ptr& logger) + : mysql_bind_base(logger) {} /** * @brief Constructor * @@ -47,7 +50,9 @@ class mysql_bulk_bind : public mysql_bind_base { * @param row_count Number of rows to reserve. Columns are not allocated with * a such size, they are just reserved. */ - mysql_bulk_bind(int size, size_t reserved_rows_count); + mysql_bulk_bind(int size, + size_t reserved_rows_count, + const std::shared_ptr& logger); ~mysql_bulk_bind() noexcept = default; /** @@ -310,6 +315,6 @@ class mysql_bulk_bind : public mysql_bind_base { } // namespace database -} +} // namespace com::centreon::broker #endif // CCB_MYSQL_BULK_BIND_HH diff --git a/broker/core/sql/inc/com/centreon/broker/sql/mysql_bulk_stmt.hh b/broker/core/sql/inc/com/centreon/broker/sql/mysql_bulk_stmt.hh index d8c27e0bbae..d26e39c7753 100644 --- a/broker/core/sql/inc/com/centreon/broker/sql/mysql_bulk_stmt.hh +++ b/broker/core/sql/inc/com/centreon/broker/sql/mysql_bulk_stmt.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2018-2023 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2018-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_MYSQL_BULK_STMT_HH #define CCB_MYSQL_BULK_STMT_HH @@ -214,6 +214,6 @@ class mysql_bulk_stmt : public mysql_stmt_base { } // namespace database -} +} // namespace com::centreon::broker #endif // CCB_MYSQL_BULK_STMT_HH diff --git a/broker/core/sql/inc/com/centreon/broker/sql/mysql_column.hh b/broker/core/sql/inc/com/centreon/broker/sql/mysql_column.hh index 96fa3339e98..7d411e8ee0c 100644 --- a/broker/core/sql/inc/com/centreon/broker/sql/mysql_column.hh +++ b/broker/core/sql/inc/com/centreon/broker/sql/mysql_column.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2018 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2018-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_DATABASE_MYSQL_COLUMN_HH #define CCB_DATABASE_MYSQL_COLUMN_HH diff --git a/broker/core/sql/inc/com/centreon/broker/sql/mysql_connection.hh b/broker/core/sql/inc/com/centreon/broker/sql/mysql_connection.hh index 305feb778d8..d83aaa17697 100644 --- a/broker/core/sql/inc/com/centreon/broker/sql/mysql_connection.hh +++ b/broker/core/sql/inc/com/centreon/broker/sql/mysql_connection.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2018 - 2023 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2018 - 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_MYSQL_CONNECTION_HH #define CCB_MYSQL_CONNECTION_HH @@ -109,6 +109,11 @@ class mysql_connection { mutable std::mutex _error_m; database::mysql_error _error; + /* Logger */ + std::shared_ptr _logger; + + std::shared_ptr _center; + /**************************************************************************/ /* Methods executed by this thread */ /**************************************************************************/ @@ -151,7 +156,10 @@ class mysql_connection { /* Methods executed by the main thread */ /**************************************************************************/ - mysql_connection(const database_config& db_cfg, SqlConnectionStats* stats); + mysql_connection(const database_config& db_cfg, + SqlConnectionStats* stats, + const std::shared_ptr& logger, + std::shared_ptr center); ~mysql_connection(); void prepare_query(int id, std::string const& query); @@ -201,6 +209,6 @@ class mysql_connection { void stop(); }; -} +} // namespace com::centreon::broker #endif // CCB_MYSQL_CONNECTION_HH diff --git a/broker/core/sql/inc/com/centreon/broker/sql/mysql_error.hh b/broker/core/sql/inc/com/centreon/broker/sql/mysql_error.hh index c17474ce168..0afb7938210 100644 --- a/broker/core/sql/inc/com/centreon/broker/sql/mysql_error.hh +++ b/broker/core/sql/inc/com/centreon/broker/sql/mysql_error.hh @@ -1,27 +1,26 @@ -/* -** Copyright 2018-2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2018-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_MYSQL_ERROR_HH #define CCB_MYSQL_ERROR_HH #include - namespace com::centreon::broker { namespace database { @@ -227,6 +226,6 @@ class mysql_error { } // namespace database -} +} // namespace com::centreon::broker #endif // CCB_MYSQL_ERROR_HH diff --git a/broker/core/sql/inc/com/centreon/broker/sql/mysql_manager.hh b/broker/core/sql/inc/com/centreon/broker/sql/mysql_manager.hh index 4a17ff813a5..bad19031959 100644 --- a/broker/core/sql/inc/com/centreon/broker/sql/mysql_manager.hh +++ b/broker/core/sql/inc/com/centreon/broker/sql/mysql_manager.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2018-2021 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2018-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_MYSQL_MANAGER_HH #define CCB_MYSQL_MANAGER_HH @@ -67,9 +67,13 @@ class mysql_manager { // last stats update timestamp time_t _stats_connections_timestamp; // stats + std::shared_ptr _center; // Number of tasks per connection std::vector _stats_counts; + /* Logger */ + std::shared_ptr _logger; + mysql_manager(); public: @@ -86,6 +90,6 @@ class mysql_manager { size_t connections_count() const; }; -} +} // namespace com::centreon::broker #endif // CCB_MYSQL_MANAGER_HH diff --git a/broker/core/sql/inc/com/centreon/broker/sql/mysql_multi_insert.hh b/broker/core/sql/inc/com/centreon/broker/sql/mysql_multi_insert.hh index 2af840142ed..3c6dc47c825 100644 --- a/broker/core/sql/inc/com/centreon/broker/sql/mysql_multi_insert.hh +++ b/broker/core/sql/inc/com/centreon/broker/sql/mysql_multi_insert.hh @@ -1,5 +1,5 @@ -/* - * Copyright 2023 Centreon +/** + * Copyright 2023-2024 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -212,6 +212,6 @@ class bulk_or_multi { } // namespace database -} +} // namespace com::centreon::broker #endif // CCB_MYSQL_MULTI_INSERT_HH diff --git a/broker/core/sql/inc/com/centreon/broker/sql/mysql_result.hh b/broker/core/sql/inc/com/centreon/broker/sql/mysql_result.hh index d1223823370..e0bd04c5fe7 100644 --- a/broker/core/sql/inc/com/centreon/broker/sql/mysql_result.hh +++ b/broker/core/sql/inc/com/centreon/broker/sql/mysql_result.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2018-2023 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2018-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_MYSQL_RESULT_HH #define CCB_MYSQL_RESULT_HH @@ -74,6 +74,6 @@ class mysql_result { }; } // namespace database -} +} // namespace com::centreon::broker #endif // CCB_MYSQL_RESULT_HH diff --git a/broker/core/sql/inc/com/centreon/broker/sql/mysql_stmt.hh b/broker/core/sql/inc/com/centreon/broker/sql/mysql_stmt.hh index faa75762602..026dc3ea42d 100644 --- a/broker/core/sql/inc/com/centreon/broker/sql/mysql_stmt.hh +++ b/broker/core/sql/inc/com/centreon/broker/sql/mysql_stmt.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2018-2023 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2018-2023 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_MYSQL_STMT_HH #define CCB_MYSQL_STMT_HH @@ -208,6 +208,6 @@ class mysql_stmt : public mysql_stmt_base { } // namespace database -} +} // namespace com::centreon::broker #endif // CCB_MYSQL_STMT_HH diff --git a/broker/core/sql/inc/com/centreon/broker/sql/mysql_stmt_base.hh b/broker/core/sql/inc/com/centreon/broker/sql/mysql_stmt_base.hh index ddc559ac524..15eec8a1d03 100644 --- a/broker/core/sql/inc/com/centreon/broker/sql/mysql_stmt_base.hh +++ b/broker/core/sql/inc/com/centreon/broker/sql/mysql_stmt_base.hh @@ -1,26 +1,25 @@ -/* -** Copyright 2023 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2023-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_MYSQL_STMT_BASE_HH #define CCB_MYSQL_STMT_BASE_HH #include "com/centreon/broker/io/data.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/sql/mysql_bind.hh" namespace com::centreon::broker { @@ -44,13 +43,15 @@ class mysql_stmt_base { */ std::vector> _pb_mapping; + protected: + /* Logger */ + std::shared_ptr _logger; + + private: size_t _compute_param_count(const std::string& query); public: - /** - * @brief Default constructor. - */ - mysql_stmt_base(bool bulk) : _bulk(bulk) {} + mysql_stmt_base(bool bulk); mysql_stmt_base(const std::string& query, bool named, bool bulk); mysql_stmt_base( const std::string& query, @@ -414,6 +415,6 @@ class mysql_stmt_base { } // namespace database -} +} // namespace com::centreon::broker #endif // CCB_MYSQL_STMT_BASE_HH diff --git a/broker/core/sql/inc/com/centreon/broker/sql/mysql_task.hh b/broker/core/sql/inc/com/centreon/broker/sql/mysql_task.hh index 107e71b7a11..9f26958d458 100644 --- a/broker/core/sql/inc/com/centreon/broker/sql/mysql_task.hh +++ b/broker/core/sql/inc/com/centreon/broker/sql/mysql_task.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2018 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2018-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_MYSQL_TASK_HH #define CCB_MYSQL_TASK_HH @@ -214,6 +214,6 @@ class mysql_task_statement_int : public mysql_task { }; } // namespace database -} +} // namespace com::centreon::broker #endif // CCB_MYSQL_TASK_HH diff --git a/broker/core/sql/inc/com/centreon/broker/sql/query_preparator.hh b/broker/core/sql/inc/com/centreon/broker/sql/query_preparator.hh index 2beaf51abdd..29644885864 100644 --- a/broker/core/sql/inc/com/centreon/broker/sql/query_preparator.hh +++ b/broker/core/sql/inc/com/centreon/broker/sql/query_preparator.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2015, 2021 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2015, 2021-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_QUERY_PREPARATOR_HH #define CCB_QUERY_PREPARATOR_HH @@ -63,6 +63,8 @@ namespace com::centreon::broker { * Where hg is of type neb::host_group. */ class query_preparator { + std::shared_ptr _logger; + public: using excluded_fields = absl::btree_set; using doubled_fields = absl::btree_set; @@ -111,6 +113,6 @@ class query_preparator { const std::string& table); }; -} +} // namespace com::centreon::broker #endif // !CCB_QUERY_PREPARATOR_HH diff --git a/broker/core/sql/inc/com/centreon/broker/sql/stats.hh b/broker/core/sql/inc/com/centreon/broker/sql/stats.hh index d5673c4f249..16109130968 100644 --- a/broker/core/sql/inc/com/centreon/broker/sql/stats.hh +++ b/broker/core/sql/inc/com/centreon/broker/sql/stats.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2023 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2023-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_STATS_HH #define CCB_STATS_HH @@ -221,6 +221,6 @@ class stats { } // namespace sql -} +} // namespace com::centreon::broker #endif /* !CCB_STATS_HH */ diff --git a/broker/core/sql/src/database_config.cc b/broker/core/sql/src/database_config.cc index dabff29240a..855d56e0faa 100644 --- a/broker/core/sql/src/database_config.cc +++ b/broker/core/sql/src/database_config.cc @@ -1,28 +1,29 @@ /** -* Copyright 2014-2015 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2014-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/sql/database_config.hh" #include "com/centreon/broker/config/parser.hh" #include "com/centreon/broker/exceptions/config.hh" -#include "com/centreon/broker/log_v2.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; +using com::centreon::common::log_v2::log_v2; namespace com::centreon::broker { std::ostream& operator<<(std::ostream& s, const database_config cfg) { @@ -32,14 +33,14 @@ std::ostream& operator<<(std::ostream& s, const database_config cfg) { } else { s << cfg.get_socket(); } - s << "queries per transaction:" << cfg.get_queries_per_transaction() + s << " queries per transaction:" << cfg.get_queries_per_transaction() << " check replication:" << cfg.get_check_replication() - << " connnexion count:" << cfg.get_connections_count() - << " max comit delay:" << cfg.get_max_commit_delay() << 's'; + << " connection count:" << cfg.get_connections_count() + << " max commit delay:" << cfg.get_max_commit_delay() << 's'; return s; } -} +} // namespace com::centreon::broker /** * Default constructor. @@ -127,11 +128,13 @@ database_config::database_config(config::endpoint const& cfg) { // db_port it = cfg.params.find("db_port"); + auto logger_config = log_v2::instance().get(log_v2::CONFIG); if (it != end) { uint32_t port; if (!absl::SimpleAtoi(it->second, &port)) { - log_v2::config()->error( - "In the database configuration, 'db_port' should be a number, and " + logger_config->error( + "In the database configuration, 'db_port' should be a number, " + "and " "not '{}'", it->second); _port = 0; @@ -162,8 +165,9 @@ database_config::database_config(config::endpoint const& cfg) { it = cfg.params.find("queries_per_transaction"); if (it != end) { if (!absl::SimpleAtoi(it->second, &_queries_per_transaction)) { - log_v2::core()->error( - "queries_per_transaction is a number but must be given as a string. " + logger_config->error( + "queries_per_transaction is a number but must be given as a " + "string. " "Unable to read the value '{}' - value 2000 taken by default.", it->second); _queries_per_transaction = 2000; @@ -175,7 +179,7 @@ database_config::database_config(config::endpoint const& cfg) { it = cfg.params.find("check_replication"); if (it != end) { if (!absl::SimpleAtob(it->second, &_check_replication)) { - log_v2::core()->error( + logger_config->error( "check_replication is a string containing a boolean. If not " "specified, it will be considered as \"true\"."); _check_replication = true; @@ -187,7 +191,7 @@ database_config::database_config(config::endpoint const& cfg) { it = cfg.params.find("connections_count"); if (it != end) { if (!absl::SimpleAtoi(it->second, &_connections_count)) { - log_v2::core()->error( + logger_config->error( "connections_count is a string " "containing an integer. If not " "specified, it will be considered as " @@ -199,7 +203,7 @@ database_config::database_config(config::endpoint const& cfg) { it = cfg.params.find("max_commit_delay"); if (it != end) { if (!absl::SimpleAtoi(it->second, &_max_commit_delay)) { - log_v2::core()->error( + logger_config->error( "max_commit_delay is a string " "containing an integer. If not " "specified, it will be considered as " @@ -254,53 +258,54 @@ bool database_config::operator==(database_config const& other) const { _connections_count == other._connections_count && _max_commit_delay == other._max_commit_delay}; if (!retval) { + auto logger = log_v2::instance().get(log_v2::SQL); if (_type != other._type) - log_v2::sql()->debug( + logger->debug( "database configurations do not match because of their types: {} " "!= {}", _type, other._type); else if (_host != other._host) - log_v2::sql()->debug( + logger->debug( "database configurations do not match because of their hosts: {} " "!= {}", _host, other._host); else if (_socket != other._socket) - log_v2::sql()->debug( + logger->debug( "database configurations do not match because of their sockets: {} " "!= {}", _socket, other._socket); else if (_port != other._port) - log_v2::sql()->debug( + logger->debug( "database configurations do not match because of their ports: {} " "!= {}", _port, other._port); else if (_user != other._user) - log_v2::sql()->debug( + logger->debug( "database configurations do not match because of their users: {} " "!= {}", _user, other._user); else if (_password != other._password) - log_v2::sql()->debug( + logger->debug( "database configurations do not match because of their passwords: " "{} != {}", _password, other._password); else if (_name != other._name) - log_v2::sql()->debug( + logger->debug( "database configurations do not match because of their names: {} " "!= {}", _name, other._name); else if (_queries_per_transaction != other._queries_per_transaction) - log_v2::sql()->debug( + logger->debug( "database configurations do not match because of their queries per " "transactions: {} != {}", _queries_per_transaction, other._queries_per_transaction); else if (_connections_count != other._connections_count) - log_v2::sql()->debug( + logger->debug( "database configurations do not match because of their connections " "counts: {} != {}", _connections_count, other._connections_count); else if (_max_commit_delay != other._max_commit_delay) - log_v2::sql()->debug( + logger->debug( "database configurations do not match because of their commit " "delay: {} != {}", _max_commit_delay, other._max_commit_delay); diff --git a/broker/core/sql/src/mysql.cc b/broker/core/sql/src/mysql.cc index 9d5c053b63d..7e35d114642 100644 --- a/broker/core/sql/src/mysql.cc +++ b/broker/core/sql/src/mysql.cc @@ -1,30 +1,31 @@ /** -* Copyright 2018 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2018-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/sql/mysql_manager.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::database; +using com::centreon::common::log_v2::log_v2; /** * Constructor. @@ -32,11 +33,14 @@ using namespace com::centreon::broker::database; * @param[in] db_cfg Database configuration. */ mysql::mysql(database_config const& db_cfg) - : _db_cfg(db_cfg), _pending_queries(0), _current_connection(0) { + : _db_cfg(db_cfg), + _pending_queries(0), + _current_connection(0), + _logger{log_v2::instance().get(log_v2::SQL)} { mysql_manager& mgr(mysql_manager::instance()); _connection = mgr.get_connections(db_cfg); - log_v2::sql()->info("mysql connector configured with {} connection(s)", - db_cfg.get_connections_count()); + _logger->info("mysql connector configured with {} connection(s)", + db_cfg.get_connections_count()); _get_server_infos(); } @@ -44,17 +48,17 @@ mysql::mysql(database_config const& db_cfg) * Destructor */ mysql::~mysql() { - log_v2::sql()->trace("mysql: destruction"); + _logger->trace("mysql: destruction"); try { commit(); } catch (const std::exception& e) { - log_v2::sql()->warn( + _logger->warn( "Unable to commit on the database server. Probably not connected: {}", e.what()); } _connection.clear(); mysql_manager::instance().update_connections(); - log_v2::sql()->trace("mysql object destroyed"); + _logger->trace("mysql object destroyed"); } /** @@ -397,16 +401,15 @@ void mysql::_get_server_infos() { std::string_view server = v[3]; if (absl::SimpleAtoi(v[0], &major) && absl::SimpleAtoi(v[1], &minor) && absl::SimpleAtoi(v[2], &patch)) { - log_v2::sql()->info("connected to '{}' Server, version {}.{}.{}", - fmt::string_view(server.data(), server.size()), major, - minor, patch); + _logger->info("connected to '{}' Server, version {}.{}.{}", + fmt::string_view(server.data(), server.size()), major, + minor, patch); if (server == "MariaDB" && (major > 10 || (major == 10 && minor >= 2))) { - log_v2::sql()->info( - "it supports column-wise binding in prepared statements"); + _logger->info("it supports column-wise binding in prepared statements"); _support_bulk_statement = true; } } } else { - log_v2::sql()->info("connected to '{}' Server", _server_version); + _logger->info("connected to '{}' Server", _server_version); } } diff --git a/broker/core/sql/src/mysql_bind.cc b/broker/core/sql/src/mysql_bind.cc index 8a526df780e..58bc22e3e78 100644 --- a/broker/core/sql/src/mysql_bind.cc +++ b/broker/core/sql/src/mysql_bind.cc @@ -27,7 +27,8 @@ using namespace com::centreon::broker; using namespace com::centreon::broker::database; -mysql_bind::mysql_bind(int size) : mysql_bind_base(size), _buffer(size) {} +mysql_bind::mysql_bind(int size, const std::shared_ptr& logger) + : mysql_bind_base(size, logger), _buffer(size) {} void* mysql_bind::get_value_pointer(size_t range) { switch (_bind[range].buffer_type) { @@ -102,7 +103,7 @@ void mysql_bind::set_null_bool(size_t range) { else { \ assert("This field is not an " #sqltype == nullptr); \ SPDLOG_LOGGER_CRITICAL( \ - log_v2::sql(), "{} This field is not an " #sqltype " but {}", \ + _logger, "{} This field is not an " #sqltype " but {}", \ __FUNCTION__, static_cast(_bind[range].buffer_type)); \ return 0; \ } \ diff --git a/broker/core/sql/src/mysql_bind_base.cc b/broker/core/sql/src/mysql_bind_base.cc index faa2ec8d865..d402ab7fd46 100644 --- a/broker/core/sql/src/mysql_bind_base.cc +++ b/broker/core/sql/src/mysql_bind_base.cc @@ -1,20 +1,20 @@ /** -* Copyright 2023 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2023 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/sql/mysql_bind_base.hh" @@ -32,7 +32,9 @@ using namespace com::centreon::broker::database; * * @param size Number of columns in this bind */ -mysql_bind_base::mysql_bind_base(int size) : _typed(size), _bind(size) {} +mysql_bind_base::mysql_bind_base(int size, + const std::shared_ptr& logger) + : _typed(size), _bind(size), _logger{logger} {} /** * @brief Return a boolean telling if the column at index range has been diff --git a/broker/core/sql/src/mysql_bind_result.cc b/broker/core/sql/src/mysql_bind_result.cc index d1473124cce..e741af9f937 100644 --- a/broker/core/sql/src/mysql_bind_result.cc +++ b/broker/core/sql/src/mysql_bind_result.cc @@ -1,20 +1,20 @@ /** -* Copyright 2023 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2023 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/sql/mysql_bind_result.hh" @@ -27,8 +27,11 @@ using namespace com::centreon::broker; using namespace com::centreon::broker::database; -mysql_bind_result::mysql_bind_result(int size, int length) - : mysql_bind_base(size), _length(length), _is_null(size) { +mysql_bind_result::mysql_bind_result( + int size, + int length, + const std::shared_ptr& logger) + : mysql_bind_base(size, logger), _length(length), _is_null(size) { if (length) { int alloc = length + 1; _buffer.resize(size * alloc); @@ -49,8 +52,8 @@ int32_t mysql_bind_result::value_as_i32(size_t range) const { if (absl::SimpleAtoi(static_cast(_bind[range].buffer), &retval)) return retval; else { - log_v2::sql()->debug( - "mysql_bind_result: unable to parse an i32 at range {}", range); + _logger->debug("mysql_bind_result: unable to parse an i32 at range {}", + range); return 0; } } @@ -61,8 +64,8 @@ uint32_t mysql_bind_result::value_as_u32(size_t range) const { if (absl::SimpleAtoi(static_cast(_bind[range].buffer), &retval)) return retval; else { - log_v2::sql()->debug( - "mysql_bind_result: unable to parse an u32 at range {}", range); + _logger->debug("mysql_bind_result: unable to parse an u32 at range {}", + range); return 0; } } @@ -73,8 +76,8 @@ int64_t mysql_bind_result::value_as_i64(size_t range) const { if (absl::SimpleAtoi(static_cast(_bind[range].buffer), &retval)) return retval; else { - log_v2::sql()->debug( - "mysql_bind_result: unable to parse an i64 at range {}", range); + _logger->debug("mysql_bind_result: unable to parse an i64 at range {}", + range); return 0; } } @@ -85,8 +88,8 @@ uint64_t mysql_bind_result::value_as_u64(size_t range) const { if (absl::SimpleAtoi(static_cast(_bind[range].buffer), &retval)) return retval; else { - log_v2::sql()->debug( - "mysql_bind_result: unable to parse an u64 at range {}", range); + _logger->debug("mysql_bind_result: unable to parse an u64 at range {}", + range); return 0; } } @@ -97,8 +100,8 @@ float mysql_bind_result::value_as_f32(size_t range) const { if (absl::SimpleAtof(static_cast(_bind[range].buffer), &retval)) return retval; else { - log_v2::sql()->debug( - "mysql_bind_result: unable to parse an f32 at range {}", range); + _logger->debug("mysql_bind_result: unable to parse an f32 at range {}", + range); return 0; } } @@ -109,8 +112,8 @@ double mysql_bind_result::value_as_f64(size_t range) const { if (absl::SimpleAtod(static_cast(_bind[range].buffer), &retval)) return retval; else { - log_v2::sql()->debug( - "mysql_bind_result: unable to parse an f64 at range {}", range); + _logger->debug("mysql_bind_result: unable to parse an f64 at range {}", + range); return 0; } } @@ -126,8 +129,8 @@ char mysql_bind_result::value_as_tiny(size_t range) const { if (absl::SimpleAtoi(static_cast(_bind[range].buffer), &retval)) return static_cast(retval); else { - log_v2::sql()->debug( - "mysql_bind_result: unable to parse a tiny at range {}", range); + _logger->debug("mysql_bind_result: unable to parse a tiny at range {}", + range); return 0; } } @@ -138,8 +141,8 @@ bool mysql_bind_result::value_as_bool(size_t range) const { if (absl::SimpleAtob(static_cast(_bind[range].buffer), &retval)) return retval; else { - log_v2::sql()->debug( - "mysql_bind_result: unable to parse a bool at range {}", range); + _logger->debug("mysql_bind_result: unable to parse a bool at range {}", + range); return false; } } diff --git a/broker/core/sql/src/mysql_bulk_bind.cc b/broker/core/sql/src/mysql_bulk_bind.cc index b07967b3cdc..16750abcec0 100644 --- a/broker/core/sql/src/mysql_bulk_bind.cc +++ b/broker/core/sql/src/mysql_bulk_bind.cc @@ -27,8 +27,10 @@ using namespace com::centreon::broker; using namespace com::centreon::broker::database; -mysql_bulk_bind::mysql_bulk_bind(int size, size_t reserved_rows_count) - : mysql_bind_base(size), _column(size) { +mysql_bulk_bind::mysql_bulk_bind(int size, + size_t reserved_rows_count, + const std::shared_ptr& logger) + : mysql_bind_base(size, logger), _column(size) { for (auto& c : _column) c.reserve(reserved_rows_count); } @@ -110,7 +112,7 @@ void mysql_bulk_bind::set_value_as_i64(size_t range, else { \ assert("This field is not an " #sqltype == nullptr); \ SPDLOG_LOGGER_CRITICAL( \ - log_v2::sql(), "{} This field is not an " #sqltype " but {}", \ + _logger, "{} This field is not an " #sqltype " but {}", \ __FUNCTION__, static_cast(_bind[range].buffer_type)); \ return 0; \ } \ diff --git a/broker/core/sql/src/mysql_bulk_stmt.cc b/broker/core/sql/src/mysql_bulk_stmt.cc index b87ab21ba12..115bbbd56de 100644 --- a/broker/core/sql/src/mysql_bulk_stmt.cc +++ b/broker/core/sql/src/mysql_bulk_stmt.cc @@ -1,20 +1,20 @@ /** -* Copyright 2018-2023 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2018-2023 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/sql/mysql_bulk_stmt.hh" @@ -57,10 +57,10 @@ std::unique_ptr mysql_bulk_stmt::create_bind() { } _reserved_size = avg / _hist_size.size() + 1; } - log_v2::sql()->trace("new mysql bind of stmt {} reserved with {} rows", - get_id(), _reserved_size); - auto retval = - std::make_unique(get_param_count(), _reserved_size); + _logger->trace("new mysql bind of stmt {} reserved with {} rows", get_id(), + _reserved_size); + auto retval = std::make_unique(get_param_count(), + _reserved_size, _logger); return retval; } @@ -82,26 +82,26 @@ void mysql_bulk_stmt::set_bind(std::unique_ptr&& bind) { */ std::unique_ptr mysql_bulk_stmt::get_bind() { if (_bind) { - log_v2::sql()->trace("mysql bind of stmt {} returned with {} rows", - get_id(), _bind->rows_count()); + _logger->trace("mysql bind of stmt {} returned with {} rows", get_id(), + _bind->rows_count()); _hist_size.push_back(_bind->rows_count()); } return std::move(_bind); } -#define BIND_VALUE(ftype, vtype) \ - void mysql_bulk_stmt::bind_value_as_##ftype(size_t range, vtype value) { \ - if (!_bind) \ - _bind = std::make_unique(get_param_count(), \ - _reserved_size); \ - _bind->set_value_as_##ftype(range, value); \ - } \ - \ - void mysql_bulk_stmt::bind_null_##ftype(size_t range) { \ - if (!_bind) \ - _bind = std::make_unique(get_param_count(), \ - _reserved_size); \ - _bind->set_null_##ftype(range); \ +#define BIND_VALUE(ftype, vtype) \ + void mysql_bulk_stmt::bind_value_as_##ftype(size_t range, vtype value) { \ + if (!_bind) \ + _bind = std::make_unique( \ + get_param_count(), _reserved_size, _logger); \ + _bind->set_value_as_##ftype(range, value); \ + } \ + \ + void mysql_bulk_stmt::bind_null_##ftype(size_t range) { \ + if (!_bind) \ + _bind = std::make_unique( \ + get_param_count(), _reserved_size, _logger); \ + _bind->set_null_##ftype(range); \ } BIND_VALUE(i32, int32_t) diff --git a/broker/core/sql/src/mysql_column.cc b/broker/core/sql/src/mysql_column.cc index 763c267a3dc..3049906c291 100644 --- a/broker/core/sql/src/mysql_column.cc +++ b/broker/core/sql/src/mysql_column.cc @@ -1,29 +1,30 @@ /** -* Copyright 2018-2022 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2018-2022 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/sql/mysql_column.hh" #include -#include "com/centreon/broker/log_v2.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::database; +using com::centreon::common::log_v2::log_v2; /** * @brief Destructor @@ -82,10 +83,11 @@ void mysql_column::_free_vector() { std::vector* vector = static_cast*>(_vector); delete vector; } break; - default: - log_v2::sql()->critical( - "mysql_column: unexpected type while vector is freed"); + default: { + auto logger = log_v2::instance().get(log_v2::SQL); + logger->critical("mysql_column: unexpected type while vector is freed"); assert(1 == 0); + } } _vector = nullptr; } @@ -130,9 +132,11 @@ void* mysql_column::get_buffer() { std::vector* vector = static_cast*>(_vector); return vector->data(); } break; - default: - log_v2::sql()->critical("Unexpected type while getting the buffer value"); + default: { + auto logger = log_v2::instance().get(log_v2::SQL); + logger->critical("Unexpected type while getting the buffer value"); assert(1 == 0); + } } return nullptr; } @@ -186,10 +190,12 @@ void mysql_column::clear() { std::vector* vector = static_cast*>(_vector); vector->clear(); } break; - default: - log_v2::sql()->critical( + default: { + auto logger = log_v2::instance().get(log_v2::SQL); + logger->critical( "mysql_column: unexpected type while clearing the vector"); assert(1 == 0); + } } } @@ -238,10 +244,12 @@ void mysql_column::reserve(size_t s) { std::vector* vector = static_cast*>(_vector); vector->reserve(s); } break; - default: - log_v2::sql()->critical( + default: { + auto logger = log_v2::instance().get(log_v2::SQL); + logger->critical( "mysql_column: Unexpected type while vector reservation"); assert(1 == 0); + } } } } @@ -431,10 +439,11 @@ void mysql_column::set_type(int type) { vector->reserve(_rows_to_reserve); _vector = vector; } break; - default: - log_v2::sql()->critical("mysql_column: unexpected type {} for column", - type); + default: { + auto logger = log_v2::instance().get(log_v2::SQL); + logger->critical("mysql_column: unexpected type {} for column", type); assert(1 == 0); + } } } diff --git a/broker/core/sql/src/mysql_connection.cc b/broker/core/sql/src/mysql_connection.cc index 2889b11bb96..61580982e5b 100644 --- a/broker/core/sql/src/mysql_connection.cc +++ b/broker/core/sql/src/mysql_connection.cc @@ -18,14 +18,15 @@ #include #include "com/centreon/broker/config/applier/init.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/misc.hh" #include "com/centreon/broker/sql/mysql_manager.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::database; +using log_v2 = com::centreon::common::log_v2::log_v2; constexpr const char* mysql_error::msg[]; @@ -122,7 +123,7 @@ void mysql_connection::_update_stats() noexcept { float query_avg = _stats.average_query_duration(); { - std::lock_guard lck(stats::center::instance()); + std::lock_guard lck(*_center); _proto_stats->set_waiting_tasks(static_cast(_tasks_count)); if (static_cast(_connected)) { _proto_stats->set_up_since(_switch_point); @@ -176,13 +177,12 @@ bool mysql_connection::_try_to_reconnect() { _clear_connection(); SPDLOG_LOGGER_INFO( - log_v2::sql(), + _logger, "mysql_connection {:p}: server has gone away, attempt to reconnect", static_cast(this)); _conn = mysql_init(nullptr); if (!_conn) { - SPDLOG_LOGGER_ERROR(log_v2::sql(), - "mysql_connection: reconnection failed."); + SPDLOG_LOGGER_ERROR(_logger, "mysql_connection: reconnection failed."); set_error_message("mysql_connection: reconnection failed."); return false; } @@ -195,7 +195,7 @@ bool mysql_connection::_try_to_reconnect() { (_socket == "" ? nullptr : _socket.c_str()), CLIENT_FOUND_ROWS)) { SPDLOG_LOGGER_ERROR( - log_v2::sql(), + _logger, "mysql_connection: The mysql/mariadb database seems not started."); set_error_message( "mysql_connection: The mysql/mariadb database seems not started."); @@ -212,19 +212,18 @@ bool mysql_connection::_try_to_reconnect() { MYSQL_STMT* s = mysql_stmt_init(_conn); if (!s) { SPDLOG_LOGGER_ERROR( - log_v2::sql(), - "mysql_connection: impossible to reset prepared statements"); + _logger, "mysql_connection: impossible to reset prepared statements"); fail = true; break; } else { if (mysql_stmt_prepare(s, itq->second.c_str(), itq->second.size())) { - SPDLOG_LOGGER_ERROR(log_v2::sql(), "mysql_connection: {}", + SPDLOG_LOGGER_ERROR(_logger, "mysql_connection: {}", mysql_stmt_error(s)); fail = true; break; } else { _stmt[itq->first] = s; - SPDLOG_LOGGER_TRACE(log_v2::sql(), + SPDLOG_LOGGER_TRACE(_logger, "mysql_connection {:p}: statement prepared {} " "mysql_statement_id={}: {}", static_cast(this), itq->first, @@ -233,7 +232,7 @@ bool mysql_connection::_try_to_reconnect() { } } if (!fail) { - SPDLOG_LOGGER_DEBUG(log_v2::sql(), "mysql_connection {:p}: connected", + SPDLOG_LOGGER_DEBUG(_logger, "mysql_connection {:p}: connected", static_cast(this)); _switch_point = std::time(nullptr); _connected = true; @@ -246,7 +245,7 @@ bool mysql_connection::_try_to_reconnect() { static_cast(this), ::mysql_error(_conn)) : fmt::format("connection {:p} fail to connect", static_cast(this)); - SPDLOG_LOGGER_ERROR(log_v2::sql(), err_msg); + SPDLOG_LOGGER_ERROR(_logger, err_msg); set_error_message(err_msg); return false; } @@ -257,20 +256,20 @@ void mysql_connection::_query(mysql_task* t) { sql::stats::query_span stats(&_stats, task->query); - SPDLOG_LOGGER_DEBUG(log_v2::sql(), "mysql_connection {:p}: run query: {}", + SPDLOG_LOGGER_DEBUG(_logger, "mysql_connection {:p}: run query: {}", static_cast(this), task->query); if (mysql_query(_conn, task->query.c_str())) { const char* m = mysql_error::msg[task->error_code]; std::string err_msg(fmt::format("{} errrno={} {}", m, ::mysql_errno(_conn), ::mysql_error(_conn))); - SPDLOG_LOGGER_ERROR(log_v2::sql(), "mysql_connection: {}", err_msg); + SPDLOG_LOGGER_ERROR(_logger, "mysql_connection: {}", err_msg); if (_server_error(::mysql_errno(_conn))) set_error_message(err_msg); } else { _last_access = time(nullptr); set_need_to_commit(); } - SPDLOG_LOGGER_TRACE(log_v2::sql(), "mysql_connection {:p}: end run query: {}", + SPDLOG_LOGGER_TRACE(_logger, "mysql_connection {:p}: end run query: {}", static_cast(this), task->query); } @@ -279,11 +278,11 @@ void mysql_connection::_query_res(mysql_task* t) { sql::stats::query_span stats(&_stats, task->query); - SPDLOG_LOGGER_DEBUG(log_v2::sql(), "mysql_connection {:p}: run query: {}", + SPDLOG_LOGGER_DEBUG(_logger, "mysql_connection {:p}: run query: {}", static_cast(this), task->query); if (mysql_query(_conn, task->query.c_str())) { std::string err_msg(::mysql_error(_conn)); - SPDLOG_LOGGER_ERROR(log_v2::sql(), "mysql_connection: {}", err_msg); + SPDLOG_LOGGER_ERROR(_logger, "mysql_connection: {}", err_msg); if (_server_error(mysql_errno(_conn))) /* In case of server error, no exception because we will try again very @@ -306,11 +305,11 @@ void mysql_connection::_query_res(mysql_task* t) { void mysql_connection::_query_int(mysql_task* t) { mysql_task_run_int* task = static_cast(t); sql::stats::query_span stats(&_stats, task->query); - SPDLOG_LOGGER_DEBUG(log_v2::sql(), "mysql_connection {:p}: run query: {}", + SPDLOG_LOGGER_DEBUG(_logger, "mysql_connection {:p}: run query: {}", static_cast(this), task->query); if (mysql_query(_conn, task->query.c_str())) { std::string err_msg(::mysql_error(_conn)); - SPDLOG_LOGGER_ERROR(log_v2::sql(), "mysql_connection: {}", err_msg); + SPDLOG_LOGGER_ERROR(_logger, "mysql_connection: {}", err_msg); if (_server_error(::mysql_errno(_conn))) /* In case of server error, no exception because we will try again very @@ -340,7 +339,7 @@ void mysql_connection::_commit(mysql_task* t) { int32_t attempts = 0; int res; if (_need_commit) { - SPDLOG_LOGGER_DEBUG(log_v2::sql(), "mysql_connection {:p} : commit", + SPDLOG_LOGGER_DEBUG(_logger, "mysql_connection {:p} : commit", static_cast(this)); while (attempts++ < MAX_ATTEMPTS && (res = mysql_commit(_conn))) { err_msg = ::mysql_error(_conn); @@ -348,28 +347,27 @@ void mysql_connection::_commit(mysql_task* t) { set_error_message(err_msg); break; } - SPDLOG_LOGGER_ERROR(log_v2::sql(), "mysql_connection: {}", err_msg); + SPDLOG_LOGGER_ERROR(_logger, "mysql_connection: {}", err_msg); std::this_thread::sleep_for(std::chrono::milliseconds(50)); } if (res == 0) _last_access = std::time(nullptr); } else { - SPDLOG_LOGGER_TRACE(log_v2::sql(), - "mysql_connection {:p} : nothing to commit", + SPDLOG_LOGGER_TRACE(_logger, "mysql_connection {:p} : nothing to commit", static_cast(this)); res = 0; } if (res) { err_msg = fmt::format("Error during commit: {}", ::mysql_error(_conn)); - SPDLOG_LOGGER_ERROR(log_v2::sql(), "mysql_connection: {}", err_msg); + SPDLOG_LOGGER_ERROR(_logger, "mysql_connection: {}", err_msg); } else { /* No more queries are waiting for a commit now. */ _need_commit = false; _last_commit = time(nullptr); } } else { - SPDLOG_LOGGER_TRACE(log_v2::sql(), "mysql_connection {:p} : auto commit", + SPDLOG_LOGGER_TRACE(_logger, "mysql_connection {:p} : auto commit", static_cast(this)); } @@ -391,14 +389,14 @@ void mysql_connection::_commit(mysql_task* t) { void mysql_connection::_prepare(mysql_task* t) { mysql_task_prepare* task(static_cast(t)); if (_stmt.find(task->id) != _stmt.end()) { - SPDLOG_LOGGER_ERROR(log_v2::sql(), + SPDLOG_LOGGER_ERROR(_logger, "mysql_connection: Statement already prepared: {} ({})", task->id, task->query); return; } _stmt_query[task->id] = task->query; - SPDLOG_LOGGER_DEBUG(log_v2::sql(), + SPDLOG_LOGGER_DEBUG(_logger, "mysql_connection {:p}: prepare statement {}: {}", static_cast(this), task->id, task->query); MYSQL_STMT* stmt(mysql_stmt_init(_conn)); @@ -407,12 +405,12 @@ void mysql_connection::_prepare(mysql_task* t) { else { if (mysql_stmt_prepare(stmt, task->query.c_str(), task->query.size())) { std::string err_msg(::mysql_stmt_error(stmt)); - SPDLOG_LOGGER_ERROR(log_v2::sql(), "mysql_connection: {}", err_msg); + SPDLOG_LOGGER_ERROR(_logger, "mysql_connection: {}", err_msg); set_error_message(err_msg); } else { _last_access = time(nullptr); _stmt[task->id] = stmt; - SPDLOG_LOGGER_TRACE(log_v2::sql(), + SPDLOG_LOGGER_TRACE(_logger, "mysql_connection {:p}: statement prepared {} " "mysql_statement_id={}: {}", static_cast(this), task->id, @@ -430,8 +428,7 @@ void mysql_connection::_statement(mysql_task* t) { sql::stats::stmt_span stats(&_stats, task->statement_id, query); MYSQL_STMT* stmt(_stmt[task->statement_id]); if (!stmt) { - SPDLOG_LOGGER_ERROR(log_v2::sql(), - "mysql_connection: no statement to execute"); + SPDLOG_LOGGER_ERROR(_logger, "mysql_connection: no statement to execute"); set_error_message("statement {} not prepared", task->statement_id); return; } @@ -447,7 +444,7 @@ void mysql_connection::_statement(mysql_task* t) { } if (bb && mysql_stmt_bind_param(stmt, bb)) { SPDLOG_LOGGER_ERROR( - log_v2::sql(), + _logger, "mysql_connection: Error while binding values in statement: {}", ::mysql_stmt_error(stmt)); } else { @@ -456,14 +453,14 @@ void mysql_connection::_statement(mysql_task* t) { std::chrono::system_clock::now(); for (;;) { SPDLOG_LOGGER_TRACE( - log_v2::sql(), - "mysql_connection {:p}: execute statement {} attempt {}: {}", + _logger, + "mysql_connection {:p}: execute statement {:x} attempt {}: {}", static_cast(this), task->statement_id, attempts, query); if (mysql_stmt_execute(stmt)) { std::string err_msg( fmt::format("{} errno={} {}", mysql_error::msg[task->error_code], ::mysql_errno(_conn), ::mysql_stmt_error(stmt))); - SPDLOG_LOGGER_ERROR(log_v2::sql(), + SPDLOG_LOGGER_ERROR(_logger, "connection fail to execute statement {:p}: {}", static_cast(this), err_msg); if (_server_error(::mysql_stmt_errno(stmt))) { @@ -476,15 +473,14 @@ void mysql_connection::_statement(mysql_task* t) { if (mysql_commit(_conn)) { SPDLOG_LOGGER_ERROR( - log_v2::sql(), + _logger, "connection fail commit after execute statement failure {:p}", static_cast(this)); set_error_message("Commit failed after execute statement"); break; } - SPDLOG_LOGGER_ERROR(log_v2::sql(), - "mysql_connection {:p} attempts {}: {}", + SPDLOG_LOGGER_ERROR(_logger, "mysql_connection {:p} attempts {}: {}", static_cast(this), attempts, err_msg); if (++attempts >= MAX_ATTEMPTS) { if (_server_error(::mysql_stmt_errno(stmt))) @@ -493,9 +489,9 @@ void mysql_connection::_statement(mysql_task* t) { break; } } else { - SPDLOG_LOGGER_TRACE(log_v2::sql(), + SPDLOG_LOGGER_TRACE(_logger, "mysql_connection {:p}: success execute statement " - "{} attempt {}", + "{:x} attempt {}", static_cast(this), task->statement_id, _stmt_query[task->statement_id]); _last_access = time(nullptr); @@ -504,9 +500,9 @@ void mysql_connection::_statement(mysql_task* t) { } std::this_thread::sleep_for(std::chrono::milliseconds(50)); } - SPDLOG_LOGGER_TRACE(log_v2::sql(), + SPDLOG_LOGGER_TRACE(_logger, "mysql_connection {:p}: end execute statement " - "{} attempt {} duration {}s: {}", + "{:x} attempt {} duration {}s: {}", static_cast(this), task->statement_id, attempts, std::chrono::duration_cast( @@ -520,13 +516,11 @@ void mysql_connection::_statement_res(mysql_task* t) { mysql_task_statement_res* task(static_cast(t)); const std::string& query = _stmt_query[task->statement_id]; sql::stats::stmt_span stats(&_stats, task->statement_id, query); - SPDLOG_LOGGER_DEBUG(log_v2::sql(), - "mysql_connection: execute statement {}: {}", + SPDLOG_LOGGER_DEBUG(_logger, "mysql_connection: execute statement {:x}: {}", task->statement_id, query); MYSQL_STMT* stmt(_stmt[task->statement_id]); if (!stmt) { - SPDLOG_LOGGER_ERROR(log_v2::sql(), - "mysql_connection: no statement to execute"); + SPDLOG_LOGGER_ERROR(_logger, "mysql_connection: no statement to execute"); msg_fmt e("statement not prepared"); task->promise.set_exception(std::make_exception_ptr(e)); return; @@ -543,7 +537,7 @@ void mysql_connection::_statement_res(mysql_task* t) { } if (bb && mysql_stmt_bind_param(stmt, bb)) { std::string err_msg(::mysql_stmt_error(stmt)); - SPDLOG_LOGGER_ERROR(log_v2::sql(), "mysql_connection: {}", err_msg); + SPDLOG_LOGGER_ERROR(_logger, "mysql_connection: {}", err_msg); msg_fmt e("statement and get result failed: {}", err_msg); task->promise.set_exception(std::make_exception_ptr(e)); } else { @@ -551,7 +545,7 @@ void mysql_connection::_statement_res(mysql_task* t) { for (;;) { if (mysql_stmt_execute(stmt)) { std::string err_msg(::mysql_stmt_error(stmt)); - SPDLOG_LOGGER_ERROR(log_v2::sql(), "mysql_connection: {}", err_msg); + SPDLOG_LOGGER_ERROR(_logger, "mysql_connection: {}", err_msg); if (_server_error(mysql_stmt_errno(stmt))) { /* In case of server error, no exception because we will try again * very soon */ @@ -568,7 +562,7 @@ void mysql_connection::_statement_res(mysql_task* t) { if (mysql_commit(_conn)) { SPDLOG_LOGGER_ERROR( - log_v2::sql(), + _logger, "connection fail commit after execute statement failure {:p}", static_cast(this)); if (_server_error(mysql_errno(_conn))) { @@ -603,7 +597,8 @@ void mysql_connection::_statement_res(mysql_task* t) { task->promise.set_value(nullptr); } else { int size(mysql_num_fields(prepare_meta_result)); - auto bind = std::make_unique(size, task->length); + auto bind = + std::make_unique(size, task->length, _logger); if (mysql_stmt_bind_result(stmt, bind->get_bind())) { std::string err_msg(::mysql_stmt_error(stmt)); @@ -642,13 +637,11 @@ void mysql_connection::_statement_int(mysql_task* t) { static_cast*>(t)); const std::string& query = _stmt_query[task->statement_id]; sql::stats::stmt_span stats(&_stats, task->statement_id, query); - SPDLOG_LOGGER_DEBUG(log_v2::sql(), - "mysql_connection: execute statement {}: {}", + SPDLOG_LOGGER_DEBUG(_logger, "mysql_connection: execute statement {:x}: {}", task->statement_id, query); MYSQL_STMT* stmt(_stmt[task->statement_id]); if (!stmt) { - SPDLOG_LOGGER_ERROR(log_v2::sql(), - "mysql_connection: no statement to execute"); + SPDLOG_LOGGER_ERROR(_logger, "mysql_connection: no statement to execute"); msg_fmt e("statement not prepared"); task->promise.set_exception(std::make_exception_ptr(e)); return; @@ -665,7 +658,7 @@ void mysql_connection::_statement_int(mysql_task* t) { } if (bb && mysql_stmt_bind_param(stmt, bb)) { std::string err_msg(::mysql_stmt_error(stmt)); - SPDLOG_LOGGER_ERROR(log_v2::sql(), "mysql_connection: {}", err_msg); + SPDLOG_LOGGER_ERROR(_logger, "mysql_connection: {}", err_msg); msg_fmt e(err_msg); task->promise.set_exception(std::make_exception_ptr(e)); } else { @@ -673,7 +666,7 @@ void mysql_connection::_statement_int(mysql_task* t) { for (;;) { if (mysql_stmt_execute(stmt)) { std::string err_msg(::mysql_stmt_error(stmt)); - SPDLOG_LOGGER_ERROR(log_v2::sql(), "mysql_connection: {}", err_msg); + SPDLOG_LOGGER_ERROR(_logger, "mysql_connection: {}", err_msg); if (_server_error(mysql_stmt_errno(stmt))) { /* In case of server error, no exception because we will try again * very soon */ @@ -690,7 +683,7 @@ void mysql_connection::_statement_int(mysql_task* t) { if (mysql_commit(_conn)) { SPDLOG_LOGGER_ERROR( - log_v2::sql(), + _logger, "connection fail commit after execute statement failure {:p}", static_cast(this)); if (_server_error(mysql_errno(_conn))) { @@ -735,7 +728,7 @@ void mysql_connection::_fetch_row_sync(mysql_task* t) { int res(mysql_stmt_fetch(stmt)); if (res != 0) { if (res == MYSQL_DATA_TRUNCATED) - log_v2::sql()->error( + _logger->error( "columns in the current row are too long, data would be truncated"); task->result->get_bind()->set_empty(); } @@ -855,7 +848,7 @@ void mysql_connection::_run() { } if (config::applier::mode == config::applier::finished) { - SPDLOG_LOGGER_DEBUG(log_v2::sql(), "Connection over."); + SPDLOG_LOGGER_DEBUG(_logger, "Connection over."); _state = finished; _start_condition.notify_all(); lck.unlock(); @@ -888,7 +881,7 @@ void mysql_connection::_run() { if (_error.is_active()) { if (!_try_to_reconnect()) { if (!reconnect_failed_logged) { - SPDLOG_LOGGER_ERROR(log_v2::sql(), "SQL: Reconnection failed."); + SPDLOG_LOGGER_ERROR(_logger, "SQL: Reconnection failed."); reconnect_failed_logged = true; } else if (config::applier::mode == config::applier::finished) { _finish(); @@ -914,7 +907,7 @@ void mysql_connection::_run() { _state = finished; _start_condition.notify_all(); mysql_thread_end(); - log_v2::core()->trace("mysql connection main loop finished."); + _logger->trace("mysql connection main loop finished."); } /** @@ -985,7 +978,7 @@ void mysql_connection::_process_tasks( _commit(nullptr); } } else { - SPDLOG_LOGGER_ERROR(log_v2::sql(), + SPDLOG_LOGGER_ERROR(_logger, "mysql_connection {:p}: Error type not managed...", static_cast(this)); } @@ -1013,23 +1006,23 @@ void mysql_connection::_process_while_empty_task( auto ping = [&]() { std::time_t now = std::time(nullptr); if (now >= _last_access + 30) { - SPDLOG_LOGGER_TRACE(log_v2::sql(), + SPDLOG_LOGGER_TRACE(_logger, "mysql_connection {:p} SQL: performing mysql_ping.", static_cast(this)); if (mysql_ping(_conn)) { if (!_try_to_reconnect()) { - SPDLOG_LOGGER_ERROR(log_v2::sql(), + SPDLOG_LOGGER_ERROR(_logger, "mysql_connection {:p} SQL: Reconnection failed.", static_cast(this)); } } else { SPDLOG_LOGGER_TRACE( - log_v2::sql(), "mysql_connection {:p} SQL: connection always alive", + _logger, "mysql_connection {:p} SQL: connection always alive", static_cast(this)); _last_access = now; } } else { - SPDLOG_LOGGER_TRACE(log_v2::sql(), + SPDLOG_LOGGER_TRACE(_logger, "mysql_connection {:p} SQL: last access to the " "database for this connection for {}s", static_cast(this), now - _last_access); @@ -1044,8 +1037,7 @@ void mysql_connection::_process_while_empty_task( if (time(nullptr) > _last_commit + _max_second_commit_delay) { _commit(nullptr); } - SPDLOG_LOGGER_TRACE(log_v2::sql(), "_tasks_list.size()={}", - _tasks_list.size()); + SPDLOG_LOGGER_TRACE(_logger, "_tasks_list.size()={}", _tasks_list.size()); lock.unlock(); ping(); @@ -1059,7 +1051,7 @@ void mysql_connection::_process_while_empty_task( } else { tasks_list.swap(_tasks_list); lock.unlock(); - SPDLOG_LOGGER_TRACE(log_v2::sql(), "tasks_list={}", _get_stack(tasks_list)); + SPDLOG_LOGGER_TRACE(_logger, "tasks_list={}", _get_stack(tasks_list)); ping(); } } @@ -1068,8 +1060,11 @@ void mysql_connection::_process_while_empty_task( /* Methods executed by the main thread */ /******************************************************************************/ -mysql_connection::mysql_connection(const database_config& db_cfg, - SqlConnectionStats* stats) +mysql_connection::mysql_connection( + const database_config& db_cfg, + SqlConnectionStats* stats, + const std::shared_ptr& logger, + std::shared_ptr center) : _conn(nullptr), _finish_asked(false), _tasks_count{0}, @@ -1091,11 +1086,11 @@ mysql_connection::mysql_connection(const database_config& db_cfg, _proto_stats{stats}, _last_stats{std::time(nullptr)}, _qps(db_cfg.get_queries_per_transaction()), - _category(db_cfg.get_category()) { - DEBUG(fmt::format("CONSTRUCTOR mysql_connection {:p}", - static_cast(this))); + _category(db_cfg.get_category()), + _logger{logger}, + _center{std::move(center)} { std::unique_lock lck(_start_m); - SPDLOG_LOGGER_INFO(log_v2::sql(), + SPDLOG_LOGGER_INFO(_logger, "mysql_connection: starting connection {:p} to {}", static_cast(this), db_cfg); _thread = std::make_unique(&mysql_connection::_run, this); @@ -1103,15 +1098,13 @@ mysql_connection::mysql_connection(const database_config& db_cfg, if (_state == finished) { _thread->join(); SPDLOG_LOGGER_ERROR( - log_v2::sql(), - "mysql_connection {:p}: error while starting connection: {}", + _logger, "mysql_connection {:p}: error while starting connection: {}", static_cast(this), _error.get_message()); throw msg_fmt("mysql_connection: error while starting connection"); } pthread_setname_np(_thread->native_handle(), "mysql_connect"); - SPDLOG_LOGGER_INFO(log_v2::sql(), "mysql_connection: connection started"); - stats::center::instance().update(&SqlConnectionStats::set_waiting_tasks, - _proto_stats, 0); + SPDLOG_LOGGER_INFO(_logger, "mysql_connection: connection started"); + _center->update(&SqlConnectionStats::set_waiting_tasks, _proto_stats, 0); } /** @@ -1119,13 +1112,11 @@ mysql_connection::mysql_connection(const database_config& db_cfg, * the end will occur only when all the queries will be played. */ mysql_connection::~mysql_connection() { - SPDLOG_LOGGER_INFO(log_v2::sql(), "mysql_connection {:p}: finished", + SPDLOG_LOGGER_INFO(_logger, "mysql_connection {:p}: finished", static_cast(this)); stop(); - stats::center::instance().remove_connection(_proto_stats); + _center->remove_connection(_proto_stats); _thread->join(); - DEBUG(fmt::format("DESTRUCTOR mysql_connection {:p}", - static_cast(this))); } void mysql_connection::_push(std::unique_ptr&& q) { diff --git a/broker/core/sql/src/mysql_manager.cc b/broker/core/sql/src/mysql_manager.cc index dbc4bef13d1..c0da64034a8 100644 --- a/broker/core/sql/src/mysql_manager.cc +++ b/broker/core/sql/src/mysql_manager.cc @@ -1,29 +1,31 @@ /** -* Copyright 2018 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2018-2023 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/sql/mysql_manager.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::database; +using log_v2 = com::centreon::common::log_v2::log_v2; + mysql_manager* mysql_manager::_instance{nullptr}; /** @@ -57,8 +59,11 @@ void mysql_manager::unload() { /** * The default constructor */ -mysql_manager::mysql_manager() : _stats_connections_timestamp(time(nullptr)) { - log_v2::sql()->trace("mysql_manager instanciation"); +mysql_manager::mysql_manager() + : _stats_connections_timestamp(time(nullptr)), + _center{stats::center::instance_ptr()}, + _logger{log_v2::instance().get(log_v2::SQL)} { + _logger->trace("mysql_manager instanciation"); } /** @@ -68,7 +73,7 @@ mysql_manager::mysql_manager() : _stats_connections_timestamp(time(nullptr)) { * pending. */ mysql_manager::~mysql_manager() { - log_v2::sql()->trace("mysql_manager destruction"); + _logger->trace("mysql_manager destruction"); // If connections are still active but unique here, we can remove them std::lock_guard cfg_lock(_cfg_mutex); @@ -92,7 +97,7 @@ mysql_manager::~mysql_manager() { */ std::vector> mysql_manager::get_connections( database_config const& db_cfg) { - log_v2::sql()->trace("mysql_manager::get_connections"); + _logger->trace("mysql_manager::get_connections"); std::vector> retval; uint32_t connection_count(db_cfg.get_connections_count()); @@ -118,12 +123,12 @@ std::vector> mysql_manager::get_connections( // We are still missing threads in the configuration to return while (retval.size() < connection_count) { - SqlConnectionStats* s = stats::center::instance().add_connection(); + SqlConnectionStats* s = _center->add_connection(); std::shared_ptr c; try { - c = std::make_shared(db_cfg, s); + c = std::make_shared(db_cfg, s, _logger, _center); } catch (const std::exception& e) { - stats::center::instance().remove_connection(s); + _center->remove_connection(s); throw; } _connection.push_back(c); @@ -145,11 +150,11 @@ void mysql_manager::clear() { try { conn->stop(); } catch (const std::exception& e) { - log_v2::sql()->info("mysql_manager: Unable to stop a connection: {}", - e.what()); + _logger->info("mysql_manager: Unable to stop a connection: {}", + e.what()); } } - log_v2::sql()->debug("mysql_manager: clear finished"); + _logger->debug("mysql_manager: clear finished"); } /** @@ -163,12 +168,12 @@ void mysql_manager::update_connections() { while (it != _connection.end()) { if (it->unique() || (*it)->is_finished()) { it = _connection.erase(it); - log_v2::sql()->debug("mysql_manager: one connection removed"); + _logger->debug("mysql_manager: one connection removed"); } else ++it; } - log_v2::sql()->info("mysql_manager: currently {} active connection{}", - _connection.size(), _connection.size() > 1 ? "s" : ""); + _logger->info("mysql_manager: currently {} active connection{}", + _connection.size(), _connection.size() > 1 ? "s" : ""); if (_connection.size() == 0) mysql_library_end(); diff --git a/broker/core/sql/src/mysql_stmt.cc b/broker/core/sql/src/mysql_stmt.cc index 98a3561616a..c3222c0510f 100644 --- a/broker/core/sql/src/mysql_stmt.cc +++ b/broker/core/sql/src/mysql_stmt.cc @@ -63,8 +63,8 @@ mysql_stmt::mysql_stmt(const std::string& query, * @return An unique pointer to a mysql_bind. */ std::unique_ptr mysql_stmt::create_bind() { - log_v2::sql()->trace("new mysql bind of stmt {}", get_id()); - auto retval = std::make_unique(get_param_count()); + _logger->trace("new mysql bind of stmt {}", get_id()); + auto retval = std::make_unique(get_param_count(), _logger); return retval; } @@ -107,7 +107,7 @@ mysql_stmt& mysql_stmt::operator=(mysql_stmt&& other) { */ std::unique_ptr mysql_stmt::get_bind() { if (_bind) - log_v2::sql()->trace("mysql bind of stmt {} returned", get_id()); + _logger->trace("mysql bind of stmt {} returned", get_id()); return std::move(_bind); } @@ -162,7 +162,7 @@ void mysql_stmt::operator<<(io::data const& d) { const std::string& v(current_entry->get_string(d, &max_len)); fmt::string_view sv; if (max_len > 0 && v.size() > max_len) { - log_v2::sql()->trace( + _logger->trace( "column '{}' should admit a longer string, it is cut to {} " "characters to be stored anyway.", current_entry->get_name_v2(), max_len); @@ -172,7 +172,7 @@ void mysql_stmt::operator<<(io::data const& d) { sv = fmt::string_view(v); uint32_t attr = current_entry->get_attribute(); - if (attr & mapping::entry::invalid_on_zero && sv.size() == 0) + if ((attr & mapping::entry::invalid_on_zero) && sv.size() == 0) bind_null_str_k(field); else bind_value_as_str_k(field, sv); @@ -279,7 +279,7 @@ void mysql_stmt::operator<<(io::data const& d) { std::string v(refl->GetString(*p, f)); fmt::string_view sv; if (max_len > 0 && v.size() > max_len) { - log_v2::sql()->trace( + _logger->trace( "column '{}' should admit a longer string, it is cut to {} " "characters to be stored anyway.", field, max_len); @@ -310,7 +310,7 @@ void mysql_stmt::operator<<(io::data const& d) { void mysql_stmt::bind_value_as_f32(size_t range, float value) { if (!_bind) - _bind = std::make_unique(get_param_count()); + _bind = std::make_unique(get_param_count(), _logger); if (std::isinf(value) || std::isnan(value)) _bind->set_null_f32(range); @@ -320,13 +320,13 @@ void mysql_stmt::bind_value_as_f32(size_t range, float value) { void mysql_stmt::bind_null_f32(size_t range) { if (!_bind) - _bind = std::make_unique(get_param_count()); + _bind = std::make_unique(get_param_count(), _logger); _bind->set_null_f32(range); } void mysql_stmt::bind_value_as_f64(size_t range, double value) { if (!_bind) - _bind = std::make_unique(get_param_count()); + _bind = std::make_unique(get_param_count(), _logger); if (std::isinf(value) || std::isnan(value)) _bind->set_null_f64(range); @@ -336,21 +336,23 @@ void mysql_stmt::bind_value_as_f64(size_t range, double value) { void mysql_stmt::bind_null_f64(size_t range) { if (!_bind) - _bind = std::make_unique(get_param_count()); + _bind = std::make_unique(get_param_count(), _logger); _bind->set_null_f64(range); } -#define BIND_VALUE(ftype, vtype) \ - void mysql_stmt::bind_value_as_##ftype(size_t range, vtype value) { \ - if (!_bind) \ - _bind = std::make_unique(get_param_count()); \ - _bind->set_value_as_##ftype(range, value); \ - } \ - \ - void mysql_stmt::bind_null_##ftype(size_t range) { \ - if (!_bind) \ - _bind = std::make_unique(get_param_count()); \ - _bind->set_null_##ftype(range); \ +#define BIND_VALUE(ftype, vtype) \ + void mysql_stmt::bind_value_as_##ftype(size_t range, vtype value) { \ + if (!_bind) \ + _bind = \ + std::make_unique(get_param_count(), _logger); \ + _bind->set_value_as_##ftype(range, value); \ + } \ + \ + void mysql_stmt::bind_null_##ftype(size_t range) { \ + if (!_bind) \ + _bind = \ + std::make_unique(get_param_count(), _logger); \ + _bind->set_null_##ftype(range); \ } BIND_VALUE(i32, int32_t) diff --git a/broker/core/sql/src/mysql_stmt_base.cc b/broker/core/sql/src/mysql_stmt_base.cc index 3ef1e39f730..ee94dc58816 100644 --- a/broker/core/sql/src/mysql_stmt_base.cc +++ b/broker/core/sql/src/mysql_stmt_base.cc @@ -1,20 +1,20 @@ /** -* Copyright 2023 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2023 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/sql/mysql_stmt_base.hh" @@ -25,10 +25,18 @@ #include "com/centreon/broker/io/protobuf.hh" #include "com/centreon/broker/mapping/entry.hh" #include "com/centreon/broker/misc/string.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::database; +using com::centreon::common::log_v2::log_v2; + +/** + * @brief Constructor. + */ +mysql_stmt_base::mysql_stmt_base(bool bulk) + : _bulk(bulk), _logger{log_v2::instance().get(log_v2::SQL)} {} /** * @brief Constructor of a mysql_stmt_base from a SQL query template. This @@ -43,7 +51,7 @@ using namespace com::centreon::broker::database; mysql_stmt_base::mysql_stmt_base(const std::string& query, bool named, bool bulk) - : _bulk(bulk) { + : _bulk(bulk), _logger{log_v2::instance().get(log_v2::SQL)} { mysql_bind_mapping bind_mapping; std::hash hash_fn; if (named) { @@ -124,7 +132,8 @@ mysql_stmt_base::mysql_stmt_base(const std::string& query, : _bulk(bulk), _id(std::hash{}(query)), _query(query), - _bind_mapping(bind_mapping) { + _bind_mapping(bind_mapping), + _logger{log_v2::instance().get(log_v2::SQL)} { if (bind_mapping.empty()) _param_count = _compute_param_count(query); else @@ -140,7 +149,8 @@ mysql_stmt_base::mysql_stmt_base(mysql_stmt_base&& other) _param_count(std::move(other._param_count)), _query(std::move(other._query)), _bind_mapping(std::move(other._bind_mapping)), - _pb_mapping(std::move(other._pb_mapping)) {} + _pb_mapping(std::move(other._pb_mapping)), + _logger{std::move(other._logger)} {} /** * @brief Move copy @@ -244,54 +254,52 @@ void mysql_stmt_base::set_pb_mapping( _pb_mapping = std::move(mapping); } -#define BIND_VALUE(ftype, vtype) \ - void mysql_stmt_base::bind_value_as_##ftype##_k(const std::string& name, \ - vtype value) { \ - mysql_bind_mapping::iterator it(_bind_mapping.find(name)); \ - if (it != _bind_mapping.end()) { \ - bind_value_as_##ftype(it->second, value); \ - } else { \ - std::string key(name); \ - key.append("1"); \ - it = _bind_mapping.find(key); \ - if (it != _bind_mapping.end()) { \ - bind_value_as_##ftype(it->second, value); \ - key[key.size() - 1] = '2'; \ - it = _bind_mapping.find(key); \ - if (it != _bind_mapping.end()) \ - bind_value_as_##ftype(it->second, value); \ - else \ - log_v2::sql()->error( \ - "mysql: cannot bind object with name '{}' to " #ftype \ - " value {} in " \ - "statement {}", \ - name, value, get_id()); \ - } \ - } \ - } \ - \ - void mysql_stmt_base::bind_null_##ftype##_k(const std::string& name) { \ - mysql_bind_mapping::iterator it(_bind_mapping.find(name)); \ - if (it != _bind_mapping.end()) { \ - bind_null_##ftype(it->second); \ - } else { \ - std::string key(name); \ - key.append("1"); \ - it = _bind_mapping.find(key); \ - if (it != _bind_mapping.end()) { \ - bind_null_##ftype(it->second); \ - key[key.size() - 1] = '2'; \ - it = _bind_mapping.find(key); \ - if (it != _bind_mapping.end()) \ - bind_null_##ftype(it->second); \ - else \ - log_v2::sql()->error( \ - "mysql: cannot bind object with name '{}' to " #ftype \ - " null value in " \ - "statement {}", \ - name, get_id()); \ - } \ - } \ +#define BIND_VALUE(ftype, vtype) \ + void mysql_stmt_base::bind_value_as_##ftype##_k(const std::string& name, \ + vtype value) { \ + mysql_bind_mapping::iterator it(_bind_mapping.find(name)); \ + if (it != _bind_mapping.end()) { \ + bind_value_as_##ftype(it->second, value); \ + } else { \ + std::string key(name); \ + key.append("1"); \ + it = _bind_mapping.find(key); \ + if (it != _bind_mapping.end()) { \ + bind_value_as_##ftype(it->second, value); \ + key[key.size() - 1] = '2'; \ + it = _bind_mapping.find(key); \ + if (it != _bind_mapping.end()) \ + bind_value_as_##ftype(it->second, value); \ + else \ + _logger->error("mysql: cannot bind object with name '{}' to " #ftype \ + " value {} in " \ + "statement {}", \ + name, value, get_id()); \ + } \ + } \ + } \ + \ + void mysql_stmt_base::bind_null_##ftype##_k(const std::string& name) { \ + mysql_bind_mapping::iterator it(_bind_mapping.find(name)); \ + if (it != _bind_mapping.end()) { \ + bind_null_##ftype(it->second); \ + } else { \ + std::string key(name); \ + key.append("1"); \ + it = _bind_mapping.find(key); \ + if (it != _bind_mapping.end()) { \ + bind_null_##ftype(it->second); \ + key[key.size() - 1] = '2'; \ + it = _bind_mapping.find(key); \ + if (it != _bind_mapping.end()) \ + bind_null_##ftype(it->second); \ + else \ + _logger->error("mysql: cannot bind object with name '{}' to " #ftype \ + " null value in " \ + "statement {}", \ + name, get_id()); \ + } \ + } \ } BIND_VALUE(i32, int32_t) diff --git a/broker/core/sql/src/query_preparator.cc b/broker/core/sql/src/query_preparator.cc index d4168180570..98eac85eb76 100644 --- a/broker/core/sql/src/query_preparator.cc +++ b/broker/core/sql/src/query_preparator.cc @@ -1,32 +1,33 @@ /** -* Copyright 2015, 2020-2022 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2015, 2020-2022 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/sql/query_preparator.hh" #include "com/centreon/broker/io/events.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/mapping/entry.hh" #include "com/centreon/broker/sql/mysql.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::database; +using com::centreon::common::log_v2::log_v2; /** * Constructor. @@ -39,7 +40,10 @@ query_preparator::query_preparator( uint32_t event_id, query_preparator::event_unique const& unique, query_preparator::excluded_fields const& excluded) - : _event_id(event_id), _excluded(excluded), _unique(unique) {} + : _logger{log_v2::instance().get(log_v2::SQL)}, + _event_id(event_id), + _excluded(excluded), + _unique(unique) {} /** * Constructor. @@ -50,7 +54,9 @@ query_preparator::query_preparator( query_preparator::query_preparator( uint32_t event_id, const query_preparator::event_pb_unique& pb_unique) - : _event_id(event_id), _pb_unique(pb_unique) {} + : _logger{log_v2::instance().get(log_v2::SQL)}, + _event_id(event_id), + _pb_unique(pb_unique) {} /** * @brief Prepare an INSERT query. The function waits for the table to insert @@ -125,7 +131,7 @@ mysql_stmt query_preparator::prepare_insert_into( query.resize(query.size() - 1); query.append(")"); - log_v2::sql()->debug("mysql: query_preparator: {}", query); + _logger->debug("mysql: query_preparator: {}", query); // Prepare statement. mysql_stmt retval; try { @@ -216,7 +222,7 @@ mysql_stmt query_preparator::prepare_insert(mysql& ms, bool ignore) { query.resize(query.size() - 1); query.append(")"); } - log_v2::sql()->debug("mysql: query_preparator: {}", query); + _logger->debug("mysql: query_preparator: {}", query); // Prepare statement. mysql_stmt retval; try { @@ -293,7 +299,7 @@ mysql_stmt query_preparator::prepare_insert_or_update(mysql& ms) { insert_bind_mapping.insert( std::make_pair(it->first, it->second + insert_size)); - log_v2::sql()->debug("mysql: query_preparator: {}", insert); + _logger->debug("mysql: query_preparator: {}", insert); // Prepare statement. mysql_stmt retval; try { @@ -400,7 +406,7 @@ mysql_stmt query_preparator::prepare_insert_or_update_table( insert_bind_mapping.insert( std::make_pair(it->first, it->second + insert_size)); - log_v2::sql()->debug("mysql: query_preparator: {}", insert); + _logger->debug("mysql: query_preparator: {}", insert); // Prepare statement. mysql_stmt retval; try { @@ -670,7 +676,7 @@ mysql_stmt query_preparator::prepare_delete_table(mysql& ms, } query.resize(query.size() - 5); - log_v2::sql()->debug("mysql: query_preparator: {}", query); + _logger->debug("mysql: query_preparator: {}", query); // Prepare statement. mysql_stmt retval; try { diff --git a/broker/core/src/bbdo/acceptor.cc b/broker/core/src/bbdo/acceptor.cc index c84f55b8938..78ebf18cdad 100644 --- a/broker/core/src/bbdo/acceptor.cc +++ b/broker/core/src/bbdo/acceptor.cc @@ -25,6 +25,7 @@ #include "com/centreon/broker/config/applier/init.hh" #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/io/protocols.hh" +#include "com/centreon/broker/multiplexing/muxer_filter.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::bbdo; @@ -54,7 +55,10 @@ acceptor::acceptor(std::string name, uint32_t ack_limit, std::list>&& extensions, bool grpc_serialized) - : io::endpoint(!one_peer_retention_mode, {}), + : io::endpoint( + !one_peer_retention_mode, + multiplexing::muxer_filter(multiplexing::muxer_filter::zero_init()), + multiplexing::muxer_filter(multiplexing::muxer_filter::zero_init())), _coarse(coarse), _name(std::move(name)), _negotiate(negotiate), diff --git a/broker/core/src/bbdo/connector.cc b/broker/core/src/bbdo/connector.cc index 90a7522105c..d8f3fa3d6ba 100644 --- a/broker/core/src/bbdo/connector.cc +++ b/broker/core/src/bbdo/connector.cc @@ -24,6 +24,7 @@ #include "com/centreon/broker/bbdo/stream.hh" #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/io/protocols.hh" +#include "com/centreon/broker/multiplexing/muxer_filter.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::bbdo; @@ -47,7 +48,11 @@ connector::connector(bool negotiate, uint32_t ack_limit, std::list>&& extensions, bool grpc_serialized) - : io::endpoint{false, {}}, + : io::endpoint{false, + multiplexing::muxer_filter( + multiplexing::muxer_filter::zero_init()), + multiplexing::muxer_filter( + multiplexing::muxer_filter::zero_init())}, _is_input{connector_is_input}, _coarse{coarse}, _negotiate{negotiate}, diff --git a/broker/core/src/bbdo/factory.cc b/broker/core/src/bbdo/factory.cc index 161205b4506..aa52e70da2f 100644 --- a/broker/core/src/bbdo/factory.cc +++ b/broker/core/src/bbdo/factory.cc @@ -1,20 +1,20 @@ /** -* Copyright 2013,2015,2017 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2013,2015,2017 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include @@ -24,10 +24,11 @@ #include "com/centreon/broker/config/applier/state.hh" #include "com/centreon/broker/config/parser.hh" #include "com/centreon/broker/io/protocols.hh" -#include "com/centreon/broker/log_v2.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::bbdo; +using com::centreon::common::log_v2::log_v2; /** * @brief Check if a configuration supports this protocol. @@ -80,13 +81,14 @@ io::endpoint* factory::new_endpoint( // Return value. std::unique_ptr retval; + auto logger = log_v2::instance().get(log_v2::CORE); std::map::const_iterator it; // Coarse endpoint ? bool coarse = false; it = cfg.params.find("coarse"); if (it != cfg.params.end()) { if (!absl::SimpleAtob(it->second, &coarse)) { - log_v2::bbdo()->error( + logger->error( "factory: cannot parse the 'coarse' boolean: the content is '{}'", it->second); coarse = false; @@ -110,8 +112,7 @@ io::endpoint* factory::new_endpoint( uint32_t ack_limit{1000}; it = cfg.params.find("ack_limit"); if (it != cfg.params.end() && !absl::SimpleAtoi(it->second, &ack_limit)) { - log_v2::bbdo()->error( - "BBDO: Bad value for ack_limit, it must be an integer."); + logger->error("BBDO: Bad value for ack_limit, it must be an integer."); ack_limit = 1000; } @@ -132,14 +133,16 @@ io::endpoint* factory::new_endpoint( if (it != cfg.params.end()) { if (cfg.type == "bbdo_server") { if (!absl::SimpleAtob(it->second, &keep_retention)) { - log_v2::bbdo()->error( - "BBDO: cannot parse the 'retention' boolean: its content is " - "'{}'", - it->second); + log_v2::instance() + .get(log_v2::CORE) + ->error( + "BBDO: cannot parse the 'retention' boolean: its content is " + "'{}'", + it->second); keep_retention = false; } } else { - log_v2::bbdo()->error( + logger->error( "BBDO: Configuration error, the 'retention' mode should be " "set only on a bbdo_server"); keep_retention = false; @@ -149,7 +152,7 @@ io::endpoint* factory::new_endpoint( it = cfg.params.find("one_peer_retention_mode"); if (it != cfg.params.end()) { if (!absl::SimpleAtob(it->second, &keep_retention)) { - log_v2::bbdo()->error( + logger->error( "BBDO: cannot parse the 'one_peer_retention_mode' boolean: the " "content is '{}'", it->second); @@ -160,8 +163,9 @@ io::endpoint* factory::new_endpoint( // One peer retention mode? (i.e. keep_retention + acceptor_is_output) bool acceptor_is_output = cfg.get_io_type() == config::endpoint::output; if (!acceptor_is_output && keep_retention) - log_v2::bbdo()->error( - "BBDO: Configuration error, the one peer retention mode should be " + logger->error( + "BBDO: Configuration error, the one peer retention mode should " + "be " "set only when the connection is reversed"); retval = std::make_unique( @@ -169,13 +173,13 @@ io::endpoint* factory::new_endpoint( ack_limit, std::move(extensions), grpc_serialized); if (acceptor_is_output && keep_retention) is_acceptor = false; - log_v2::bbdo()->debug("BBDO: new acceptor {}", cfg.name); + logger->debug("BBDO: new acceptor {}", cfg.name); } else { bool connector_is_input = cfg.get_io_type() == config::endpoint::input; retval = std::make_unique( negotiate, cfg.read_timeout, connector_is_input, coarse, ack_limit, std::move(extensions), grpc_serialized); - log_v2::bbdo()->debug("BBDO: new connector {}", cfg.name); + logger->debug("BBDO: new connector {}", cfg.name); } return retval.release(); } diff --git a/broker/core/src/bbdo/internal.cc b/broker/core/src/bbdo/internal.cc index 2eb6f32e946..4278ea00ad9 100644 --- a/broker/core/src/bbdo/internal.cc +++ b/broker/core/src/bbdo/internal.cc @@ -1,20 +1,20 @@ /** -* Copyright 2013, 2021 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2013, 2021 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/bbdo/internal.hh" @@ -24,7 +24,6 @@ #include "com/centreon/broker/bbdo/factory.hh" #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/io/protocols.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon::exceptions; @@ -55,6 +54,8 @@ void bbdo::load() { &bbdo::pb_ack::operations); e.register_event(make_type(io::bbdo, bbdo::de_pb_stop), "Stop", &bbdo::pb_stop::operations); + e.register_event(make_type(io::local, local::de_pb_stop), "LocStop", + &local::pb_stop::operations); // Register BBDO protocol. io::protocols::instance().reg("BBDO", std::make_shared(), 7, diff --git a/broker/core/src/bbdo/stream.cc b/broker/core/src/bbdo/stream.cc index 796e3e1c14c..f4fb8ab754f 100644 --- a/broker/core/src/bbdo/stream.cc +++ b/broker/core/src/bbdo/stream.cc @@ -1,20 +1,20 @@ /** -* Copyright 2013,2015,2017, 2021 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2013,2015,2017, 2021-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/bbdo/stream.hh" @@ -22,6 +22,7 @@ #include #include +#include #include "bbdo/bbdo.pb.h" #include "bbdo/bbdo/ack.hh" @@ -32,15 +33,18 @@ #include "com/centreon/broker/exceptions/timeout.hh" #include "com/centreon/broker/io/protocols.hh" #include "com/centreon/broker/io/raw.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/misc.hh" #include "com/centreon/broker/misc/string.hh" +#include "com/centreon/broker/multiplexing/publisher.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::bbdo; +using log_v2 = com::centreon::common::log_v2::log_v2; + /** * Set a boolean within an object. */ @@ -48,14 +52,11 @@ static uint32_t set_boolean(io::data& t, mapping::entry const& member, void const* data, uint32_t size) { - if (!size) { - SPDLOG_LOGGER_ERROR(log_v2::bbdo(), - "cannot extract boolean value: 0 bytes left in " - "packet"); + if (!size) throw msg_fmt( "cannot extract boolean value: " "0 bytes left in packet"); - } + member.set_bool(t, *static_cast(data)); return 1; } @@ -69,17 +70,11 @@ static uint32_t set_double(io::data& t, uint32_t size) { char const* str(static_cast(data)); uint32_t len(strlen(str)); - if (len >= size) { - SPDLOG_LOGGER_ERROR( - log_v2::bbdo(), - "cannot extract double value: not terminating '\\0' in remaining " - "{} bytes of packet", - size); + if (len >= size) throw msg_fmt( "cannot extract double value: " "not terminating '\\0' in remaining {} bytes of packet", size); - } member.set_double(t, strtod(str, nullptr)); return len + 1; } @@ -91,15 +86,11 @@ static uint32_t set_integer(io::data& t, mapping::entry const& member, void const* data, uint32_t size) { - if (size < sizeof(uint32_t)) { - SPDLOG_LOGGER_ERROR(log_v2::bbdo(), - "cannot extract integer value: {} bytes left in packet", - size); + if (size < sizeof(uint32_t)) throw msg_fmt( "BBDO: cannot extract integer value: {}" " bytes left in packet", size); - } member.set_int(t, ntohl(*static_cast(data))); return sizeof(uint32_t); } @@ -111,15 +102,11 @@ static uint32_t set_short(io::data& t, mapping::entry const& member, void const* data, uint32_t size) { - if (size < sizeof(uint16_t)) { - SPDLOG_LOGGER_ERROR( - log_v2::bbdo(), - "BBDO: cannot extract short value: {} bytes left in packet", size); + if (size < sizeof(uint16_t)) throw msg_fmt( "BBDO: cannot extract short value: {}" " bytes left in packet", size); - } member.set_short(t, ntohs(*static_cast(data))); return sizeof(uint16_t); } @@ -133,18 +120,11 @@ static uint32_t set_string(io::data& t, uint32_t size) { char const* str(static_cast(data)); uint32_t len(strlen(str)); - if (len >= size) { - SPDLOG_LOGGER_ERROR( - log_v2::bbdo(), - "BBDO: cannot extract string value: no terminating '\\0' in remaining " - "{} bytes left in packet", - size); - + if (len >= size) throw msg_fmt( "BBDO: cannot extract string value: " "no terminating '\\0' in remaining {} bytes of packet", size); - } member.set_string(t, str); return len + 1; } @@ -156,15 +136,11 @@ static uint32_t set_timestamp(io::data& t, mapping::entry const& member, void const* data, uint32_t size) { - if (size < sizeof(uint64_t)) { - SPDLOG_LOGGER_ERROR( - log_v2::bbdo(), - "BBDO: cannot extract timestamp value: {} bytes left in packet", size); + if (size < sizeof(uint64_t)) throw msg_fmt( "BBDO: cannot extract timestamp value: {}" " bytes left in packet", size); - } uint32_t const* ptr(static_cast(data)); uint64_t val(ntohl(*ptr)); ++ptr; @@ -181,16 +157,11 @@ static uint32_t set_uint(io::data& t, mapping::entry const& member, void const* data, uint32_t size) { - if (size < sizeof(uint32_t)) { - SPDLOG_LOGGER_ERROR( - log_v2::bbdo(), - "BBDO: cannot extract uint32_t integer value: {} bytes left in packet", - size); + if (size < sizeof(uint32_t)) throw msg_fmt( "BBDO: cannot extract uint32_teger value: {}" " bytes left in packet", size); - } member.set_uint(t, ntohl(*static_cast(data))); return sizeof(uint32_t); } @@ -202,17 +173,11 @@ static uint32_t set_ulong(io::data& t, mapping::entry const& member, void const* data, uint32_t size) { - if (size < sizeof(uint64_t)) { - SPDLOG_LOGGER_ERROR( - log_v2::bbdo(), - "BBDO: cannot extract uint64_t integer value: {} bytes left in packet", - size); + if (size < sizeof(uint64_t)) throw msg_fmt( "BBDO: cannot extract uint64_teger value: {}" " bytes left in packet", size); - } - const uint32_t* ptr(static_cast(data)); uint64_t val(ntohl(*ptr)); ++ptr; @@ -234,11 +199,11 @@ static uint32_t set_ulong(io::data& t, * * @return Event. */ -static io::data* unserialize(uint32_t event_type, - uint32_t source_id, - uint32_t destination_id, - const char* buffer, - uint32_t size) { +io::data* stream::unserialize(uint32_t event_type, + uint32_t source_id, + uint32_t destination_id, + const char* buffer, + uint32_t size) { // Get event info (operations and mapping). io::event_info const* info(io::events::instance().get_event_info(event_type)); if (info) { @@ -282,16 +247,13 @@ static io::data* unserialize(uint32_t event_type, default: SPDLOG_LOGGER_ERROR( - log_v2::bbdo(), + _logger, "BBDO: invalid mapping for object of type '{0}': {1} is " - "not " - "a known type ID", + "not a known type ID", info->get_name(), current_entry->get_type()); throw msg_fmt( - "BBDO: invalid mapping for " - "object of type '{}" - "': {}" - " is not a known type ID", + "BBDO: invalid mapping for object of type '{}" + "': {} is not a known type ID", info->get_name(), current_entry->get_type()); } buffer += rb; @@ -300,7 +262,7 @@ static io::data* unserialize(uint32_t event_type, return t.release(); } else { SPDLOG_LOGGER_ERROR( - log_v2::bbdo(), + _logger, "BBDO: cannot create object of ID {} whereas it has been " "registered", event_type); @@ -317,7 +279,7 @@ static io::data* unserialize(uint32_t event_type, t->destination_id = destination_id; } else { SPDLOG_LOGGER_ERROR( - log_v2::bbdo(), + _logger, "BBDO: cannot create object of ID {} whereas it has been " "registered", event_type); @@ -330,7 +292,7 @@ static io::data* unserialize(uint32_t event_type, } } else { SPDLOG_LOGGER_INFO( - log_v2::bbdo(), + _logger, "BBDO: cannot unserialize event of ID {}: event was not registered and " "will therefore be ignored", event_type); @@ -443,7 +405,7 @@ static void get_ulong(io::data const& t, * * @return Serialized event. */ -static io::raw* serialize(const io::data& e) { +io::raw* stream::serialize(const io::data& e) { std::deque> queue; // Get event info (mapping). @@ -490,7 +452,7 @@ static io::raw* serialize(const io::data& e) { break; default: SPDLOG_LOGGER_ERROR( - log_v2::bbdo(), + _logger, "BBDO: invalid mapping for object of type '{}': {} is not a " "known type ID", info->get_name(), current_entry->get_type()); @@ -588,7 +550,7 @@ static io::raw* serialize(const io::data& e) { return buffer.release(); } else { SPDLOG_LOGGER_INFO( - log_v2::bbdo(), + _logger, "BBDO: cannot serialize event of ID {}: event was not registered and " "will therefore be ignored", e.type()); @@ -618,10 +580,12 @@ stream::stream(bool is_input, _ack_limit(1000), _events_received_since_last_ack(0), _last_sent_ack(time(nullptr)), + _grpc_serialized(grpc_serialized), _extensions{extensions}, _bbdo_version(config::applier::state::instance().get_bbdo_version()), - _grpc_serialized(grpc_serialized) { - SPDLOG_LOGGER_DEBUG(log_v2::core(), "create bbdo stream {:p}", + _logger{log_v2::instance().get(log_v2::BBDO)} { + SPDLOG_LOGGER_DEBUG(log_v2::instance().get(log_v2::CORE), + "create bbdo stream {:p}", static_cast(this)); } @@ -630,8 +594,8 @@ stream::stream(bool is_input, * */ stream::~stream() { - SPDLOG_LOGGER_DEBUG(log_v2::core(), "destroy bbdo stream {:p}", - static_cast(this)); + SPDLOG_LOGGER_DEBUG(_logger, "destroy bbdo stream {}", + static_cast(this)); } /** @@ -641,6 +605,7 @@ stream::~stream() { * @return The number of events to acknowledge. */ int32_t stream::stop() { + _logger->trace("bbdo::stream stop {}", static_cast(this)); /* A concrete explanation: * I'm engine and my work is to send data to broker. * Here, the user wants to stop me/ I need to ask broker how many @@ -649,16 +614,17 @@ int32_t stream::stop() { try { _send_event_stop_and_wait_for_ack(); } catch (const std::exception& e) { - log_v2::core()->info( - "BBDO: unable to send stop message to peer, it is already stopped: " + _logger->info( + "BBDO: unable to send stop message to peer, it is already " + "stopped: " "{}", e.what()); } } /* We acknowledge peer about received events. */ - log_v2::core()->info("bbdo stream stopped with {} events acknowledged", - _events_received_since_last_ack); + _logger->info("bbdo stream stopped with {} events acknowledged", + _events_received_since_last_ack); if (_events_received_since_last_ack) send_event_acknowledgement(); @@ -690,27 +656,23 @@ int stream::flush() { */ void stream::_send_event_stop_and_wait_for_ack() { if (!_coarse) { - if (_bbdo_version.major_v >= 3) { - SPDLOG_LOGGER_DEBUG(log_v2::bbdo(), - "BBDO: sending pb stop packet to peer"); - std::shared_ptr stop_packet{ - std::make_shared()}; - _write(stop_packet); - } else { - SPDLOG_LOGGER_DEBUG(log_v2::bbdo(), "BBDO: sending stop packet to peer"); - std::shared_ptr stop_packet{std::make_shared()}; - _write(stop_packet); - } - - SPDLOG_LOGGER_DEBUG(log_v2::bbdo(), - "BBDO: retrieving ack packet from peer"); + SPDLOG_LOGGER_DEBUG(_logger, "BBDO: sending stop packet to peer"); + /* Here, we send a bbdo::pb_stop that passes through the network contrary + * to the local::pb_stop. */ + std::shared_ptr stop_packet{ + std::make_shared()}; + stop_packet->mut_obj().set_poller_id( + config::applier::state::instance().poller_id()); + _write(stop_packet); + + SPDLOG_LOGGER_DEBUG(_logger, "BBDO: retrieving ack packet from peer"); std::shared_ptr d; time_t deadline = time(nullptr) + 5; _read_any(d, deadline); if (!d) { SPDLOG_LOGGER_ERROR( - log_v2::bbdo(), + _logger, "BBDO: no message received from peer. Cannot acknowledge properly " "waiting messages before stopping."); return; @@ -718,7 +680,7 @@ void stream::_send_event_stop_and_wait_for_ack() { switch (d->type()) { case ack::static_type(): SPDLOG_LOGGER_INFO( - log_v2::bbdo(), + _logger, "BBDO: received acknowledgement for {} events before finishing", std::static_pointer_cast(d)->acknowledged_events); acknowledge_events( @@ -726,7 +688,7 @@ void stream::_send_event_stop_and_wait_for_ack() { break; case pb_ack::static_type(): SPDLOG_LOGGER_INFO( - log_v2::bbdo(), + _logger, "BBDO: received acknowledgement for {} events before finishing", std::static_pointer_cast(d) ->obj() @@ -737,7 +699,7 @@ void stream::_send_event_stop_and_wait_for_ack() { break; default: SPDLOG_LOGGER_ERROR( - log_v2::bbdo(), + _logger, "BBDO: wrong message received (type {}) - expected ack event", d->type()); break; @@ -772,10 +734,10 @@ std::string stream::_get_extension_names(bool mandatory) const { * @param[in] neg Negotiation type. */ void stream::negotiate(stream::negotiation_type neg) { - SPDLOG_LOGGER_TRACE(log_v2::bbdo(), "BBDO: negotiate"); + SPDLOG_LOGGER_TRACE(_logger, "BBDO: negotiate"); std::string extensions; if (!_negotiate) { - SPDLOG_LOGGER_INFO(log_v2::bbdo(), "BBDO: negotiation disabled."); + SPDLOG_LOGGER_INFO(_logger, "BBDO: negotiation disabled."); extensions = _get_extension_names(true); } else extensions = _get_extension_names(false); @@ -785,8 +747,8 @@ void stream::negotiate(stream::negotiation_type neg) { // Send our own packet if we should be first. if (neg == negotiate_first) { SPDLOG_LOGGER_DEBUG( - log_v2::bbdo(), - "BBDO: sending welcome packet (available extensions: {})", extensions); + _logger, "BBDO: sending welcome packet (available extensions: {})", + extensions); /* if _negotiate, we send all the extensions we would like to have, * otherwise we only send the mandatory extensions */ if (_bbdo_version.total_version <= v300.total_version) { @@ -808,8 +770,7 @@ void stream::negotiate(stream::negotiation_type neg) { } // Read peer packet. - SPDLOG_LOGGER_DEBUG(log_v2::bbdo(), - "BBDO: retrieving welcome packet of peer"); + SPDLOG_LOGGER_DEBUG(_logger, "BBDO: retrieving welcome packet of peer"); std::shared_ptr d; time_t deadline; if (_timeout == (time_t)-1) @@ -835,7 +796,7 @@ void stream::negotiate(stream::negotiation_type neg) { _bbdo_version.total_version > v300.total_version ? "pb_welcome" : "version_response"); - SPDLOG_LOGGER_ERROR(log_v2::bbdo(), msg); + SPDLOG_LOGGER_ERROR(_logger, msg); throw msg_fmt(msg); } @@ -845,7 +806,7 @@ void stream::negotiate(stream::negotiation_type neg) { std::static_pointer_cast(d)); if (v->bbdo_major != _bbdo_version.major_v) { SPDLOG_LOGGER_ERROR( - log_v2::bbdo(), + _logger, "BBDO: peer is using protocol version {}.{}.{} whereas we're using " "protocol version {}.{}.{}", v->bbdo_major, v->bbdo_minor, v->bbdo_patch, _bbdo_version.major_v, @@ -857,7 +818,7 @@ void stream::negotiate(stream::negotiation_type neg) { _bbdo_version.minor_v, _bbdo_version.patch); } SPDLOG_LOGGER_INFO( - log_v2::bbdo(), + _logger, "BBDO: peer is using protocol version {}.{}.{}, we're using version " "{}.{}.{}", v->bbdo_major, v->bbdo_minor, v->bbdo_patch, _bbdo_version.major_v, @@ -866,8 +827,7 @@ void stream::negotiate(stream::negotiation_type neg) { // Send our own packet if we should be second. if (neg == negotiate_second) { SPDLOG_LOGGER_DEBUG( - log_v2::bbdo(), - "BBDO: sending welcome packet (available extensions: {})", + _logger, "BBDO: sending welcome packet (available extensions: {})", extensions); /* if _negotiate, we send all the extensions we would like to have, * otherwise we only send the mandatory extensions */ @@ -882,7 +842,7 @@ void stream::negotiate(stream::negotiation_type neg) { const auto& pb_version = w->obj().version(); if (pb_version.major() != _bbdo_version.major_v) { SPDLOG_LOGGER_ERROR( - log_v2::bbdo(), + _logger, "BBDO: peer is using protocol version {}.{}.{} whereas we're using " "protocol version {}.{}.{}", pb_version.major(), pb_version.minor(), pb_version.patch(), @@ -894,7 +854,7 @@ void stream::negotiate(stream::negotiation_type neg) { _bbdo_version.major_v, _bbdo_version.minor_v, _bbdo_version.patch); } SPDLOG_LOGGER_INFO( - log_v2::bbdo(), + _logger, "BBDO: peer is using protocol version {}.{}.{}, we're using version " "{}.{}.{}", pb_version.major(), pb_version.minor(), pb_version.patch(), @@ -903,8 +863,7 @@ void stream::negotiate(stream::negotiation_type neg) { // Send our own packet if we should be second. if (neg == negotiate_second) { SPDLOG_LOGGER_DEBUG( - log_v2::bbdo(), - "BBDO: sending welcome packet (available extensions: {})", + _logger, "BBDO: sending welcome packet (available extensions: {})", extensions); /* if _negotiate, we send all the extensions we would like to have, * otherwise we only send the mandatory extensions */ @@ -931,8 +890,7 @@ void stream::negotiate(stream::negotiation_type neg) { // Apply negotiated extensions. SPDLOG_LOGGER_INFO( - log_v2::bbdo(), "BBDO: we have extensions '{}' and peer has '{}'", - extensions, + _logger, "BBDO: we have extensions '{}' and peer has '{}'", extensions, fmt::string_view(peer_extensions.data(), peer_extensions.size())); std::list peer_ext{absl::StrSplit(peer_extensions, ' ')}; for (auto& ext : _extensions) { @@ -942,7 +900,7 @@ void stream::negotiate(stream::negotiation_type neg) { if (peer_it != peer_ext.end()) { if (std::find(running_config.begin(), running_config.end(), ext->name()) == running_config.end()) { - SPDLOG_LOGGER_INFO(log_v2::bbdo(), "BBDO: applying extension '{}'", + SPDLOG_LOGGER_INFO(_logger, "BBDO: applying extension '{}'", ext->name()); for (std::map::const_iterator proto_it = io::protocols::instance().begin(), @@ -957,21 +915,20 @@ void stream::negotiate(stream::negotiation_type neg) { } } } else - SPDLOG_LOGGER_INFO(log_v2::bbdo(), - "BBDO: extension '{}' already configured", + SPDLOG_LOGGER_INFO(_logger, "BBDO: extension '{}' already configured", ext->name()); } else { if (ext->is_mandatory()) { SPDLOG_LOGGER_ERROR( - log_v2::bbdo(), + _logger, "BBDO: extension '{}' is set to 'yes' in the configuration but " "cannot be activated because of peer configuration.", ext->name()); } if (std::find(running_config.begin(), running_config.end(), ext->name()) != running_config.end()) { - SPDLOG_LOGGER_INFO(log_v2::bbdo(), - "BBDO: extension '{}' no more needed", ext->name()); + SPDLOG_LOGGER_INFO(_logger, "BBDO: extension '{}' no more needed", + ext->name()); auto substream = get_substream(); if (substream->get_name() == ext->name()) { auto subsubstream = substream->get_substream(); @@ -993,7 +950,7 @@ void stream::negotiate(stream::negotiation_type neg) { // Stream has now negotiated. _negotiated = true; config::applier::state::instance().add_poller(_poller_id, _poller_name); - SPDLOG_LOGGER_TRACE(log_v2::bbdo(), "Negotiation done."); + SPDLOG_LOGGER_TRACE(_logger, "Negotiation done."); } std::list stream::get_running_config() { @@ -1029,7 +986,7 @@ bool stream::read(std::shared_ptr& d, time_t deadline) { auto version(std::static_pointer_cast(d)); if (version->bbdo_major != _bbdo_version.major_v) { SPDLOG_LOGGER_ERROR( - log_v2::bbdo(), + _logger, "BBDO: peer is using protocol version {}.{}.{}, whereas we're " "using protocol version {}.{}.{}", version->bbdo_major, version->bbdo_minor, version->bbdo_patch, @@ -1043,7 +1000,7 @@ bool stream::read(std::shared_ptr& d, time_t deadline) { _bbdo_version.patch); } SPDLOG_LOGGER_INFO( - log_v2::bbdo(), + _logger, "BBDO: peer is using protocol version {}.{}.{} , we're using " "version " "{}.{}.{}", @@ -1057,7 +1014,7 @@ bool stream::read(std::shared_ptr& d, time_t deadline) { const auto& pb_version = welcome->obj().version(); if (pb_version.major() != _bbdo_version.major_v) { SPDLOG_LOGGER_ERROR( - log_v2::bbdo(), + _logger, "BBDO: peer is using protocol version {}.{}.{}, whereas we're " "using protocol version {}.{}.{}", pb_version.major(), pb_version.minor(), pb_version.patch(), @@ -1071,7 +1028,7 @@ bool stream::read(std::shared_ptr& d, time_t deadline) { _bbdo_version.patch); } SPDLOG_LOGGER_INFO( - log_v2::bbdo(), + _logger, "BBDO: peer is using protocol version {}.{}.{} , we're using " "version " "{}.{}.{}", @@ -1081,13 +1038,13 @@ bool stream::read(std::shared_ptr& d, time_t deadline) { } case ack::static_type(): SPDLOG_LOGGER_INFO( - log_v2::bbdo(), "BBDO: received acknowledgement for {} events", + _logger, "BBDO: received acknowledgement for {} events", std::static_pointer_cast(d)->acknowledged_events); acknowledge_events( std::static_pointer_cast(d)->acknowledged_events); break; case pb_ack::static_type(): - SPDLOG_LOGGER_INFO(log_v2::bbdo(), + SPDLOG_LOGGER_INFO(_logger, "BBDO: received pb acknowledgement for {} events", std::static_pointer_cast(d) ->obj() @@ -1096,23 +1053,28 @@ bool stream::read(std::shared_ptr& d, time_t deadline) { ->obj() .acknowledged_events()); break; - case stop::static_type(): { - SPDLOG_LOGGER_INFO(log_v2::bbdo(), "BBDO: received stop from peer"); - send_event_acknowledgement(); - break; - } + case stop::static_type(): case pb_stop::static_type(): { - SPDLOG_LOGGER_INFO(log_v2::bbdo(), "BBDO: received pb stop from peer"); + SPDLOG_LOGGER_INFO( + _logger, "BBDO: received stop from peer with ID {}", + std::static_pointer_cast(d)->obj().poller_id()); send_event_acknowledgement(); - break; - } + /* Now, we send a local::pb_stop to ask unified_sql to update the + * database since the poller is going away. */ + auto loc_stop = std::make_shared(); + auto& obj = loc_stop->mut_obj(); + obj.set_poller_id( + std::static_pointer_cast(d)->obj().poller_id()); + multiplexing::publisher pblshr; + pblshr.write(loc_stop); + } break; default: break; } // Control messages. SPDLOG_LOGGER_DEBUG( - log_v2::bbdo(), + _logger, "BBDO: event with ID {} was a control message, launching recursive " "read", event_id); @@ -1126,7 +1088,7 @@ bool stream::read(std::shared_ptr& d, time_t deadline) { */ if (!timed_out) { ++_events_received_since_last_ack; - SPDLOG_LOGGER_TRACE(log_v2::bbdo(), "{} events to acknowledge", + SPDLOG_LOGGER_TRACE(_logger, "{} events to acknowledge", _events_received_since_last_ack); } time_t now = time(nullptr); @@ -1160,7 +1122,7 @@ bool stream::_read_any(std::shared_ptr& d, time_t deadline) { _read_packet(BBDO_HEADER_SIZE, deadline); if (!_grpc_serialized_queue.empty()) { d = _grpc_serialized_queue.front(); - SPDLOG_LOGGER_TRACE(log_v2::bbdo(), "read event: {}", *d); + SPDLOG_LOGGER_TRACE(_logger, "read event: {}", *d); _grpc_serialized_queue.pop_front(); return true; } @@ -1178,7 +1140,7 @@ bool stream::_read_any(std::shared_ptr& d, time_t deadline) { uint16_t expected = misc::crc16_ccitt(pack + 2, BBDO_HEADER_SIZE - 2); SPDLOG_LOGGER_TRACE( - log_v2::bbdo(), + _logger, "Reading: header eventID {} sourceID {} destID {} checksum {:x} and " "expected {:x}", event_id, source_id, dest_id, chksum, expected); @@ -1188,7 +1150,7 @@ bool stream::_read_any(std::shared_ptr& d, time_t deadline) { if (_skipped == 0) { // First corrupted byte. SPDLOG_LOGGER_ERROR( - log_v2::bbdo(), + _logger, "peer {} is sending corrupted data: invalid CRC: {:04x} != " "{:04x}", peer(), chksum, expected); @@ -1198,7 +1160,7 @@ bool stream::_read_any(std::shared_ptr& d, time_t deadline) { continue; } else if (_skipped) { SPDLOG_LOGGER_INFO( - log_v2::bbdo(), + _logger, "peer {} sent {} corrupted payload bytes, resuming processing", peer(), _skipped); _skipped = 0; @@ -1213,8 +1175,7 @@ bool stream::_read_any(std::shared_ptr& d, time_t deadline) { std::vector content; if (_packet.size() == BBDO_HEADER_SIZE + packet_size) { SPDLOG_LOGGER_TRACE( - log_v2::bbdo(), - "packet matches header + content => extracting content"); + _logger, "packet matches header + content => extracting content"); // We remove the header from the packet: FIXME DBR this is not // beautiful... @@ -1233,7 +1194,7 @@ bool stream::_read_any(std::shared_ptr& d, time_t deadline) { _packet.erase(_packet.begin(), _packet.begin() + BBDO_HEADER_SIZE + packet_size); SPDLOG_LOGGER_TRACE( - log_v2::bbdo(), + _logger, "packet longer than header + content => splitting the whole of " "size {} to content of size {} and remaining of size {}", previous_packet_size, content.size(), _packet.size()); @@ -1256,7 +1217,7 @@ bool stream::_read_any(std::shared_ptr& d, time_t deadline) { /* There is no reason to have this but no one knows. */ if (_buffer.size() > 0) { SPDLOG_LOGGER_ERROR( - log_v2::bbdo(), + _logger, "There are still {} long BBDO packets that cannot be sent, this " "maybe be due to a corrupted retention file.", _buffer.size()); @@ -1264,7 +1225,7 @@ bool stream::_read_any(std::shared_ptr& d, time_t deadline) { * oldest ones. */ while (_buffer.size() > 3) { SPDLOG_LOGGER_INFO( - log_v2::bbdo(), + _logger, "One too old long event part of type {} removed from memory", _buffer.front().get_event_id()); _buffer.pop_front(); @@ -1277,14 +1238,14 @@ bool stream::_read_any(std::shared_ptr& d, time_t deadline) { packet_size = content.size(); d.reset(unserialize(event_id, source_id, dest_id, pack, packet_size)); if (d) { - SPDLOG_LOGGER_TRACE(log_v2::bbdo(), + SPDLOG_LOGGER_TRACE(_logger, "unserialized {} bytes for event of type {}", BBDO_HEADER_SIZE + packet_size, event_id); } else { - SPDLOG_LOGGER_WARN(log_v2::bbdo(), + SPDLOG_LOGGER_WARN(_logger, "unknown event type {} event cannot be decoded", event_id); - SPDLOG_LOGGER_TRACE(log_v2::bbdo(), "discarded {} bytes", + SPDLOG_LOGGER_TRACE(_logger, "discarded {} bytes", BBDO_HEADER_SIZE + packet_size); } return true; @@ -1308,7 +1269,7 @@ bool stream::_read_any(std::shared_ptr& d, time_t deadline) { /* There is no reason to have this but no one knows. */ if (_buffer.size() > 1) { SPDLOG_LOGGER_ERROR( - log_v2::bbdo(), + _logger, "There are {} long BBDO packets waiting for their missing parts " "in memory, this may be due to a corrupted retention file.", _buffer.size()); @@ -1316,7 +1277,7 @@ bool stream::_read_any(std::shared_ptr& d, time_t deadline) { * oldest ones. */ while (_buffer.size() > 4) { SPDLOG_LOGGER_INFO( - log_v2::bbdo(), + _logger, "One too old long event part of type {} removed from memory", _buffer.front().get_event_id()); _buffer.pop_front(); @@ -1366,7 +1327,7 @@ void stream::_read_packet(size_t size, time_t deadline) { } } if (timeout) { - SPDLOG_LOGGER_TRACE(log_v2::bbdo(), + SPDLOG_LOGGER_TRACE(_logger, "_read_packet timeout!!, size = {}, deadline = {}", size, deadline); throw exceptions::timeout(); @@ -1432,7 +1393,7 @@ void stream::_write(const std::shared_ptr& d) { // Check if data exists. std::shared_ptr serialized(serialize(*d)); if (serialized) { - SPDLOG_LOGGER_TRACE(log_v2::bbdo(), + SPDLOG_LOGGER_TRACE(_logger, "BBDO: serialized event of type {} to {} bytes", d->type(), serialized->size()); _substream->write(serialized); @@ -1470,17 +1431,14 @@ void stream::acknowledge_events(uint32_t events) { */ void stream::send_event_acknowledgement() { if (!_coarse) { + SPDLOG_LOGGER_DEBUG(_logger, "send acknowledgement for {} events", + _events_received_since_last_ack); if (_bbdo_version.total_version >= 0x0300000001) { - SPDLOG_LOGGER_DEBUG(log_v2::core(), - "send pb acknowledgement for {} events", - _events_received_since_last_ack); std::shared_ptr acknowledgement(std::make_shared()); acknowledgement->mut_obj().set_acknowledged_events( _events_received_since_last_ack); _write(acknowledgement); } else { - SPDLOG_LOGGER_DEBUG(log_v2::core(), "send acknowledgement for {} events", - _events_received_since_last_ack); std::shared_ptr acknowledgement( std::make_shared(_events_received_since_last_ack)); _write(acknowledgement); diff --git a/broker/core/src/broker_impl.cc b/broker/core/src/broker_impl.cc index 359187644ce..21f817e07d9 100644 --- a/broker/core/src/broker_impl.cc +++ b/broker/core/src/broker_impl.cc @@ -21,15 +21,16 @@ #include "com/centreon/broker/config/applier/endpoint.hh" #include "com/centreon/broker/config/applier/state.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/multiplexing/publisher.hh" #include "com/centreon/broker/stats/center.hh" #include "com/centreon/broker/stats/helper.hh" #include "com/centreon/broker/version.hh" #include "com/centreon/common/process_stat.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::version; +using com::centreon::common::log_v2::log_v2; /** * @brief Return the Broker's version. @@ -128,7 +129,7 @@ grpc::Status broker_impl::GetModulesStats(grpc::ServerContext* context } grpc::Status broker_impl::GetEndpointStats(grpc::ServerContext* context - __attribute__((unused)), + [[maybe_unused]], const GenericNameOrIndex* request, GenericString* response) { std::vector value; @@ -181,8 +182,8 @@ grpc::Status broker_impl::GetEndpointStats(grpc::ServerContext* context } grpc::Status broker_impl::GetGenericStats( - grpc::ServerContext* context __attribute__((unused)), - const ::google::protobuf::Empty* request __attribute__((unused)), + grpc::ServerContext* context [[maybe_unused]], + const ::google::protobuf::Empty* request [[maybe_unused]], GenericString* response) { nlohmann::json object; stats::get_generic_stats(object); @@ -192,14 +193,15 @@ grpc::Status broker_impl::GetGenericStats( } grpc::Status broker_impl::GetSqlManagerStats(grpc::ServerContext* context - __attribute__((unused)), + [[maybe_unused]], const SqlConnection* request, SqlManagerStats* response) { + auto center = stats::center::instance_ptr(); if (!request->has_id()) - stats::center::instance().get_sql_manager_stats(response); + center->get_sql_manager_stats(response); else { try { - stats::center::instance().get_sql_manager_stats(response, request->id()); + center->get_sql_manager_stats(response, request->id()); } catch (const std::exception& e) { return grpc::Status(grpc::StatusCode::NOT_FOUND, e.what()); } @@ -222,19 +224,21 @@ grpc::Status broker_impl::SetSqlManagerStats( } grpc::Status broker_impl::GetConflictManagerStats( - grpc::ServerContext* context __attribute__((unused)), - const ::google::protobuf::Empty* request __attribute__((unused)), + grpc::ServerContext* context [[maybe_unused]], + const ::google::protobuf::Empty* request [[maybe_unused]], ConflictManagerStats* response) { - stats::center::instance().get_conflict_manager_stats(response); + auto center = stats::center::instance_ptr(); + center->get_conflict_manager_stats(response); return grpc::Status::OK; } grpc::Status broker_impl::GetMuxerStats(grpc::ServerContext* context - __attribute__((unused)), + [[maybe_unused]], const GenericString* request, MuxerStats* response) { const std::string name = request->str_arg(); - bool status = stats::center::instance().muxer_stats(name, response); + auto center = stats::center::instance_ptr(); + bool status = center->muxer_stats(name, response); return status ? grpc::Status::OK : grpc::Status( grpc::StatusCode::NOT_FOUND, @@ -256,10 +260,10 @@ void broker_impl::set_broker_name(const std::string& s) { * @return grpc::Status::OK */ grpc::Status broker_impl::RebuildRRDGraphs(grpc::ServerContext* context - __attribute__((unused)), + [[maybe_unused]], const IndexIds* request, ::google::protobuf::Empty* response - __attribute__((unused))) { + [[maybe_unused]]) { multiplexing::publisher pblshr; auto e{std::make_shared(*request)}; pblshr.write(e); @@ -291,15 +295,16 @@ grpc::Status broker_impl::GetProcessingStats( grpc::ServerContext* context [[maybe_unused]], const ::google::protobuf::Empty* request [[maybe_unused]], ::ProcessingStats* response) { - stats::center::instance().get_processing_stats(response); + auto center = stats::center::instance_ptr(); + center->get_processing_stats(response); return grpc::Status::OK; } grpc::Status broker_impl::RemovePoller(grpc::ServerContext* context - __attribute__((unused)), + [[maybe_unused]], const GenericNameOrIndex* request, ::google::protobuf::Empty*) { - log_v2::core()->info("Remove poller..."); + log_v2::instance().get(log_v2::CORE)->info("Remove poller..."); multiplexing::publisher pblshr; auto e{std::make_shared(*request)}; pblshr.write(e); @@ -312,18 +317,19 @@ grpc::Status broker_impl::GetLogInfo(grpc::ServerContext* context LogInfo* response) { auto& name{request->str_arg()}; auto& map = *response->mutable_level(); - auto lvs = log_v2::instance()->levels(); - response->set_log_name(log_v2::instance()->log_name()); - response->set_log_file(log_v2::instance()->file_path()); - response->set_log_flush_period( - log_v2::instance()->get_flush_interval().count()); + auto lvs = log_v2::instance().levels(); + response->set_log_name(log_v2::instance().log_name()); + response->set_log_file(log_v2::instance().filename()); + response->set_log_flush_period(log_v2::instance().flush_interval().count()); if (!name.empty()) { - auto found = std::find_if(lvs.begin(), lvs.end(), - [&name](std::pair& p) { - return p.first == name; - }); + auto found = std::find_if( + lvs.begin(), lvs.end(), + [&name](std::pair& p) { + return p.first == name; + }); if (found != lvs.end()) { - map[name] = std::move(found->second); + auto level = to_string_view(found->second); + map[name] = std::string(level.data(), level.size()); return grpc::Status::OK; } else { std::string msg{fmt::format("'{}' is not a logger in broker", name)}; @@ -345,7 +351,7 @@ grpc::Status broker_impl::SetLogLevel(grpc::ServerContext* context if (!logger) { std::string err_detail = fmt::format("The '{}' logger does not exist", logger_name); - SPDLOG_LOGGER_ERROR(log_v2::core(), err_detail); + SPDLOG_LOGGER_ERROR(log_v2::instance().get(log_v2::CORE), err_detail); return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, err_detail); } else { logger->set_level(spdlog::level::level_enum(request->level())); @@ -357,18 +363,7 @@ grpc::Status broker_impl::SetLogFlushPeriod(grpc::ServerContext* context [[maybe_unused]], const LogFlushPeriod* request, ::google::protobuf::Empty*) { - bool done = false; - spdlog::apply_all([&](const std::shared_ptr logger) { - if (!done) { - std::shared_ptr logger_base = - std::dynamic_pointer_cast( - logger); - if (logger_base) { - logger_base->get_parent()->set_flush_interval(request->period()); - done = true; - } - } - }); + log_v2::instance().set_flush_interval(request->period()); return grpc::Status::OK; } @@ -381,14 +376,15 @@ grpc::Status broker_impl::SetLogFlushPeriod(grpc::ServerContext* context * @return ::grpc::Status */ ::grpc::Status broker_impl::GetProcessStats( - ::grpc::ServerContext* context, - const ::google::protobuf::Empty* request, + ::grpc::ServerContext* context [[maybe_unused]], + const ::google::protobuf::Empty* request [[maybe_unused]], ::com::centreon::common::pb_process_stat* response) { try { com::centreon::common::process_stat stat(getpid()); stat.to_protobuff(*response); } catch (const boost::exception& e) { - SPDLOG_LOGGER_ERROR(log_v2::core(), "fail to get process info: {}", + SPDLOG_LOGGER_ERROR(log_v2::instance().get(log_v2::CORE), + "fail to get process info: {}", boost::diagnostic_information(e)); return grpc::Status(grpc::StatusCode::INTERNAL, diff --git a/broker/core/src/cache/global_cache.cc b/broker/core/src/cache/global_cache.cc index ccb789de107..17b1bd52f18 100644 --- a/broker/core/src/cache/global_cache.cc +++ b/broker/core/src/cache/global_cache.cc @@ -1,23 +1,22 @@ /** -* Copyright 2023 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2023-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/cache/global_cache_data.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon::broker; @@ -35,8 +34,9 @@ inline std::string operator+(const std::string& left, std::shared_ptr global_cache::_instance; -global_cache::global_cache(const std::string& file_path) - : _file_size(0), _file_path(file_path) {} +global_cache::global_cache(const std::string& file_path, + const std::shared_ptr& logger) + : _file_size(0), _file_path(file_path), _logger{logger} {} global_cache::~global_cache() { if (_file) { @@ -62,13 +62,12 @@ void global_cache::_open(size_t initial_size_on_create, const void* address) { if (dirty && !*dirty) { // dirty will be erased by destructor *dirty = true; - SPDLOG_LOGGER_INFO(log_v2::core(), "global_cache open file {}", - _file_path); + SPDLOG_LOGGER_INFO(_logger, "global_cache open file {}", _file_path); this->managed_map(false); return; } else { SPDLOG_LOGGER_ERROR( - log_v2::core(), + _logger, "global_cache dirty flag not reset => erase file and recreate"); } } @@ -77,7 +76,7 @@ void global_cache::_open(size_t initial_size_on_create, const void* address) { fmt::format("corrupted cache file {} => recreate {}", _file_path, boost::diagnostic_information(e)); - SPDLOG_LOGGER_ERROR(log_v2::core(), err_detail); + SPDLOG_LOGGER_ERROR(_logger, err_detail); _file.reset(); _file_size = 0; ::remove(_file_path.c_str()); @@ -85,14 +84,13 @@ void global_cache::_open(size_t initial_size_on_create, const void* address) { std::string err_detail = fmt::format( "corrupted cache file {} => recreate {}", _file_path, e.what()); - SPDLOG_LOGGER_ERROR(log_v2::core(), err_detail); + SPDLOG_LOGGER_ERROR(_logger, err_detail); _file.reset(); _file_size = 0; ::remove(_file_path.c_str()); } - SPDLOG_LOGGER_INFO(log_v2::core(), "global_cache create file {}", - _file_path); + SPDLOG_LOGGER_INFO(_logger, "global_cache create file {}", _file_path); ::remove(_file_path.c_str()); _grow(initial_size_on_create); @@ -100,7 +98,7 @@ void global_cache::_open(size_t initial_size_on_create, const void* address) { try { this->managed_map(true); } catch (const boost::interprocess::bad_alloc& e) { - SPDLOG_LOGGER_ERROR(log_v2::core(), + SPDLOG_LOGGER_ERROR(_logger, "allocation error: {}, too small initial file size?", boost::diagnostic_information(e)); throw; @@ -122,8 +120,8 @@ void global_cache::_grow(size_t new_size, void* address) { if (new_size <= _file_size) { return; } - SPDLOG_LOGGER_DEBUG(log_v2::core(), "resize file {} from {} to {}", - _file_path, _file_size, new_size); + SPDLOG_LOGGER_DEBUG(_logger, "resize file {} from {} to {}", _file_path, + _file_size, new_size); size_t old_size = 0; if (_file) { _file->flush(); @@ -139,7 +137,7 @@ void global_cache::_grow(size_t new_size, void* address) { // file doesn't exist if (stat(_file_path.c_str(), &exist) || !S_ISREG(exist.st_mode)) { ::remove(_file_path.c_str()); - SPDLOG_LOGGER_DEBUG(log_v2::core(), + SPDLOG_LOGGER_DEBUG(_logger, "file {} removed or not a file => remove and create", _file_path); _file = std::make_unique( @@ -154,7 +152,7 @@ void global_cache::_grow(size_t new_size, void* address) { } catch (const std::exception& e) { std::string err_msg = fmt::format("fail to map file {} to size {} : {}", _file_path, new_size, e.what()); - SPDLOG_LOGGER_ERROR(log_v2::core(), err_msg); + SPDLOG_LOGGER_ERROR(_logger, err_msg); _file.reset(); _file_size = 0; throw msg_fmt(err_msg); diff --git a/broker/core/src/cache/global_cache_data.cc b/broker/core/src/cache/global_cache_data.cc index 876f064069f..ecd8f2af7c8 100644 --- a/broker/core/src/cache/global_cache_data.cc +++ b/broker/core/src/cache/global_cache_data.cc @@ -17,7 +17,6 @@ */ #include "com/centreon/broker/cache/global_cache_data.hh" -#include "com/centreon/broker/log_v2.hh" using namespace com::centreon::broker::cache; @@ -92,7 +91,7 @@ void global_cache_data::set_metric_info(uint64_t metric_id, _metric_info->emplace(metric_id, to_add); } } catch (const interprocess::bad_alloc& e) { - SPDLOG_LOGGER_DEBUG(log_v2::core(), "file full => grow"); + SPDLOG_LOGGER_DEBUG(_logger, "file full => grow"); allocation_exception_handler(); set_metric_info(metric_id, index_id, name, unit, min, max); } @@ -122,7 +121,7 @@ void global_cache_data::store_instance(uint64_t instance_id, exist->second.assign(instance_name.data(), instance_name.length()); } } catch (const interprocess::bad_alloc& e) { - SPDLOG_LOGGER_DEBUG(log_v2::core(), "file full => grow"); + SPDLOG_LOGGER_DEBUG(_logger, "file full => grow"); allocation_exception_handler(); store_instance(instance_id, instance_name); } @@ -159,7 +158,7 @@ void global_cache_data::store_host(uint64_t host_id, exist->second.severity_id = severity_id; } } catch (const interprocess::bad_alloc& e) { - SPDLOG_LOGGER_DEBUG(log_v2::core(), "file full => grow"); + SPDLOG_LOGGER_DEBUG(_logger, "file full => grow"); allocation_exception_handler(); store_host(host_id, host_name, resource_id, severity_id); } @@ -203,7 +202,7 @@ void global_cache_data::store_service( } } catch (const interprocess::bad_alloc& e) { - SPDLOG_LOGGER_DEBUG(log_v2::core(), "file full => grow"); + SPDLOG_LOGGER_DEBUG(_logger, "file full => grow"); allocation_exception_handler(); store_service(host_id, service_id, service_description, resource_id, severity_id); @@ -228,7 +227,7 @@ void global_cache_data::set_index_mapping(uint64_t index_id, } _index_id_mapping->emplace(index_id, host_serv_pair(host_id, service_id)); } catch (const interprocess::bad_alloc& e) { - SPDLOG_LOGGER_DEBUG(log_v2::core(), "file full => grow"); + SPDLOG_LOGGER_DEBUG(_logger, "file full => grow"); allocation_exception_handler(); set_index_mapping(index_id, host_id, service_id); } @@ -248,7 +247,7 @@ void global_cache_data::add_host_to_group(uint64_t group, absl::WriterMutexLock l(&_protect); _host_group->emplace(host_group_element{host, group, poller_id}); } catch (const interprocess::bad_alloc& e) { - SPDLOG_LOGGER_DEBUG(log_v2::core(), "file full => grow"); + SPDLOG_LOGGER_DEBUG(_logger, "file full => grow"); allocation_exception_handler(); add_host_to_group(group, host, poller_id); } @@ -301,7 +300,7 @@ void global_cache_data::add_service_to_group(uint64_t group, _service_group->emplace( service_group_element{{host, service}, group, poller_id}); } catch (const interprocess::bad_alloc& e) { - SPDLOG_LOGGER_DEBUG(log_v2::core(), "file full => grow"); + SPDLOG_LOGGER_DEBUG(_logger, "file full => grow"); allocation_exception_handler(); add_service_to_group(group, host, service, poller_id); } @@ -371,7 +370,7 @@ void global_cache_data::add_tag(uint64_t tag_id, } } } catch (const interprocess::bad_alloc& e) { - SPDLOG_LOGGER_DEBUG(log_v2::core(), "file full => grow"); + SPDLOG_LOGGER_DEBUG(_logger, "file full => grow"); allocation_exception_handler(); add_tag(tag_id, tag_name, tag_type, poller_id); } @@ -400,11 +399,11 @@ void global_cache_data::set_host_tag(uint64_t host, try { absl::WriterMutexLock l(&_protect); uint64_t tag_id; - while (tag_id = tag_filler()) { + while ((tag_id = tag_filler())) { _host_tag->insert({host, tag_id}); } } catch (const interprocess::bad_alloc& e) { - SPDLOG_LOGGER_DEBUG(log_v2::core(), "file full => grow"); + SPDLOG_LOGGER_DEBUG(_logger, "file full => grow"); allocation_exception_handler(); set_host_tag(host, std::move(tag_filler)); } @@ -422,11 +421,11 @@ void global_cache_data::set_serv_tag(uint64_t host, try { absl::WriterMutexLock l(&_protect); uint64_t tag_id; - while (tag_id = tag_filler()) { + while ((tag_id = tag_filler())) { _serv_tag->insert({{host, serv}, tag_id}); } } catch (const interprocess::bad_alloc& e) { - SPDLOG_LOGGER_DEBUG(log_v2::core(), "file full => grow"); + SPDLOG_LOGGER_DEBUG(_logger, "file full => grow"); allocation_exception_handler(); set_serv_tag(host, serv, std::move(tag_filler)); } diff --git a/broker/core/src/compression/factory.cc b/broker/core/src/compression/factory.cc index 17a3bd601f2..4d904dc09d3 100644 --- a/broker/core/src/compression/factory.cc +++ b/broker/core/src/compression/factory.cc @@ -1,20 +1,20 @@ /** -* Copyright 2011-2013, 2022 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2013, 2022 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/compression/factory.hh" @@ -23,10 +23,11 @@ #include "com/centreon/broker/compression/opener.hh" #include "com/centreon/broker/compression/stream.hh" #include "com/centreon/broker/config/parser.hh" -#include "com/centreon/broker/log_v2.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::compression; +using log_v2 = com::centreon::common::log_v2::log_v2; /** * Check if an endpoint configuration match the compression layer. @@ -59,9 +60,12 @@ bool factory::has_endpoint(config::endpoint& cfg, io::extension* ext) { if (it == cfg.params.end()) has_compression = false; else if (!absl::SimpleAtob(it->second, &has_compression)) { - log_v2::core()->error( - "TLS: the field 'compression' in endpoint '{}' should be a boolean", - cfg.name); + log_v2::instance() + .get(log_v2::CORE) + ->error( + "TLS: the field 'compression' in endpoint '{}' should be a " + "boolean", + cfg.name); has_compression = false; } @@ -82,10 +86,12 @@ bool factory::has_endpoint(config::endpoint& cfg, io::extension* ext) { if (absl::EqualsIgnoreCase(it->second, "auto")) has_compression = true; else { - log_v2::core()->error( - "TLS: the field 'compression' in endpoint '{}' should be a " - "boolean", - cfg.name); + log_v2::instance() + .get(log_v2::CORE) + ->error( + "TLS: the field 'compression' in endpoint '{}' should be a " + "boolean", + cfg.name); has_compression = false; } } @@ -123,10 +129,13 @@ io::endpoint* factory::new_endpoint( cfg.params.find("compression_level")}; if (it != cfg.params.end()) { if (!absl::SimpleAtoi(it->second, &level)) { - log_v2::core()->error( - "compression: the 'compression_level' should be an integer and not " - "'{}'", - it->second); + log_v2::instance() + .get(log_v2::CORE) + ->error( + "compression: the 'compression_level' should be an integer and " + "not " + "'{}'", + it->second); level = -1; } } @@ -136,10 +145,12 @@ io::endpoint* factory::new_endpoint( it = cfg.params.find("compression_buffer"); if (it != cfg.params.end()) { if (!absl::SimpleAtoi(it->second, &size)) { - log_v2::core()->error( - "compression: compression_buffer is the size of the compression " - "buffer represented by an integer and not '{}'", - it->second); + log_v2::instance() + .get(log_v2::CORE) + ->error( + "compression: compression_buffer is the size of the compression " + "buffer represented by an integer and not '{}'", + it->second); size = 0; } } diff --git a/broker/core/src/compression/opener.cc b/broker/core/src/compression/opener.cc index de607b712b8..4c1e719293b 100644 --- a/broker/core/src/compression/opener.cc +++ b/broker/core/src/compression/opener.cc @@ -1,20 +1,20 @@ /** -* Copyright 2011-2012, 2021-2022 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2012, 2021-2022 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/compression/opener.hh" #include "com/centreon/broker/compression/stream.hh" @@ -30,7 +30,7 @@ using namespace com::centreon::broker::compression; * the default compression. */ opener::opener(int32_t level, size_t size) - : io::endpoint(false, {}), _level(level), _size(size) {} + : io::endpoint(false, {}, {}), _level(level), _size(size) {} /** * Open a compression stream. diff --git a/broker/core/src/compression/stream.cc b/broker/core/src/compression/stream.cc index 8eb80233af9..3f0b701188e 100644 --- a/broker/core/src/compression/stream.cc +++ b/broker/core/src/compression/stream.cc @@ -1,20 +1,20 @@ /** -* Copyright 2011-2017 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/compression/stream.hh" @@ -25,12 +25,14 @@ #include "com/centreon/broker/exceptions/timeout.hh" #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/io/raw.hh" -#include "com/centreon/broker/log_v2.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::compression; +using log_v2 = com::centreon::common::log_v2::log_v2; + const size_t stream::max_data_size = 100000000u; /** @@ -40,7 +42,11 @@ const size_t stream::max_data_size = 100000000u; * @param[in] size Compression buffer size. */ stream::stream(int level, size_t size) - : io::stream("compression"), _level(level), _shutdown(false), _size(size) {} + : io::stream("compression"), + _level(level), + _shutdown(false), + _size(size), + _logger(log_v2::instance().get(log_v2::CORE)) {} /** * Destructor. @@ -91,26 +97,25 @@ bool stream::read(std::shared_ptr& data, time_t deadline) { unsigned char const* buff((unsigned char const*)_rbuffer.data()); size = static_cast((buff[0] << 24) | (buff[1] << 16) | (buff[2] << 8) | (buff[3])); - log_v2::core()->trace( - "extract size: {} from {:02X} {:02X} {:02X} {:02X}", size, - buff[0], buff[1], buff[2], buff[3]); + _logger->trace("extract size: {} from {:02X} {:02X} {:02X} {:02X}", + size, buff[0], buff[1], buff[2], buff[3]); } // Check if size is within bounds. if (size <= 0 || size > max_data_size) { // Skip corrupted data, one byte at a time. - log_v2::core()->error( + _logger->error( "compression: stream got corrupted packet size of {} bytes, not " "in " "the 0-{} range, skipping next byte", size, max_data_size); if (!skipped) - log_v2::core()->error( - "compression: peer {} is sending corrupted data", peer()); + _logger->error("compression: peer {} is sending corrupted data", + peer()); ++skipped; _rbuffer.pop(1); } else { - log_v2::core()->trace("compression: reading {} bytes", size); + _logger->trace("compression: reading {} bytes", size); corrupted = false; } } @@ -130,31 +135,30 @@ bool stream::read(std::shared_ptr& data, time_t deadline) { (_rbuffer.data() + sizeof(int32_t))), size); } catch (exceptions::corruption const& e) { - log_v2::core()->debug("corrupted data: {}", e.what()); + _logger->debug("corrupted data: {}", e.what()); } } if (!r->size()) { // No data or uncompressed size of 0 means corrupted // input. - log_v2::core()->error( + _logger->error( "compression: stream got corrupted compressed data, skipping next " "byte"); if (!skipped) - log_v2::core()->error( - "compression: peer {} is sending corrupted data", peer()); + _logger->error("compression: peer {} is sending corrupted data", + peer()); ++skipped; _rbuffer.pop(1); corrupted = true; } else { - log_v2::core()->debug( - "compression: stream uncompressed {} bytes to {} bytes", - size + sizeof(int32_t), r->size()); + _logger->debug("compression: stream uncompressed {} bytes to {} bytes", + size + sizeof(int32_t), r->size()); data = r; _rbuffer.pop(size + sizeof(int32_t)); corrupted = false; } } if (skipped) - log_v2::core()->info( + _logger->info( "compression: peer {} sent {} corrupted compressed bytes, resuming " "processing", peer(), skipped); @@ -239,7 +243,7 @@ int stream::write(std::shared_ptr const& d) { "this error to Centreon Broker developers", max_data_size); else if (r.size() > 0) { - log_v2::core()->trace("compression: writing {} bytes", r.size()); + _logger->trace("compression: writing {} bytes", r.size()); // Append data to write buffer. std::copy(r.get_buffer().begin(), r.get_buffer().end(), std::back_inserter(_wbuffer)); @@ -266,7 +270,7 @@ void stream::_flush() { auto compressed{std::make_shared()}; std::vector& data(compressed->get_buffer()); data = zlib::compress(_wbuffer, _level); - log_v2::core()->debug( + _logger->debug( "compression: stream compressed {} bytes to {} bytes (level {})", _wbuffer.size(), compressed->size(), _level); _wbuffer.clear(); diff --git a/broker/core/src/compression/zlib.cc b/broker/core/src/compression/zlib.cc index b5ab78e3c16..2b60a9746fa 100644 --- a/broker/core/src/compression/zlib.cc +++ b/broker/core/src/compression/zlib.cc @@ -1,30 +1,31 @@ /** -* Copyright 2011-2017 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/compression/zlib.hh" #include #include "com/centreon/broker/compression/stream.hh" #include "com/centreon/broker/exceptions/corruption.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker::compression; +using log_v2 = com::centreon::common::log_v2::log_v2; /** * Compression function @@ -84,7 +85,9 @@ std::vector zlib::compress(std::vector const& data, */ std::vector zlib::uncompress(unsigned char const* data, uLong nbytes) { if (!data) { - log_v2::core()->debug("compression: attempting to uncompress null buffer"); + log_v2::instance() + .get(log_v2::CORE) + ->debug("compression: attempting to uncompress null buffer"); return std::vector(); } if (nbytes <= 4) { diff --git a/broker/core/src/config/applier/endpoint.cc b/broker/core/src/config/applier/endpoint.cc index ccff0c017a3..60edff28267 100644 --- a/broker/core/src/config/applier/endpoint.cc +++ b/broker/core/src/config/applier/endpoint.cc @@ -1,20 +1,20 @@ /** -* Copyright 2011-2012,2015,2017-2022 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2012,2015,2017-2022 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/config/applier/endpoint.hh" @@ -24,7 +24,6 @@ #include "com/centreon/broker/io/endpoint.hh" #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/io/protocols.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/misc.hh" #include "com/centreon/broker/multiplexing/engine.hh" #include "com/centreon/broker/multiplexing/muxer.hh" @@ -33,11 +32,14 @@ #include "com/centreon/broker/processing/endpoint.hh" #include "com/centreon/broker/processing/failover.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::config::applier; +using log_v2 = com::centreon::common::log_v2::log_v2; + // Class instance. static config::applier::endpoint* gl_endpoint = nullptr; static std::atomic_bool gl_loaded{false}; @@ -45,7 +47,8 @@ static std::atomic_bool gl_loaded{false}; /** * @brief Default constructor. */ -endpoint::endpoint() : _discarding{false} {} +endpoint::endpoint() + : _discarding{false}, _logger{log_v2::instance().get(log_v2::CONFIG)} {} /** * Comparison classes. @@ -99,15 +102,14 @@ endpoint::~endpoint() { */ void endpoint::apply(std::list const& endpoints) { // Log messages. - log_v2::config()->info("endpoint applier: loading configuration"); + _logger->info("endpoint applier: loading configuration"); { std::vector eps; for (auto& ep : endpoints) eps.push_back(ep.name); - log_v2::config()->debug("endpoint applier: {} endpoints to apply: {}", - endpoints.size(), - fmt::format("{}", fmt::join(eps, ", "))); + _logger->debug("endpoint applier: {} endpoints to apply: {}", + endpoints.size(), fmt::format("{}", fmt::join(eps, ", "))); } // Copy endpoint configurations and apply eventual modifications. @@ -127,8 +129,8 @@ void endpoint::apply(std::list const& endpoints) { // resources that might be used by other endpoints. auto it = _endpoints.find(ep); if (it != _endpoints.end()) { - log_v2::config()->debug("endpoint applier: removing old endpoint {}", - it->first.name); + _logger->debug("endpoint applier: removing old endpoint {}", + it->first.name); /* failover::exit() is called. */ it->second->exit(); delete it->second; @@ -139,14 +141,13 @@ void endpoint::apply(std::list const& endpoints) { // Update existing endpoints. for (auto it = _endpoints.begin(), end = _endpoints.end(); it != end; ++it) { - log_v2::config()->debug("endpoint applier: updating endpoint {}", - it->first.name); + _logger->debug("endpoint applier: updating endpoint {}", it->first.name); it->second->update(); } // Debug message. - log_v2::config()->debug("endpoint applier: {} endpoints to create", - endp_to_create.size()); + _logger->debug("endpoint applier: {} endpoints to create", + endp_to_create.size()); // Create new endpoints. for (config::endpoint& ep : endp_to_create) { @@ -155,8 +156,7 @@ void endpoint::apply(std::list const& endpoints) { if (ep.name.empty() || std::find_if(endp_to_create.begin(), endp_to_create.end(), name_match_failover(ep.name)) == endp_to_create.end()) { - log_v2::config()->debug("endpoint applier: creating endpoint {}", - ep.name); + _logger->debug("endpoint applier: creating endpoint {}", ep.name); bool is_acceptor; std::shared_ptr e{_create_endpoint(ep, is_acceptor)}; std::unique_ptr endp; @@ -176,10 +176,12 @@ void endpoint::apply(std::list const& endpoints) { multiplexing::muxer_filter r_filter = parse_filters(ep.read_filters); multiplexing::muxer_filter w_filter = parse_filters(ep.write_filters); if (is_acceptor) { + w_filter -= e->get_stream_forbidden_filter(); + r_filter -= e->get_stream_forbidden_filter(); std::unique_ptr acceptr( std::make_unique(e, ep.name, r_filter, w_filter)); - log_v2::config()->debug( + _logger->debug( "endpoint applier: acceptor '{}' configured with write filters: {} " "and read filters: {}", ep.name, w_filter.get_allowed_categories(), @@ -187,23 +189,35 @@ void endpoint::apply(std::list const& endpoints) { endp.reset(acceptr.release()); } else { // Create muxer and endpoint. - if (e->get_stream_mandatory_filter().is_in(w_filter)) { - w_filter = e->get_stream_mandatory_filter(); - log_v2::config()->debug( - "endpoint applier: filters for endpoint '{}' reduced to the " - "needed ones: {}", - ep.name, misc::dump_filters(w_filter)); - } else if (!e->get_stream_mandatory_filter().allows_all()) { - w_filter = e->get_stream_mandatory_filter(); - log_v2::config()->error( + + /* Are there missing events in the w_filter ? */ + if (!e->get_stream_mandatory_filter().is_in(w_filter)) { + w_filter |= e->get_stream_mandatory_filter(); + _logger->debug( "endpoint applier: The configured write filters for the endpoint " - "'{}' are too restrictive and will be ignored.{} categories are " - "mandatory.", - ep.name, w_filter.get_allowed_categories()); - } else - log_v2::config()->debug( - "endpoint applier: filters {} for endpoint '{}' applied.", - w_filter.get_allowed_categories(), ep.name); + "'{}' are too restrictive. Mandatory categories added to them", + ep.name); + } + /* Are there events in w_filter that are forbidden ? */ + if (w_filter.contains_some_of(e->get_stream_forbidden_filter())) { + w_filter -= e->get_stream_forbidden_filter(); + _logger->error( + "endpoint applier: The configured write filters for the endpoint " + "'{}' contain forbidden filters. These ones are removed", + ep.name); + } + + /* Are there events in r_filter that are forbidden ? */ + if (r_filter.contains_some_of(e->get_stream_forbidden_filter())) { + r_filter -= e->get_stream_forbidden_filter(); + _logger->error( + "endpoint applier: The configured read filters for the endpoint " + "'{}' contain forbidden filters. These ones are removed", + ep.name); + } + _logger->debug( + "endpoint applier: filters {} for endpoint '{}' applied.", + w_filter.get_allowed_categories(), ep.name); auto mux = multiplexing::muxer::create( ep.name, multiplexing::engine::instance_ptr(), r_filter, w_filter, @@ -216,7 +230,7 @@ void endpoint::apply(std::list const& endpoints) { } // Run thread. - log_v2::config()->debug( + _logger->debug( "endpoint applier: endpoint thread {} of '{}' is registered and " "ready to run", static_cast(endp.get()), ep.name); @@ -231,13 +245,13 @@ void endpoint::apply(std::list const& endpoints) { */ void endpoint::_discard() { _discarding = true; - log_v2::config()->debug("endpoint applier: destruction"); + _logger->debug("endpoint applier: destruction"); // wait for failover and feeder to push endloop event ::usleep(processing::idle_microsec_wait_idle_thread_delay + 100000); // Exit threads. { - log_v2::config()->debug("endpoint applier: requesting threads termination"); + _logger->debug("endpoint applier: requesting threads termination"); std::unique_lock lock(_endpointsm); // Send termination requests. @@ -245,9 +259,8 @@ void endpoint::_discard() { for (auto it = _endpoints.begin(); it != _endpoints.end();) { if (it->second->is_feeder()) { it->second->wait_for_all_events_written(5000); - log_v2::config()->trace( - "endpoint applier: send exit signal to endpoint '{}'", - it->second->get_name()); + _logger->trace("endpoint applier: send exit signal to endpoint '{}'", + it->second->get_name()); delete it->second; it = _endpoints.erase(it); } else @@ -257,20 +270,19 @@ void endpoint::_discard() { // Exit threads. { - log_v2::config()->debug("endpoint applier: requesting threads termination"); + _logger->debug("endpoint applier: requesting threads termination"); std::unique_lock lock(_endpointsm); // We continue with failovers for (auto it = _endpoints.begin(); it != _endpoints.end();) { it->second->wait_for_all_events_written(5000); - log_v2::config()->trace( - "endpoint applier: send exit signal on endpoint '{}'", - it->second->get_name()); + _logger->trace("endpoint applier: send exit signal on endpoint '{}'", + it->second->get_name()); delete it->second; it = _endpoints.erase(it); } - log_v2::config()->debug("endpoint applier: all threads are terminated"); + _logger->debug("endpoint applier: all threads are terminated"); } // Stop multiplexing: we must stop the engine after failovers otherwise @@ -278,8 +290,7 @@ void endpoint::_discard() { try { multiplexing::engine::instance_ptr()->stop(); } catch (const std::exception& e) { - log_v2::config()->warn("multiplexing engine stop interrupted: {}", - e.what()); + _logger->warn("multiplexing engine stop interrupted: {}", e.what()); } } @@ -362,8 +373,7 @@ processing::failover* endpoint::_create_failover( std::shared_ptr endp, std::list& l) { // Debug message. - log_v2::config()->info("endpoint applier: creating new failover '{}'", - cfg.name); + _logger->info("endpoint applier: creating new failover '{}'", cfg.name); // Check that failover is configured. std::shared_ptr failovr; @@ -372,7 +382,7 @@ processing::failover* endpoint::_create_failover( std::list::iterator it = std::find_if(l.begin(), l.end(), failover_match_name(front_failover)); if (it == l.end()) - log_v2::config()->error( + _logger->error( "endpoint applier: could not find failover '{}' for endpoint '{}'", front_failover, cfg.name); else { @@ -401,7 +411,7 @@ processing::failover* endpoint::_create_failover( bool is_acceptor{false}; std::shared_ptr endp(_create_endpoint(*it, is_acceptor)); if (is_acceptor) { - log_v2::config()->error( + _logger->error( "endpoint applier: secondary failover '{}' is an acceptor and " "cannot therefore be instantiated for endpoint '{}'", *failover_it, cfg.name); @@ -439,15 +449,21 @@ std::shared_ptr endpoint::_create_endpoint(config::endpoint& cfg, if (it->second.osi_from == 1 && it->second.endpntfactry->has_endpoint(cfg, nullptr)) { std::shared_ptr cache; - if (cfg.cache_enabled) - cache = std::make_shared(fmt::format( - "{}.cache.{}", config::applier::state::instance().cache_dir(), - cfg.name)); + if (cfg.cache_enabled) { + log_v2::logger_id log_id = log_v2::instance().get_id(it->first); + if (log_id == log_v2::LOGGER_SIZE) + log_id = log_v2::CORE; + cache = std::make_shared( + fmt::format("{}.cache.{}", + config::applier::state::instance().cache_dir(), + cfg.name), + log_v2::instance().get(log_id)); + } endp = std::shared_ptr( it->second.endpntfactry->new_endpoint(cfg, is_acceptor, cache)); - log_v2::config()->info(" create endpoint {} for endpoint '{}'", it->first, - cfg.name); + _logger->info(" create endpoint {} for endpoint '{}'", it->first, + cfg.name); level = it->second.osi_to + 1; break; } @@ -468,8 +484,8 @@ std::shared_ptr endpoint::_create_endpoint(config::endpoint& cfg, (it->second.endpntfactry->has_endpoint(cfg, nullptr))) { std::shared_ptr current( it->second.endpntfactry->new_endpoint(cfg, is_acceptor)); - log_v2::config()->info(" create endpoint {} for endpoint '{}'", - it->first, cfg.name); + _logger->info(" create endpoint {} for endpoint '{}'", it->first, + cfg.name); current->from(endp); endp = current; level = it->second.osi_to; @@ -529,7 +545,7 @@ void endpoint::_diff_endpoints( list_it = std::find_if(new_ep.begin(), new_ep.end(), failover_match_name(failover)); if (list_it == new_ep.end()) - log_v2::config()->error( + _logger->error( "endpoint applier: could not find failover '{}' for endpoint " "'{}'", failover, entry.name); @@ -559,9 +575,10 @@ void endpoint::_diff_endpoints( */ multiplexing::muxer_filter endpoint::parse_filters( const std::set& str_filters) { + auto logger = log_v2::instance().get(log_v2::CONFIG); multiplexing::muxer_filter elements({}); std::forward_list applied_filters; - auto fill_elements = [&elements](const std::string& str) -> bool { + auto fill_elements = [&elements, logger](const std::string& str) -> bool { bool retval = false; io::events::events_container const& tmp_elements( io::events::instance().get_matching_events(str)); @@ -569,8 +586,7 @@ multiplexing::muxer_filter endpoint::parse_filters( it = tmp_elements.cbegin(), end = tmp_elements.cend(); it != end; ++it) { - log_v2::config()->trace("endpoint applier: new filtering element: {}", - it->first); + logger->trace("endpoint applier: new filtering element: {}", it->first); elements.insert(it->first); retval = true; } @@ -586,9 +602,8 @@ multiplexing::muxer_filter endpoint::parse_filters( try { ok = fill_elements(str); } catch (const std::exception& e) { - log_v2::config()->error( - "endpoint applier: '{}' is not a known category: {}", str, - e.what()); + logger->error("endpoint applier: '{}' is not a known category: {}", str, + e.what()); } if (ok) applied_filters.emplace_front(str); @@ -598,7 +613,7 @@ multiplexing::muxer_filter endpoint::parse_filters( applied_filters.emplace_front("all"); } } - log_v2::config()->info("Filters applied on endpoint:{}", - fmt::join(applied_filters, ", ")); + logger->info("Filters applied on endpoint:{}", + fmt::join(applied_filters, ", ")); return elements; } diff --git a/broker/core/src/config/applier/init.cc b/broker/core/src/config/applier/init.cc index ff6bdcaa6c9..cb99e7c2120 100644 --- a/broker/core/src/config/applier/init.cc +++ b/broker/core/src/config/applier/init.cc @@ -1,5 +1,5 @@ /** - * Copyright 2011-2013, 2021-2022 Centreon + * Copyright 2011-2013, 2021-2024 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,13 +40,14 @@ namespace asio = boost::asio; #include "com/centreon/broker/file/disk_accessor.hh" #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/io/protocols.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/multiplexing/engine.hh" #include "com/centreon/broker/sql/mysql_manager.hh" #include "com/centreon/broker/time/timezone_manager.hh" #include "com/centreon/common/pool.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; +using com::centreon::common::log_v2::log_v2; std::atomic config::applier::mode{not_started}; @@ -60,7 +61,17 @@ std::atomic config::applier::mode{not_started}; void config::applier::init(size_t n_thread, const std::string&, size_t event_queues_total_size) { - // Load singletons. + /* Load singletons. + * Why so many? + * The stats::center is now embedded by each user. We could avoid the + * singleton but as the pool is going to move to common, I don't have a view + * on the impact of this change, so I prefer to keep it as a singleton but + * starting the job to embed the center. + * For the multipliexing::engine, we have a similar issue. Muxers embed the + * engine, so we could avoid the singleton, but it is possible to access the + * engine from stream thanks to the singleton. As this functionality is still + * used, we must keep the singleton. + */ com::centreon::common::pool::set_pool_size(n_thread); stats::center::load(); mysql_manager::load(); @@ -78,6 +89,8 @@ void config::applier::init(size_t n_thread, */ void config::applier::deinit() { mode = finished; + auto logger = log_v2::instance().get(log_v2::CORE); + logger->info("unloading applier::endpoint"); config::applier::endpoint::unload(); { auto eng = multiplexing::engine::instance_ptr(); @@ -89,9 +102,8 @@ void config::applier::deinit() { io::events::unload(); io::protocols::unload(); mysql_manager::unload(); - stats::center::unload(); file::disk_accessor::unload(); - + stats::center::unload(); } /** diff --git a/broker/core/src/config/applier/modules.cc b/broker/core/src/config/applier/modules.cc index 50e65f44e03..91352f7e2a0 100644 --- a/broker/core/src/config/applier/modules.cc +++ b/broker/core/src/config/applier/modules.cc @@ -1,32 +1,34 @@ /** -* Copyright 2011-2013, 2021 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2013, 2021-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/config/applier/modules.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/filesystem.hh" #include "com/centreon/broker/modules/handle.hh" #include "com/centreon/broker/multiplexing/engine.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker::config::applier; +using log_v2 = com::centreon::common::log_v2::log_v2; + /** * Apply a module configuration. * @@ -39,10 +41,9 @@ void modules::apply(const std::list& module_list, const void* arg) { // Load modules. for (const std::string& m : module_list) { - log_v2::config()->info("module applier: loading module '{}'", m); + _logger->info("module applier: loading module '{}'", m); if (!load_file(fmt::format("{}/{}", module_dir, m), arg)) - log_v2::config()->error("module applier: impossible to load module '{}'", - m); + _logger->error("module applier: impossible to load module '{}'", m); } } @@ -92,13 +93,13 @@ bool modules::_check_module(const std::string& name, void* h) noexcept { return false; // Find init symbol. - log_v2::core()->debug( + _logger->debug( "modules: checking initialization routine (symbol '{}') in '{}'", handle::initialization, name); void* init = dlsym(h, handle::initialization); if (!init) { - log_v2::core()->error( + _logger->error( "modules: could not find initialization routine in '{}' (not a " "Centreon Broker module ?): {}", name, dlerror()); @@ -106,13 +107,13 @@ bool modules::_check_module(const std::string& name, void* h) noexcept { } // Find deinit symbol. - log_v2::core()->debug( + _logger->debug( "modules: checking deinitialization routine (symbol '{}') in '{}'", handle::deinitialization, name); void* deinit = dlsym(h, handle::deinitialization); if (!deinit) { - log_v2::core()->error( + _logger->error( "modules: could not find deinitialization routine in '{}' (not a " "Centreon Broker module ?): {}", name, dlerror()); @@ -120,22 +121,21 @@ bool modules::_check_module(const std::string& name, void* h) noexcept { } // Find version symbol. - log_v2::core()->debug( - "modules: checking module version (symbol '{}') in '{}'", - handle::versionning, name); + _logger->debug("modules: checking module version (symbol '{}') in '{}'", + handle::versionning, name); const char** version = (const char**)dlsym(h, handle::versionning); // Could not find version symbol. if (!version) { - log_v2::core()->error( + _logger->error( "modules: could not find version in '{}' (not a Centreon Broker module " "?): {}", name, dlerror()); return false; } if (!*version) { - log_v2::core()->error( + _logger->error( "modules: version symbol of module '{}' is empty (not a Centreon " "Broker module ?)", name); @@ -145,7 +145,7 @@ bool modules::_check_module(const std::string& name, void* h) noexcept { // Check version. if (::strncmp(CENTREON_BROKER_VERSION, *version, strlen(CENTREON_BROKER_VERSION) + 1) != 0) { - log_v2::core()->error( + _logger->error( "modules: version mismatch in '{}': expected '{}', found '{}'", name, CENTREON_BROKER_VERSION, *version); return false; @@ -164,11 +164,11 @@ bool modules::_check_module(const std::string& name, void* h) noexcept { bool modules::load_file(const std::string& filename, const void* arg) { auto found = _handles.find(filename); if (found == _handles.end()) { - log_v2::core()->info("modules: attempt to load module '{}'", filename); + _logger->info("modules: attempt to load module '{}'", filename); void* h = dlopen(filename.c_str(), RTLD_LAZY | RTLD_GLOBAL); if (!h) - log_v2::config()->error("modules: could not load module '{}': {}", - filename, dlerror()); + _logger->error("modules: could not load module '{}': {}", filename, + dlerror()); if (_check_module(filename, h)) { void* parents = dlsym(h, handle::parents_list); @@ -189,8 +189,8 @@ bool modules::load_file(const std::string& filename, const void* arg) { auto found = _handles.find(*p); if (found == _handles.end()) if (!load_file(fmt::format("{}/{}", path, *p), arg)) - log_v2::config()->error( - "modules: impossible to load parent module '{}'", *p); + _logger->error("modules: impossible to load parent module '{}'", + *p); } } } else { @@ -200,8 +200,8 @@ bool modules::load_file(const std::string& filename, const void* arg) { } _handles.emplace(filename, std::make_unique(filename, h, arg)); } else { - log_v2::core()->info( - "modules: attempt to load '{}' which is already loaded", filename); + _logger->info("modules: attempt to load '{}' which is already loaded", + filename); found->second->update(arg); } return true; diff --git a/broker/core/src/config/applier/state.cc b/broker/core/src/config/applier/state.cc index 3805ea74048..4af76911d21 100644 --- a/broker/core/src/config/applier/state.cc +++ b/broker/core/src/config/applier/state.cc @@ -1,35 +1,37 @@ /** -* Copyright 2011-2013,2015-2016, 2020-2021 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2013,2015-2016, 2020-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/config/applier/state.hh" #include "com/centreon/broker/config/applier/endpoint.hh" #include "com/centreon/broker/instance_broadcast.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/multiplexing/engine.hh" #include "com/centreon/broker/multiplexing/muxer.hh" #include "com/centreon/broker/vars.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::config::applier; +using log_v2 = com::centreon::common::log_v2::log_v2; + // Class instance. static state* gl_state = nullptr; @@ -44,7 +46,11 @@ state::stats state::_stats_conf; /** * Default constructor. */ -state::state() : _poller_id(0), _rpc_port(0), _bbdo_version{2u, 0u, 0u} {} +state::state(const std::shared_ptr& logger) + : _poller_id(0), + _rpc_port(0), + _bbdo_version{2u, 0u, 0u}, + _modules{logger} {} /** * Apply a configuration state. @@ -53,6 +59,8 @@ state::state() : _poller_id(0), _rpc_port(0), _bbdo_version{2u, 0u, 0u} {} * @param[in] run_mux Set to true if multiplexing must be run. */ void state::apply(const com::centreon::broker::config::state& s, bool run_mux) { + auto logger = log_v2::instance().get(log_v2::CONFIG); + /* With bbdo 3.0, unified_sql must replace sql/storage */ if (s.get_bbdo_version().major_v >= 3) { auto& lst = s.module_list(); @@ -61,7 +69,7 @@ void state::apply(const com::centreon::broker::config::state& s, bool run_mux) { bool found_storage = std::find(lst.begin(), lst.end(), "20-storage.so") != lst.end(); if (found_sql || found_storage) { - log_v2::config()->error( + logger->error( "Configuration check error: bbdo versions >= 3.0.0 need the " "unified_sql module to be configured."); throw msg_fmt( @@ -120,9 +128,9 @@ void state::apply(const com::centreon::broker::config::state& s, bool run_mux) { else { uint32_t module_count = _modules.size(); if (module_count) - log_v2::config()->info("applier: {} modules loaded", module_count); + logger->info("applier: {} modules loaded", module_count); else - log_v2::config()->info( + logger->info( "applier: no module loaded, you might want to check the " "'module_directory' directory"); } @@ -182,7 +190,7 @@ state& state::instance() { */ void state::load() { if (!gl_state) - gl_state = new state; + gl_state = new state(log_v2::instance().get(log_v2::CONFIG)); } /** @@ -250,15 +258,15 @@ const config::applier::state::stats& state::stats_conf() { */ void state::add_poller(uint64_t poller_id, const std::string& poller_name) { std::lock_guard lck(_connected_pollers_m); + auto logger = log_v2::instance().get(log_v2::CORE); auto found = _connected_pollers.find(poller_id); if (found == _connected_pollers.end()) { - log_v2::core()->info("Poller '{}' with id {} connected", poller_name, - poller_id); + logger->info("Poller '{}' with id {} connected", poller_name, poller_id); _connected_pollers[poller_id] = poller_name; } else { - log_v2::core()->warn( - "Poller '{}' with id {} already known as connected. Replacing it with " - "'{}'", + logger->warn( + "Poller '{}' with id {} already known as connected. Replacing it " + "with '{}'", _connected_pollers[poller_id], poller_id, poller_name); found->second = poller_name; } @@ -271,13 +279,13 @@ void state::add_poller(uint64_t poller_id, const std::string& poller_name) { */ void state::remove_poller(uint64_t poller_id) { std::lock_guard lck(_connected_pollers_m); + auto logger = log_v2::instance().get(log_v2::CORE); auto found = _connected_pollers.find(poller_id); if (found == _connected_pollers.end()) - log_v2::core()->warn("There is currently no poller {} connected", - poller_id); + logger->warn("There is currently no poller {} connected", poller_id); else { - log_v2::core()->info("Poller '{}' with id {} just disconnected", - _connected_pollers[poller_id], poller_id); + logger->info("Poller '{}' with id {} just disconnected", + _connected_pollers[poller_id], poller_id); _connected_pollers.erase(found); } } diff --git a/broker/core/src/config/endpoint.cc b/broker/core/src/config/endpoint.cc index eaab7df2f8b..05fc64535dd 100644 --- a/broker/core/src/config/endpoint.cc +++ b/broker/core/src/config/endpoint.cc @@ -1,23 +1,22 @@ /** -* Copyright 2009-2013,2020-2021 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2009-2013,2020-2021 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/config/endpoint.hh" -#include "com/centreon/broker/log_v2.hh" using namespace com::centreon::broker::config; diff --git a/broker/core/src/config/parser.cc b/broker/core/src/config/parser.cc index 55d46e09cd2..298feb98abf 100644 --- a/broker/core/src/config/parser.cc +++ b/broker/core/src/config/parser.cc @@ -1,20 +1,20 @@ /** -* Copyright 2011-2013,2015,2017-2023 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2013,2015,2017-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/config/parser.hh" @@ -25,8 +25,8 @@ #include #include "com/centreon/broker/exceptions/deprecated.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/filesystem.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; @@ -35,6 +35,7 @@ using namespace nlohmann; using msg_fmt = com::centreon::exceptions::msg_fmt; using deprecated = com::centreon::broker::exceptions::deprecated; +using log_v2 = com::centreon::common::log_v2::log_v2; template static bool get_conf(std::pair const& obj, @@ -155,6 +156,7 @@ state parser::parse(std::string const& file) { state retval; // Parse JSON document. std::ifstream f(file); + auto logger_config = log_v2::instance().get(log_v2::CONFIG); if (f.fail()) throw msg_fmt("Config parser: Cannot read file '{}': {}", file, @@ -288,7 +290,7 @@ state parser::parse(std::string const& file) { retval.add_module(std::move(module)); retval.add_endpoint(std::move(out)); } catch (const deprecated& e) { - log_v2::config()->warn( + logger_config->warn( "Deprecated endpoint found in the output configuration: {}", e.what()); } @@ -302,7 +304,7 @@ state parser::parse(std::string const& file) { retval.add_module(std::move(module)); retval.add_endpoint(std::move(out)); } catch (const deprecated& e) { - log_v2::config()->warn( + logger_config->warn( "Deprecated endpoint found in the output configuration: {}", e.what()); } @@ -322,7 +324,7 @@ state parser::parse(std::string const& file) { retval.add_module(std::move(module)); retval.add_endpoint(std::move(in)); } catch (const deprecated& e) { - log_v2::config()->warn( + logger_config->warn( "Deprecated endpoint found in the input configuration: {}", e.what()); } @@ -335,7 +337,7 @@ state parser::parse(std::string const& file) { retval.add_module(std::move(module)); retval.add_endpoint(std::move(in)); } catch (const deprecated& e) { - log_v2::config()->warn( + logger_config->warn( "Deprecated endpoint found in the input configuration: {}", e.what()); } @@ -356,24 +358,24 @@ state parser::parse(std::string const& file) { auto& conf = retval.mut_log_conf(); if (conf_js.contains("directory") && conf_js["directory"].is_string()) - conf.directory = conf_js["directory"].get(); + conf.set_dirname(conf_js["directory"].get()); else if (conf_js.contains("directory") && !conf_js["directory"].is_null()) throw msg_fmt( "'directory' key in the log configuration must contain a " "directory name"); - if (conf.directory.empty()) - conf.directory = "/var/log/centreon-broker"; + if (conf.dirname().empty()) + conf.set_dirname("/var/log/centreon-broker"); - if (!misc::filesystem::writable(conf.directory)) + if (!misc::filesystem::writable(conf.dirname())) throw msg_fmt("The log directory '{}' is not writable", - conf.directory); + conf.dirname()); - conf.filename = ""; + conf.set_filename(""); if (conf_js.contains("filename") && conf_js["filename"].is_string()) { - conf.filename = conf_js["filename"].get(); - if (conf.filename.find("/") != std::string::npos) + conf.set_filename(conf_js["filename"].get()); + if (conf.filename().find("/") != std::string::npos) throw msg_fmt( "'filename' must only contain a filename without directory"); @@ -384,7 +386,7 @@ state parser::parse(std::string const& file) { "file name"); auto ms = check_and_read(conf_js, "max_size"); - conf.max_size = ms ? ms.value() : 0u; + conf.set_max_size(ms ? ms.value() : 0u); auto fp = check_and_read(conf_js, "flush_period"); if (fp) { @@ -393,31 +395,31 @@ state parser::parse(std::string const& file) { "'flush_period' key in the log configuration must contain a " "positive number or 0."); - conf.flush_period = fp.value(); + conf.set_flush_interval(fp.value()); } else - conf.flush_period = 0u; + conf.set_flush_interval(0u); auto lp = check_and_read(conf_js, "log_pid"); - conf.log_pid = lp ? lp.value() : false; + conf.set_log_pid(lp ? lp.value() : false); auto ls = check_and_read(conf_js, "log_source"); - conf.log_source = ls ? ls.value() : false; + conf.set_log_source(ls ? ls.value() : false); if (conf_js.contains("loggers") && conf_js["loggers"].is_object()) { - conf.loggers.clear(); + conf.loggers().clear(); for (auto it = conf_js["loggers"].begin(); it != conf_js["loggers"].end(); ++it) { - if (!log_v2::contains_logger(it.key())) + if (!log_v2::instance().contains_logger(it.key())) throw msg_fmt("'{}' is not available as logger", it.key()); - if (!it.value().is_string() || - !log_v2::contains_level(it.value().get())) + if (!it.value().is_string() || !log_v2::instance().contains_level( + it.value().get())) throw msg_fmt( "The logger '{}' must contain a string among 'trace', " "'debug', 'info', 'warning', 'error', 'critical', " "'disabled'", it.key()); - conf.loggers.emplace(it.key(), it.value().get()); + conf.set_level(it.key(), it.value().get()); } } } else if (it.key() == "stats_exporter") { @@ -480,11 +482,11 @@ state parser::parse(std::string const& file) { } retval.add_module("15-stats_exporter.so"); } else - log_v2::config()->warn( + logger_config->warn( "config parser: no exporters defined in the stats_exporter " "configuration"); } else if (it.key() == "logger") { - log_v2::config()->warn("logger object is deprecated on 21.10"); + logger_config->warn("logger object is deprecated on 21.10"); } else { if (it.key() == "stats") retval.add_module("15-stats.so"); @@ -500,8 +502,8 @@ state parser::parse(std::string const& file) { /* Post configuration */ auto& conf = retval.mut_log_conf(); - if (conf.filename.empty()) - conf.filename = fmt::format("{}.log", retval.broker_name()); + if (conf.filename().empty()) + conf.set_filename(fmt::format("{}.log", retval.broker_name())); return retval; } @@ -614,9 +616,11 @@ void parser::_parse_endpoint(const json& elem, if (it.value().is_string()) e.params[it.key()] = it.value().get(); else - log_v2::config()->debug( - "config parser (while reading configuration file): " - "for key: '{}' value is not a string.", - it.key()); + log_v2::instance() + .get(log_v2::CONFIG) + ->debug( + "config parser (while reading configuration file): " + "for key: '{}' value is not a string.", + it.key()); } } diff --git a/broker/core/src/config/state.cc b/broker/core/src/config/state.cc index 08b4ca8f0fe..9cbd8c16655 100644 --- a/broker/core/src/config/state.cc +++ b/broker/core/src/config/state.cc @@ -1,30 +1,33 @@ /** -* Copyright 2011-2012,2017, 2021 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2012,2017, 2021 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/config/state.hh" #include "com/centreon/broker/bbdo/internal.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker::config; using namespace com::centreon::exceptions; using namespace com::centreon::broker; +using log_v2 = com::centreon::common::log_v2::log_v2; +using log_v2_config = com::centreon::common::log_v2::config; + /** * Default constructor. */ @@ -36,7 +39,13 @@ state::state() _event_queue_max_size{10000}, _poller_id{0}, _pool_size{0}, - _log_conf{"/var/log/centreon-broker", "", 0u, 5u, false, false, {}} {} + _log_conf{"/var/log/centreon-broker/", + log_v2_config::logger_type::LOGGER_FILE, 5u, false, false} { + // FIXME DBO: Is it useful since the log_conf constructor parse the name to + // create a path + filename. + _log_conf.set_filename(""); + _log_conf.set_max_size(0); +} /** * Copy constructor. @@ -58,7 +67,8 @@ state::state(const state& other) _params(other._params), _poller_id(other._poller_id), _poller_name(other._poller_name), - _pool_size(other._pool_size) {} + _pool_size(other._pool_size), + _log_conf(other._log_conf) {} /** * Destructor. @@ -251,7 +261,9 @@ std::string const& state::command_protocol() const noexcept { * @param out The endpoint is moved to the configuration. */ void state::add_endpoint(endpoint&& out) noexcept { - log_v2::core()->trace("endpoint {} added to state", out.name); + log_v2::instance() + .get(log_v2::CORE) + ->trace("endpoint {} added to state", out.name); _endpoints.emplace_back(std::move(out)); } @@ -445,11 +457,11 @@ const std::string& state::listen_address() const noexcept { return _listen_address; } -state::log& state::mut_log_conf() { +log_v2_config& state::mut_log_conf() { return _log_conf; } -const state::log& state::log_conf() const { +const log_v2_config& state::log_conf() const { return _log_conf; } diff --git a/broker/core/src/file/directory_watcher.cc b/broker/core/src/file/directory_watcher.cc index 64c4d1f074a..18a1d0101c9 100644 --- a/broker/core/src/file/directory_watcher.cc +++ b/broker/core/src/file/directory_watcher.cc @@ -29,12 +29,13 @@ #include #include -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::file; +using log_v2 = com::centreon::common::log_v2::log_v2; /** * Default constructor. @@ -131,6 +132,8 @@ std::vector directory_watcher::get_events() { if (!FD_ISSET(_inotify_instance_id, &set)) return (ret); + auto logger = log_v2::instance().get(log_v2::CORE); + // Get the events int buf_size; if (ioctl(_inotify_instance_id, FIONREAD, &buf_size) == -1) { @@ -138,8 +141,7 @@ std::vector directory_watcher::get_events() { throw msg_fmt("directory_watcher: couldn't read events: '{}'", ::strerror(err)); } - log_v2::core()->debug("file: directory watcher getting events of size {}", - buf_size); + logger->debug("file: directory watcher getting events of size {}", buf_size); char* buf = (char*)alloca(buf_size); int len = ::read(_inotify_instance_id, buf, buf_size); if (len == -1) { @@ -190,8 +192,9 @@ std::vector directory_watcher::get_events() { } ret.push_back(directory_event(name, event_type, ft)); - log_v2::core()->debug( - "file: directory watcher getting an event for path '{}' and type {}", + logger->debug( + "file: directory watcher getting an event for path '{}' and type " + "{}", name, static_cast(event_type)); } diff --git a/broker/core/src/file/disk_accessor.cc b/broker/core/src/file/disk_accessor.cc index 444e0d6a9ea..fc1a7f558ae 100644 --- a/broker/core/src/file/disk_accessor.cc +++ b/broker/core/src/file/disk_accessor.cc @@ -1,25 +1,27 @@ /** -* Copyright 2022 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2022 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/file/disk_accessor.hh" -#include "com/centreon/broker/log_v2.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker::file; +using log_v2 = com::centreon::common::log_v2::log_v2; + disk_accessor* disk_accessor::_instance{nullptr}; /** * @brief Constructor. limit_size is the maximum allowed size for the generated @@ -34,7 +36,7 @@ void disk_accessor::load(size_t limit_size) { if (_instance == nullptr) _instance = new disk_accessor(limit_size); else - log_v2::core()->warn("disk accessor already loaded"); + log_v2::instance().get(log_v2::CORE)->warn("disk accessor already loaded"); } /** @@ -88,10 +90,13 @@ size_t disk_accessor::fwrite(const void* ptr, return ::fwrite(ptr, size, nmemb, stream); } else { errno = ENOSPC; - log_v2::core()->error( - "disk_accessor: the limit size of {} bytes is reached for queue files. " - "New events written to disk are lost", - _limit_size); + log_v2::instance() + .get(log_v2::CORE) + ->error( + "disk_accessor: the limit size of {} bytes is reached for queue " + "files. " + "New events written to disk are lost", + _limit_size); return 0; } } @@ -106,7 +111,7 @@ size_t disk_accessor::fwrite(const void* ptr, * @param nmemb * @param stream * - * @return + * @return */ size_t disk_accessor::fread(void* ptr, size_t size, size_t nmemb, fd stream) { return ::fread(ptr, size, nmemb, stream); @@ -140,7 +145,7 @@ size_t disk_accessor::current_size() const { * @param name * @param mode * - * @return + * @return */ disk_accessor::fd disk_accessor::fopen(const std::string& name, const char* mode) { diff --git a/broker/core/src/file/fifo.cc b/broker/core/src/file/fifo.cc index 88d3890f38a..67ff01a4686 100644 --- a/broker/core/src/file/fifo.cc +++ b/broker/core/src/file/fifo.cc @@ -1,20 +1,20 @@ /** -* Copyright 2011-2013 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2013 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/file/fifo.hh" @@ -25,14 +25,15 @@ #include #include -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" #define BUF_SIZE 4096 * 4 using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::file; +using log_v2 = com::centreon::common::log_v2::log_v2; /** * Fifo constructor. @@ -113,7 +114,9 @@ void fifo::_open_fifo() { // Stat failed, probably because of inexistant file. if (::stat(_path.c_str(), &s) != 0) { char const* msg(strerror(errno)); - log_v2::config()->info("stats: cannot stat() '{}': {}", _path, msg); + log_v2::instance() + .get(log_v2::CONFIG) + ->info("stats: cannot stat() '{}': {}", _path, msg); // Create FIFO. if (::mkfifo(_path.c_str(), diff --git a/broker/core/src/file/opener.cc b/broker/core/src/file/opener.cc index f298acb107a..c2f41df9227 100644 --- a/broker/core/src/file/opener.cc +++ b/broker/core/src/file/opener.cc @@ -1,25 +1,26 @@ /** -* Copyright 2011-2012,2017, 2021 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2012,2017, 2021 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/file/opener.hh" #include "com/centreon/broker/file/splitter.hh" #include "com/centreon/broker/file/stream.hh" +#include "com/centreon/broker/multiplexing/muxer_filter.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::file; @@ -28,7 +29,12 @@ using namespace com::centreon::broker::file; * Constructor. */ opener::opener() - : io::endpoint(false, {}), _auto_delete(true), _max_size(100000000) {} + : io::endpoint( + false, + {}, + multiplexing::muxer_filter(multiplexing::muxer_filter::zero_init())), + _auto_delete(true), + _max_size(100000000) {} /** * Copy constructor. diff --git a/broker/core/src/file/splitter.cc b/broker/core/src/file/splitter.cc index b94868e4792..eb390dfccab 100644 --- a/broker/core/src/file/splitter.cc +++ b/broker/core/src/file/splitter.cc @@ -26,14 +26,16 @@ #include "com/centreon/broker/exceptions/shutdown.hh" #include "com/centreon/broker/file/cfile.hh" #include "com/centreon/broker/file/disk_accessor.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/filesystem.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::file; +using com::centreon::common::log_v2::log_v2; + /** * Build a new splitter. * @@ -157,17 +159,17 @@ long splitter::read(void* buffer, long max_size) { // Seek to current read position. fseek(_rfile.get(), _roffset, SEEK_SET); + auto logger = log_v2::instance().get(log_v2::BBDO); // Read data. long rb = disk_accessor::instance().fread(buffer, 1, max_size, _rfile.get()); std::string file_path(get_file_path(_rid)); - log_v2::bbdo()->debug("splitter: read {} bytes at offset {} from '{}'", rb, - _roffset, file_path); + logger->debug("splitter: read {} bytes at offset {} from '{}'", rb, _roffset, + file_path); _roffset += rb; if (rb == 0) { if (feof(_rfile.get())) { if (_auto_delete) { - log_v2::bbdo()->info("file: end of file '{}' reached, erasing it", - file_path); + logger->info("file: end of file '{}' reached, erasing it", file_path); /* Here we have to really verify that _wfile and _rfile are the same, * and then we close files before removing them. */ if (lck.owns_lock() && _wfile == _rfile) { @@ -235,11 +237,11 @@ long splitter::write(void const* buffer, long size) { if (!_open_write_file()) return 0; + auto logger = log_v2::instance().get(log_v2::BBDO); // Open next write file is max file size is reached. if ((_woffset + size) > _max_file_size) { if (fflush(_wfile.get())) { - log_v2::bbdo()->error("splitter: cannot flush file '{}'", - get_file_path(_wid)); + logger->error("splitter: cannot flush file '{}'", get_file_path(_wid)); char msg[1024]; throw msg_fmt("cannot flush file '{}': {}", get_file_path(_wid), strerror_r(errno, msg, sizeof(msg))); @@ -253,16 +255,16 @@ long splitter::write(void const* buffer, long size) { fseek(_wfile.get(), _woffset, SEEK_SET); // Debug message. - log_v2::bbdo()->debug("file: write request of {} bytes for '{}'", size, - get_file_path(_wid)); + logger->debug("file: write request of {} bytes for '{}'", size, + get_file_path(_wid)); // Write data. long wb = disk_accessor::instance().fwrite(buffer, 1, size, _wfile.get()); if (wb != size) { std::string wfile(get_file_path(_wid)); char msg[1024]; - log_v2::bbdo()->critical("splitter: cannot write to file '{}': {}", wfile, - strerror_r(errno, msg, sizeof(msg))); + logger->critical("splitter: cannot write to file '{}': {}", wfile, + strerror_r(errno, msg, sizeof(msg))); return 0; } _woffset += size; @@ -386,10 +388,11 @@ void splitter::_open_read_file() { if (!done) { std::string fname(get_file_path(_rid)); FILE* f = disk_accessor::instance().fopen(fname, "r+b"); + auto logger = log_v2::instance().get(log_v2::BBDO); if (f) - log_v2::bbdo()->debug("splitter: read open '{}'", fname); + logger->debug("splitter: read open '{}'", fname); else - log_v2::bbdo()->error("splitter: read fail open '{}'", fname); + logger->error("splitter: read fail open '{}'", fname); _rfile = f ? std::shared_ptr(f, fclose) : std::shared_ptr(); } @@ -416,10 +419,11 @@ void splitter::_open_read_file() { bool splitter::_open_write_file() { std::string fname(get_file_path(_wid)); FILE* f = disk_accessor::instance().fopen(fname, "a+b"); + auto logger = log_v2::instance().get(log_v2::BBDO); if (f) - log_v2::bbdo()->debug("splitter: write open '{}'", fname); + logger->debug("splitter: write open '{}'", fname); else - log_v2::bbdo()->error("splitter: write fail open '{}'", fname); + logger->error("splitter: write fail open '{}'", fname); _wfile = f ? std::shared_ptr(f, fclose) : std::shared_ptr(); @@ -446,8 +450,8 @@ bool splitter::_open_write_file() { if (size != sizeof(header)) { std::string wfile(get_file_path(_wid)); char msg[1024]; - log_v2::bbdo()->critical("splitter: cannot write to file '{}': {}", wfile, - strerror_r(errno, msg, sizeof(msg))); + logger->critical("splitter: cannot write to file '{}': {}", wfile, + strerror_r(errno, msg, sizeof(msg))); _wfile.reset(); return false; } diff --git a/broker/core/src/file/stream.cc b/broker/core/src/file/stream.cc index 853a2bbe7ac..8b20a595842 100644 --- a/broker/core/src/file/stream.cc +++ b/broker/core/src/file/stream.cc @@ -1,20 +1,20 @@ /** -* Copyright 2011-2017 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2017-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/file/stream.hh" @@ -22,13 +22,14 @@ #include "broker.pb.h" #include "com/centreon/broker/io/raw.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/math.hh" #include "com/centreon/broker/misc/string.hh" #include "com/centreon/broker/stats/center.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::file; +using log_v2 = com::centreon::common::log_v2::log_v2; static constexpr double eps = 0.000001; @@ -51,7 +52,8 @@ stream::stream(const std::string& path, _last_write_offset(0), _stats_perc{}, _stats_idx{0u}, - _stats_size{0u} {} + _stats_size{0u}, + _center{stats::center::instance_ptr()} {} /** * Get peer name. @@ -195,7 +197,7 @@ void stream::_update_stats() { } if (reg) { - stats::center::instance().execute( + _center->execute( [s = this->_stats, now, wid, woffset, rid, roffset, perc, m, p] { s->set_file_write_path(wid); s->set_file_write_offset(woffset); @@ -224,24 +226,25 @@ void stream::_update_stats() { d = fmt::format("{}s", sec); s->set_file_expected_terminated_in(d); - log_v2::core()->info( - "Retention file will be terminated at {:%Y-%m-%d " - "%H:%M:%S}", - fmt::localtime(terminated)); + log_v2::instance() + .get(log_v2::CORE) + ->info( + "Retention file will be terminated at {:%Y-%m-%d " + "%H:%M:%S}", + fmt::localtime(terminated)); } } else s->set_file_expected_terminated_at( std::numeric_limits::max()); }); } else { - stats::center::instance().execute( - [s = this->_stats, wid, woffset, rid, roffset, perc] { - s->set_file_write_path(wid); - s->set_file_write_offset(woffset); - s->set_file_read_path(rid); - s->set_file_read_offset(roffset); - s->set_file_percent_processed(perc); - }); + _center->execute([s = this->_stats, wid, woffset, rid, roffset, perc] { + s->set_file_write_path(wid); + s->set_file_write_offset(woffset); + s->set_file_read_path(rid); + s->set_file_read_offset(roffset); + s->set_file_percent_processed(perc); + }); } } } diff --git a/broker/core/src/io/endpoint.cc b/broker/core/src/io/endpoint.cc index 4538c5a1198..303152c9e55 100644 --- a/broker/core/src/io/endpoint.cc +++ b/broker/core/src/io/endpoint.cc @@ -1,20 +1,20 @@ /** -* Copyright 2011-2013 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2013, 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/io/endpoint.hh" #include "com/centreon/broker/persistent_cache.hh" @@ -22,12 +22,20 @@ using namespace com::centreon::broker::io; /** - * Default constructor. + * @brief Constructor for an acceptor or a connector, that also gets filters, + * the minimal filter configuration for the endpoint to work and also the list + * of filters that must not make part of it. * - * @param[in] is_accptr True if endpoint is an acceptor. + * @param is_accptr True for an acceptor, false otherwise. + * @param mandatory_filter The filters needed by the endpoint. + * @param forbidden_filter The filters that would break the endpoint. */ -endpoint::endpoint(bool is_accptr, const multiplexing::muxer_filter& filter) - : _is_acceptor(is_accptr), _stream_mandatory_filter{filter} {} +endpoint::endpoint(bool is_accptr, + const multiplexing::muxer_filter& mandatory_filter, + const multiplexing::muxer_filter& forbidden_filter) + : _is_acceptor(is_accptr), + _stream_mandatory_filter{mandatory_filter}, + _stream_forbidden_filter{forbidden_filter} {} /** * Copy constructor. @@ -37,6 +45,7 @@ endpoint::endpoint(bool is_accptr, const multiplexing::muxer_filter& filter) endpoint::endpoint(endpoint const& other) : _is_acceptor(other._is_acceptor), _stream_mandatory_filter{other._stream_mandatory_filter}, + _stream_forbidden_filter{other._stream_forbidden_filter}, _from(other._from) {} /** @@ -45,6 +54,8 @@ endpoint::endpoint(endpoint const& other) * @param[in] endp Lower layer endpoint object. */ void endpoint::from(std::shared_ptr endp) { + _stream_mandatory_filter |= endp->get_stream_mandatory_filter(); + _stream_forbidden_filter |= endp->get_stream_forbidden_filter(); _from = endp; } diff --git a/broker/core/src/io/factory.cc b/broker/core/src/io/factory.cc index 74bc320a0eb..31a1f033212 100644 --- a/broker/core/src/io/factory.cc +++ b/broker/core/src/io/factory.cc @@ -1,26 +1,25 @@ /** -* Copyright 2011-2013,2017 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2013,2017 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include #include "com/centreon/broker/config/applier/state.hh" #include "com/centreon/broker/io/factory.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon::exceptions; @@ -63,4 +62,4 @@ bool factory::direct_grpc_serialized(const config::endpoint& cfg) { } } return false; -} \ No newline at end of file +} diff --git a/broker/core/src/io/protocols.cc b/broker/core/src/io/protocols.cc index ba846ce4619..ea94af921af 100644 --- a/broker/core/src/io/protocols.cc +++ b/broker/core/src/io/protocols.cc @@ -1,28 +1,29 @@ /** -* Copyright 2011-2012, 2021 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2012, 2021 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/io/protocols.hh" #include #include "com/centreon/broker/compression/factory.hh" #include "com/centreon/broker/file/factory.hh" -#include "com/centreon/broker/log_v2.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker::io; +using log_v2 = com::centreon::common::log_v2::log_v2; // Class instance. static protocols* gl_protocols = nullptr; @@ -93,8 +94,10 @@ void protocols::reg(std::string const& name, p.osi_to = osi_to; // Register protocol in protocol list. - log_v2::core()->info("protocols: registering protocol ('{}' (layers {}-{})", - name, osi_from, osi_to); + log_v2::instance() + .get(log_v2::CORE) + ->info("protocols: registering protocol ('{}' (layers {}-{})", name, + osi_from, osi_to); _protocols[name] = p; } @@ -104,7 +107,9 @@ void protocols::reg(std::string const& name, * @param[in] name Protocol name. */ void protocols::unreg(std::string const& name) { - log_v2::core()->info("protocols: unregistering protocol '{}'", name); + log_v2::instance() + .get(log_v2::CORE) + ->info("protocols: unregistering protocol '{}'", name); _protocols.erase(name); } @@ -123,6 +128,8 @@ protocols::protocols() { protocols::~protocols() noexcept { unreg("compression"); unreg("file"); - log_v2::core()->info("protocols: destruction ({} protocols still registered)", - _protocols.size()); + log_v2::instance() + .get(log_v2::CORE) + ->info("protocols: destruction ({} protocols still registered)", + _protocols.size()); } diff --git a/broker/core/src/io/raw.cc b/broker/core/src/io/raw.cc index fd838c13a02..f28dbbcdcae 100644 --- a/broker/core/src/io/raw.cc +++ b/broker/core/src/io/raw.cc @@ -18,8 +18,6 @@ #include "com/centreon/broker/io/raw.hh" -#include "com/centreon/broker/log_v2.hh" - namespace com::centreon::broker::io { std::ostream& operator<<(std::ostream& s, const raw& d) { @@ -71,17 +69,29 @@ raw& raw::operator=(raw const& r) { return *this; } -void raw::resize(size_t s) { _buffer.resize(s); } +void raw::resize(size_t s) { + _buffer.resize(s); +} -char* raw::data() { return &_buffer[0]; } +char* raw::data() { + return &_buffer[0]; +} -char const* raw::const_data() const { return &_buffer[0]; } +char const* raw::const_data() const { + return &_buffer[0]; +} -size_t raw::size() const { return _buffer.size(); } +size_t raw::size() const { + return _buffer.size(); +} -std::vector& raw::get_buffer() { return _buffer; } +std::vector& raw::get_buffer() { + return _buffer; +} -bool raw::empty() const { return _buffer.empty(); } +bool raw::empty() const { + return _buffer.empty(); +} // void raw::append(const char* msg) { // _buffer.insert(_buffer.end(), msg, msg + strlen(msg)); diff --git a/broker/core/src/io/stream.cc b/broker/core/src/io/stream.cc index d3bf0d575b1..387184a2d2a 100644 --- a/broker/core/src/io/stream.cc +++ b/broker/core/src/io/stream.cc @@ -1,26 +1,28 @@ /** -* Copyright 2011-2012,2015,2017, 2021 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2012,2015,2017-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/io/stream.hh" -#include "com/centreon/broker/log_v2.hh" + +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::io; +using log_v2 = com::centreon::common::log_v2::log_v2; /** * @brief Constructor. The name is chosen by the developer. This name is @@ -30,16 +32,6 @@ using namespace com::centreon::broker::io; */ stream::stream(const std::string& name) : _name(name) {} -/** - * @brief This method provides a mecanism to stop threads behind the stream and - * to flush pending events. It returns the number of acknowledged events. - * - * @return The number of acknowledged events. - */ -// int32_t stream::stop() { -// return 0; -//} - /** * Flush data. * @@ -97,11 +89,13 @@ void stream::update() {} bool stream::validate(std::shared_ptr const& d, std::string const& error) { if (!d) { - log_v2::core()->error( - "{}: received a null event. This should never happen. " - "This is likely a software bug that you should report " - "to Centreon Broker developers.", - error); + log_v2::instance() + .get(log_v2::CORE) + ->error( + "{}: received a null event. This should never happen. " + "This is likely a software bug that you should report " + "to Centreon Broker developers.", + error); return false; } return true; diff --git a/broker/core/src/log_v2.cc b/broker/core/src/log_v2.cc deleted file mode 100644 index 7f34aed1fa5..00000000000 --- a/broker/core/src/log_v2.cc +++ /dev/null @@ -1,373 +0,0 @@ -/** -* Copyright 2020-2023 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ - -#include "com/centreon/broker/log_v2.hh" - -#include -#include -#include -#include -#include - -#include - -#include "com/centreon/exceptions/msg_fmt.hh" -#include "com/centreon/broker/misc/misc.hh" - -using namespace com::centreon::broker; -using namespace com::centreon::exceptions; -using namespace spdlog; - -/** - * @brief this function is passed to grpc in order to log grpc layer's events to - * logv2 - * - * @param args grpc logging params - */ -static void grpc_logger(gpr_log_func_args* args) { - std::shared_ptr logger = log_v2::grpc(); - spdlog::level::level_enum grpc_level = logger->level(); - const char* start; - if (grpc_level == spdlog::level::off) - return; - else if (grpc_level > spdlog::level::debug) { - start = strstr(args->message, "}: "); - if (!start) - return; - start += 3; - } else - start = args->message; - switch (args->severity) { - case GPR_LOG_SEVERITY_DEBUG: - if (grpc_level == spdlog::level::trace || - grpc_level == spdlog::level::debug) { - SPDLOG_LOGGER_DEBUG(logger, "{} ({}:{})", start, args->file, - args->line); - } - break; - case GPR_LOG_SEVERITY_INFO: - if (grpc_level == spdlog::level::trace || - grpc_level == spdlog::level::debug || - grpc_level == spdlog::level::info) { - if (start) - SPDLOG_LOGGER_INFO(logger, "{}", start); - } - break; - case GPR_LOG_SEVERITY_ERROR: - SPDLOG_LOGGER_ERROR(logger, "{}", start); - break; - } -} - -std::shared_ptr log_v2::_instance; - -void log_v2::load(const std::shared_ptr& io_context) { - if (!_instance) - _instance.reset(new log_v2(io_context)); -} - -std::shared_ptr log_v2::instance() { - return _instance; -} - -log_v2::log_v2(const std::shared_ptr& io_context) - : log_v2_base("broker"), - _running{false}, - _flush_timer(*io_context), - _flush_timer_active(true), - _io_context(io_context) { - DEBUG(fmt::format("CONSTRUCTOR log_v2 {:p}", static_cast(this))); - auto stdout_sink = std::make_shared(); - auto create_logger = [&](const std::string& name) { - std::shared_ptr log = - std::make_shared(name, this, - stdout_sink); - log->flush_on(level::info); - log->set_level(level::info); - spdlog::register_logger(log); - return log; - }; - - _log[log_v2::log_bam] = create_logger("bam"); - _log[log_v2::log_bbdo] = create_logger("bbdo"); - _log[log_v2::log_config] = create_logger("config"); - _log[log_v2::log_core] = create_logger("core"); - _log[log_v2::log_graphite] = create_logger("graphite"); - _log[log_v2::log_notification] = create_logger("notification"); - _log[log_v2::log_rrd] = create_logger("rrd"); - _log[log_v2::log_stats] = create_logger("stats"); - _log[log_v2::log_influxdb] = create_logger("influxdb"); - _log[log_v2::log_lua] = create_logger("lua"); - _log[log_v2::log_neb] = create_logger("neb"); - _log[log_v2::log_perfdata] = create_logger("perfdata"); - _log[log_v2::log_processing] = create_logger("processing"); - _log[log_v2::log_sql] = create_logger("sql"); - _log[log_v2::log_tcp] = create_logger("tcp"); - _log[log_v2::log_tls] = create_logger("tls"); - _log[log_v2::log_grpc] = create_logger("grpc"); - _log[log_v2::log_victoria_metrics] = create_logger("victoria_metrics"); - gpr_set_log_function(grpc_logger); - _running = true; -} - -log_v2::~log_v2() noexcept { - _log[log_v2::log_core]->info("log finished"); - _running = false; - for (auto& l : _log) - l.reset(); - DEBUG(fmt::format("DESTRUCTOR log_v2 {:p}", static_cast(this))); -} - -void log_v2::apply(const config::state& conf) { - std::lock_guard lock(_load_m); - _running = false; - - const auto& log = conf.log_conf(); - - // reset loggers to null sink - auto null_sink = std::make_shared(); - std::shared_ptr> file_sink; - - _file_path = log.log_path(); - if (log.max_size) - file_sink = std::make_shared( - _file_path, log.max_size, 99); - else - file_sink = std::make_shared(_file_path); - - auto create_log = [&](const std::string& name, level::level_enum lvl) { - spdlog::drop(name); - auto logger = std::make_shared( - name, this, file_sink); - logger->set_level(lvl); - if (lvl != level::off) { - if (log.flush_period) - logger->flush_on(level::warn); - else - logger->flush_on(level::trace); - if (log.log_pid) { - if (log.log_source) - logger->set_pattern( - "[%Y-%m-%dT%H:%M:%S.%e%z] [%n] [%l] [%s:%#] [%P] %v"); - else - logger->set_pattern("[%Y-%m-%dT%H:%M:%S.%e%z] [%n] [%l] [%P] %v"); - } else { - if (log.log_source) - logger->set_pattern("[%Y-%m-%dT%H:%M:%S.%e%z] [%n] [%l] [%s:%#] %v"); - else - logger->set_pattern("[%Y-%m-%dT%H:%M:%S.%e%z] [%n] [%l] %v"); - } - } - - if (name == "grpc") { - switch (lvl) { - case level::level_enum::trace: - case level::level_enum::debug: - gpr_set_log_verbosity(GPR_LOG_SEVERITY_DEBUG); - break; - case level::level_enum::info: - case level::level_enum::warn: - gpr_set_log_verbosity(GPR_LOG_SEVERITY_INFO); - break; - default: - gpr_set_log_verbosity(GPR_LOG_SEVERITY_ERROR); - break; - } - } - - spdlog::register_logger(logger); - return logger; - }; - - _log[log_v2::log_core] = create_log("core", level::info); - core()->info("{} : log started", _file_path); - - absl::flat_hash_map lgs{ - {"bam", log_v2::log_bam}, - {"bbdo", log_v2::log_bbdo}, - {"config", log_v2::log_config}, - {"core", log_v2::log_core}, - {"graphite", log_v2::log_graphite}, - {"grpc", log_v2::log_grpc}, - {"influxdb", log_v2::log_influxdb}, - {"lua", log_v2::log_lua}, - {"neb", log_v2::log_neb}, - {"notification", log_v2::log_notification}, - {"perfdata", log_v2::log_perfdata}, - {"processing", log_v2::log_processing}, - {"rrd", log_v2::log_rrd}, - {"sql", log_v2::log_sql}, - {"stats", log_v2::log_stats}, - {"tcp", log_v2::log_tcp}, - {"tls", log_v2::log_tls}, - {"victoria_metrics", log_v2::log_victoria_metrics}, - }; - for (auto it = log.loggers.begin(), end = log.loggers.end(); it != end; - ++it) { - if (lgs.contains(it->first)) { - _log[lgs[it->first]] = create_log(it->first, level::from_str(it->second)); - lgs.erase(it->first); - } - } - - for (auto it = lgs.begin(); it != lgs.end(); ++it) { - _log[lgs[it->first]] = create_log(it->first, spdlog::level::off); - } - - _flush_interval = - std::chrono::seconds(log.flush_period > 0 ? log.flush_period : 2); - start_flush_timer(file_sink); - _running = true; -} - -void log_v2::set_flush_interval(unsigned second_flush_interval) { - log_v2_base::set_flush_interval(second_flush_interval); - if (second_flush_interval) { - for (auto logger : _log) { - logger->flush_on(level::warn); - } - } else { - for (auto logger : _log) { - logger->flush_on(level::trace); - } - } -} - -/** - * @brief logs are written periodicaly to disk - * - * @param sink - */ -void log_v2::start_flush_timer(spdlog::sink_ptr sink) { - std::lock_guard l(_flush_timer_m); - _flush_timer.expires_after(_flush_interval); - _flush_timer.async_wait([me = std::static_pointer_cast(_instance), - sink](const boost::system::error_code& err) { - if (err || !me->_flush_timer_active) { - return; - } - if (me->get_flush_interval().count() > 0) { - sink->flush(); - } - me->start_flush_timer(sink); - }); -} - -void log_v2::stop_flush_timer() { - std::lock_guard l(_flush_timer_m); - _flush_timer_active = false; - _flush_timer.cancel(); -} - -/** - * @brief Check if the given logger makes part of our loggers - * - * @param logger A logger name - * - * @return a boolean. - */ -bool log_v2::contains_logger(const std::string& logger) { - const std::array loggers{ - "bam", "bbdo", "config", - "core", "lua", "influxdb", - "graphite", "notification", "rrd", - "stats", "perfdata", "processing", - "sql", "neb", "tcp", - "tls", "grpc", "victoria_metrics"}; - return std::find(loggers.begin(), loggers.end(), logger) != loggers.end(); -} - -/** - * @brief Accessor to the various levels of loggers - * - * @return A vector of pairs of strings. The first string is the logger name and - * the second string is its level. - */ -std::vector> log_v2::levels() const { - std::vector> retval; - if (_running) { - retval.reserve(_log.size()); - for (auto& l : _log) { - spdlog::level::level_enum level = l->level(); - auto& lv = to_string_view(level); - retval.emplace_back(l->name(), std::string(lv.data(), lv.size())); - } - } - return retval; -} - -/** - * @brief this private static method is used to access a specific logger - * - * @param log_type - * @param log_str - * @return std::shared_ptr - */ -std::shared_ptr log_v2::get_logger(logger log_type, - const char* log_str) { - if (_running) - return _log[log_type]; - else { - auto null_sink = std::make_shared(); - return std::make_shared(log_str, null_sink); - } -} - -/** - * @brief Check if the given level makes part of the available levels. - * - * @param level A level as a string - * - * @return A boolean. - */ -bool log_v2::contains_level(const std::string& level) { - /* spdlog wants 'off' to disable a log but we tolerate 'disabled' */ - if (level == "disabled" || level == "off") - return true; - - level::level_enum l = level::from_str(level); - return l != level::off; -} - -/** - * @brief Set the level of a logger. - * - * @param logger The logger name - * @param level The level as a string - */ -void log_v2::set_level(const std::string& logger, const std::string& level) { - if (_running) { - bool found = false; - for (auto l : _log) { - if (l->name() == logger) { - found = true; - level::level_enum lvl = level::from_str(level); - if (lvl == level::off && level != "off") - throw msg_fmt("The '{}' level is unknown", level); - l->set_level(lvl); - break; - } - } - if (!found) - throw msg_fmt("The '{}' logger does not exist", logger); - } else - throw msg_fmt( - "Unable to change '{}' logger level, the logger is not running for now " - "- try later.", - logger); -} diff --git a/broker/core/src/main.cc b/broker/core/src/main.cc index 563d473ee9c..7d910ae6d43 100644 --- a/broker/core/src/main.cc +++ b/broker/core/src/main.cc @@ -1,5 +1,5 @@ /** - * Copyright 2009-2013,2015,2018 Centreon + * Copyright 2009-2013,2018-2024 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,6 +31,8 @@ #include #include +#include + #include #include @@ -52,11 +54,11 @@ namespace asio = boost::asio; #include "com/centreon/broker/config/applier/state.hh" #include "com/centreon/broker/config/parser.hh" #include "com/centreon/broker/config/state.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/diagnostic.hh" #include "com/centreon/common/pool.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::exceptions; @@ -64,6 +66,8 @@ using namespace com::centreon::exceptions; std::shared_ptr g_io_context = std::make_shared(); +using log_v2 = com::centreon::common::log_v2::log_v2; + // Main config file. static std::vector gl_mainconfigfiles; static config::state gl_state; @@ -87,16 +91,21 @@ static void hup_handler(int) { signal(SIGHUP, SIG_IGN); // Log message. - log_v2::core()->info("main: configuration update requested"); + auto core_logger = log_v2::instance().get(log_v2::CORE); + core_logger->info("main: configuration update requested"); try { // Parse configuration file. config::parser parsr; config::state conf{parsr.parse(gl_mainconfigfiles.front())}; + auto& log_conf = conf.mut_log_conf(); + log_conf.allow_only_atomic_changes(true); try { - log_v2::instance()->apply(conf); + log_v2::instance().apply(log_conf); + /* We update the logger, since the conf has been applied */ } catch (const std::exception& e) { - log_v2::core()->error("problem while reloading cbd: {}", e.what()); + core_logger->error("problem while reloading cbd: {}", e.what()); + core_logger->error("problem while reloading cbd: {}", e.what()); } try { @@ -105,22 +114,21 @@ static void hup_handler(int) { gl_state = conf; } catch (const std::exception& e) { - log_v2::core()->error( + core_logger->error( "main: configuration update could not succeed, reloading previous " "configuration: {}", e.what()); config::applier::state::instance().apply(gl_state); } catch (...) { - log_v2::core()->error( + core_logger->error( "main: configuration update could not succeed, reloading previous " "configuration"); config::applier::state::instance().apply(gl_state); } } catch (const std::exception& e) { - log_v2::config()->info("main: configuration update failed: {}", e.what()); + core_logger->info("main: configuration update failed: {}", e.what()); } catch (...) { - log_v2::config()->info( - "main: configuration update failed: unknown exception"); + core_logger->info("main: configuration update failed: unknown exception"); } // Reenable SIGHUP handler. @@ -152,19 +160,22 @@ static void term_handler(int signum) { * @return 0 on normal termination, any other value on failure. */ int main(int argc, char* argv[]) { + absl::SetMutexDeadlockDetectionMode(absl::OnDeadlockCycle::kAbort); + absl::EnableMutexInvariantDebugging(true); // Initialization. int opt, option_index = 0, n_thread = 0; std::string broker_name{"unknown"}; uint16_t default_port{51000}; std::string default_listen_address{"localhost"}; - log_v2::load(g_io_context); - com::centreon::common::pool::load(g_io_context, log_v2::core()); + log_v2::load("cbd"); + auto core_logger = log_v2::instance().get(log_v2::CORE); + com::centreon::common::pool::load(g_io_context, core_logger); // Set configuration update handler. if (signal(SIGHUP, hup_handler) == SIG_ERR) { char const* err{strerror(errno)}; - log_v2::core()->info( + core_logger->info( "main: could not register configuration update handler: {}", err); } @@ -175,7 +186,7 @@ int main(int argc, char* argv[]) { // Set termination handler. if (sigaction(SIGTERM, &sigterm_act, nullptr) < 0) - log_v2::core()->info("main: could not register termination handler"); + core_logger->info("main: could not register termination handler"); // Return value. int retval(0); @@ -220,39 +231,39 @@ int main(int argc, char* argv[]) { // Check parameters requirements. if (diagnose) { if (gl_mainconfigfiles.empty()) { - log_v2::core()->error( + core_logger->error( "diagnostic: no configuration file provided: DIAGNOSTIC FILE MIGHT " "NOT BE USEFUL"); } misc::diagnostic diag; diag.generate(gl_mainconfigfiles); } else if (help) { - log_v2::core()->info( + core_logger->info( "USAGE: {} [-s ] [-c] [-D] [-h] [-v] []", argv[0]); - log_v2::core()->info(" '-s' Set poolsize threads."); - log_v2::core()->info(" '-c' Check configuration file."); - log_v2::core()->info(" '-D' Generate a diagnostic file."); - log_v2::core()->info(" '-h' Print this help."); - log_v2::core()->info(" '-v' Print Centreon Broker version."); - log_v2::core()->info("Centreon Broker {}", CENTREON_BROKER_VERSION); - log_v2::core()->info("Copyright 2009-2021 Centreon"); - log_v2::core()->info( + core_logger->info(" '-s' Set poolsize threads."); + core_logger->info(" '-c' Check configuration file."); + core_logger->info(" '-D' Generate a diagnostic file."); + core_logger->info(" '-h' Print this help."); + core_logger->info(" '-v' Print Centreon Broker version."); + core_logger->info("Centreon Broker {}", CENTREON_BROKER_VERSION); + core_logger->info("Copyright 2009-2021 Centreon"); + core_logger->info( "License ASL 2.0 "); retval = 0; } else if (version) { - log_v2::core()->info("Centreon Broker {}", CENTREON_BROKER_VERSION); + core_logger->info("Centreon Broker {}", CENTREON_BROKER_VERSION); retval = 0; } else if (gl_mainconfigfiles.empty()) { - log_v2::core()->error( + core_logger->error( "USAGE: {} [-s ] [-c] [-D] [-h] [-v] []\n\n", argv[0]); return 1; } else { - log_v2::core()->info("Centreon Broker {}", CENTREON_BROKER_VERSION); - log_v2::core()->info("Copyright 2009-2021 Centreon"); - log_v2::core()->info( + core_logger->info("Centreon Broker {}", CENTREON_BROKER_VERSION); + core_logger->info("Copyright 2009-2021 Centreon"); + core_logger->info( "License ASL 2.0 "); // Reset locale. @@ -262,14 +273,14 @@ int main(int argc, char* argv[]) { // Parse configuration file. config::parser parsr; config::state conf{parsr.parse(gl_mainconfigfiles.front())}; + auto& log_conf = conf.log_conf(); try { - log_v2::instance()->apply(conf); + log_v2::instance().apply(log_conf); } catch (const std::exception& e) { - log_v2::core()->error("{}", e.what()); + core_logger->error("{}", e.what()); } - log_v2::core()->info("main: process {} pid:{} begin", argv[0], - getpid()); + core_logger->info("main: process {} pid:{} begin", argv[0], getpid()); if (n_thread > 0 && n_thread < 100) conf.pool_size(n_thread); @@ -301,30 +312,29 @@ int main(int argc, char* argv[]) { while (!gl_term) { std::this_thread::sleep_for(std::chrono::seconds(1)); } - log_v2::core()->info("main: termination request received by process {}", - getpid()); + core_logger->info("main: termination request received by process {}", + getpid()); } - log_v2::instance()->stop_flush_timer(); - // Unload endpoints. + // Unload endpoints. config::applier::deinit(); - spdlog::shutdown(); cache::global_cache::unload(); } } // Standard exception. catch (const std::exception& e) { - log_v2::core()->error("Error during cbd exit: {}", e.what()); + core_logger->error("Error during cbd exit: {}", e.what()); retval = EXIT_FAILURE; } // Unknown exception. catch (...) { - log_v2::core()->error("Error general during cbd exit"); + core_logger->error("Error general during cbd exit"); retval = EXIT_FAILURE; } - log_v2::core()->info("main: process {} pid:{} end exit_code:{}", argv[0], - getpid(), retval); + core_logger->info("main: process {} pid:{} end exit_code:{}", argv[0], + getpid(), retval); g_io_context->stop(); com::centreon::common::pool::unload(); + log_v2::unload(); return retval; } diff --git a/broker/core/src/misc/diagnostic.cc b/broker/core/src/misc/diagnostic.cc index 2adfa3ac9ef..21f394ff1d1 100644 --- a/broker/core/src/misc/diagnostic.cc +++ b/broker/core/src/misc/diagnostic.cc @@ -1,65 +1,40 @@ /** -* Copyright 2013,2015 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2013,2015 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/misc/diagnostic.hh" #include #include #include #include "com/centreon/broker/config/parser.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/filesystem.hh" #include "com/centreon/broker/misc/misc.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::misc; +using log_v2 = com::centreon::common::log_v2::log_v2; /** * Default constructor. */ -diagnostic::diagnostic() {} - -/** - * Copy constructor. - * - * @param[in] right Object to copy. - */ -diagnostic::diagnostic(diagnostic const& right) { - (void)right; -} - -/** - * Destructor. - */ -diagnostic::~diagnostic() throw() {} - -/** - * Assignment operator. - * - * @param[in] right Object to copy. - * - * @return This object. - */ -diagnostic& diagnostic::operator=(diagnostic const& right) { - (void)right; - return (*this); -} +diagnostic::diagnostic() : _logger{log_v2::instance().get(log_v2::CORE)} {} /** * Generate diagnostic file. @@ -86,11 +61,10 @@ void diagnostic::generate(std::vector const& cfg_files, to_remove.push_back(diagnostic_log_path); // Base information about the software. - log_v2::core()->info("diagnostic: Centreon Broker {}", - CENTREON_BROKER_VERSION); + _logger->info("diagnostic: Centreon Broker {}", CENTREON_BROKER_VERSION); // df. - log_v2::core()->info("diagnostic: getting disk usage"); + _logger->info("diagnostic: getting disk usage"); { std::string df_log_path; df_log_path = tmp_dir; @@ -104,7 +78,7 @@ void diagnostic::generate(std::vector const& cfg_files, } // lsb_release. - log_v2::core()->info("diagnostic: getting LSB information"); + _logger->info("diagnostic: getting LSB information"); { std::string lsb_release_log_path; lsb_release_log_path = tmp_dir; @@ -118,7 +92,7 @@ void diagnostic::generate(std::vector const& cfg_files, } // uname. - log_v2::core()->info("diagnostic: getting system name"); + _logger->info("diagnostic: getting system name"); { std::string uname_log_path; uname_log_path = tmp_dir; @@ -132,7 +106,7 @@ void diagnostic::generate(std::vector const& cfg_files, } // /proc/version - log_v2::core()->info("diagnostic: getting kernel information"); + _logger->info("diagnostic: getting kernel information"); { std::string proc_version_log_path; proc_version_log_path = tmp_dir; @@ -146,7 +120,7 @@ void diagnostic::generate(std::vector const& cfg_files, } // netstat. - log_v2::core()->info("diagnostic: getting network connections information"); + _logger->info("diagnostic: getting network connections information"); { std::string netstat_log_path; netstat_log_path = tmp_dir; @@ -160,7 +134,7 @@ void diagnostic::generate(std::vector const& cfg_files, } // ps. - log_v2::core()->info("diagnostic: getting processes information"); + _logger->info("diagnostic: getting processes information"); { std::string ps_log_path; ps_log_path = tmp_dir; @@ -174,7 +148,7 @@ void diagnostic::generate(std::vector const& cfg_files, } // rpm. - log_v2::core()->info("diagnostic: getting packages information"); + _logger->info("diagnostic: getting packages information"); { std::string rpm_log_path; rpm_log_path = tmp_dir; @@ -188,7 +162,7 @@ void diagnostic::generate(std::vector const& cfg_files, } // sestatus. - log_v2::core()->info("diagnostic: getting SELinux status"); + _logger->info("diagnostic: getting SELinux status"); { std::string selinux_log_path; selinux_log_path = tmp_dir; @@ -206,7 +180,7 @@ void diagnostic::generate(std::vector const& cfg_files, end(cfg_files.end()); it != end; ++it) { // Configuration file. - log_v2::core()->info("diagnostic: getting configuration file '{}'", *it); + _logger->info("diagnostic: getting configuration file '{}'", *it); std::string cfg_path; { cfg_path = tmp_dir; @@ -226,16 +200,15 @@ void diagnostic::generate(std::vector const& cfg_files, config::parser parsr; config::state conf; try { - log_v2::core()->info("diagnostic: reading configuration file."); + _logger->info("diagnostic: reading configuration file."); conf = parsr.parse(*it); } catch (std::exception const& e) { - log_v2::core()->error( - "diagnostic: configuration file '{}' parsing failed: {}", *it, - e.what()); + _logger->error("diagnostic: configuration file '{}' parsing failed: {}", + *it, e.what()); } // ls. - log_v2::core()->info("diagnostic: getting modules information"); + _logger->info("diagnostic: getting modules information"); { std::string ls_log_path; ls_log_path = tmp_dir; @@ -272,7 +245,7 @@ void diagnostic::generate(std::vector const& cfg_files, my_out_file = out_file; // Create tarball. - log_v2::core()->info("diagnostic: creating tarball '{}'", my_out_file); + _logger->info("diagnostic: creating tarball '{}'", my_out_file); { std::string cmd{fmt::format("tar czf {} {}", my_out_file, tmp_dir)}; std::string output{misc::exec(cmd)}; diff --git a/broker/core/src/misc/filesystem.cc b/broker/core/src/misc/filesystem.cc index 0e708ec5947..9331c821f41 100644 --- a/broker/core/src/misc/filesystem.cc +++ b/broker/core/src/misc/filesystem.cc @@ -1,20 +1,20 @@ /** -* Copyright 2015,2017 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2015,2017 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/misc/filesystem.hh" #include @@ -22,11 +22,13 @@ #include #include #include -#include "com/centreon/broker/log_v2.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::misc; +using log_v2 = com::centreon::common::log_v2::log_v2; + /** * Fill a strings list with the files listed in the directory. * @@ -71,8 +73,9 @@ std::list filesystem::dir_content(std::string const& path, } closedir(dir); } else - log_v2::core()->error("directory_dumper: unable to read directory '{}'", - path); + log_v2::instance() + .get(log_v2::CORE) + ->error("directory_dumper: unable to read directory '{}'", path); return retval; } diff --git a/broker/core/src/misc/parse_perfdata.cc b/broker/core/src/misc/parse_perfdata.cc index 0b91babd163..0dd459170bc 100644 --- a/broker/core/src/misc/parse_perfdata.cc +++ b/broker/core/src/misc/parse_perfdata.cc @@ -1,34 +1,36 @@ /** -* Copyright 2011-2013,2017-2021 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2013,2017-2021 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include #include #include #include "bbdo/storage/metric.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/misc.hh" #include "com/centreon/broker/misc/string.hh" #include "com/centreon/broker/sql/table_max_size.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::misc; +using log_v2 = com::centreon::common::log_v2::log_v2; + /** * Extract a real value from a perfdata string. * @@ -123,9 +125,11 @@ static inline void extract_range(double* low, * * @return A list of perfdata */ -std::list misc::parse_perfdata(uint32_t host_id, - uint32_t service_id, - const char* str) { +std::list misc::parse_perfdata( + uint32_t host_id, + uint32_t service_id, + const char* str, + const std::shared_ptr& logger) { std::list retval; auto id = [host_id, service_id] { if (host_id || service_id) @@ -138,8 +142,7 @@ std::list misc::parse_perfdata(uint32_t host_id, const char* buf = str + start; // Debug message. - log_v2::perfdata()->debug("storage: parsing service {} perfdata string '{}'", - id(), buf); + logger->debug("storage: parsing service {} perfdata string '{}'", id(), buf); char const* tmp = buf; @@ -208,9 +211,8 @@ std::list misc::parse_perfdata(uint32_t host_id, name, get_metrics_col_size(metrics_metric_name))); p.name(std::move(name)); } else { - log_v2::perfdata()->error( - "In service {}, metric name empty before '{}...'", id(), - fmt::string_view(s, 10)); + logger->error("In service {}, metric name empty before '{}...'", id(), + fmt::string_view(s, 10)); error = true; } @@ -219,7 +221,7 @@ std::list misc::parse_perfdata(uint32_t host_id, int i; for (i = 0; i < 10 && tmp[i]; i++) ; - log_v2::perfdata()->warn( + logger->warn( "invalid perfdata format in service {}: equal sign not present or " "misplaced '{}'", id(), fmt::string_view(s, (tmp - s) + i)); @@ -239,7 +241,7 @@ std::list misc::parse_perfdata(uint32_t host_id, for (i = 0; i < 10 && tmp[i]; i++) ; - log_v2::perfdata()->warn( + logger->warn( "storage: invalid perfdata format in service {}: no numeric value " "after equal sign " "'{}'", @@ -291,7 +293,7 @@ std::list misc::parse_perfdata(uint32_t host_id, p.max(extract_double(const_cast(&tmp))); // Log new perfdata. - log_v2::perfdata()->debug( + logger->debug( "storage: got new perfdata (name={}, value={}, unit={}, warning={}, " "critical={}, min={}, max={})", p.name(), p.value(), p.unit(), p.warning(), p.critical(), p.min(), diff --git a/broker/core/src/modules/handle.cc b/broker/core/src/modules/handle.cc index 08e33d2c872..7e7d08f962d 100644 --- a/broker/core/src/modules/handle.cc +++ b/broker/core/src/modules/handle.cc @@ -1,29 +1,31 @@ /** -* Copyright 2011-2013,2015, 2021 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2013,2015, 2021 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/modules/handle.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::modules; +using log_v2 = com::centreon::common::log_v2::log_v2; + constexpr const char* handle::deinitialization; constexpr const char* handle::initialization; constexpr const char* handle::updatization; @@ -31,7 +33,9 @@ constexpr const char* handle::versionning; constexpr const char* handle::parents_list; handle::handle(const std::string& filename, void* h, const void* arg) - : _filename{filename}, _handle{h} { + : _filename{filename}, + _handle{h}, + _logger{log_v2::instance().get(log_v2::CORE)} { _init(arg); } @@ -42,10 +46,9 @@ handle::~handle() noexcept { try { _close(); } catch (std::exception const& e) { - log_v2::core()->error("{}", e.what()); + _logger->error("{}", e.what()); } catch (...) { - log_v2::core()->error("modules: unknown error while unloading '{}'", - _filename); + _logger->error("modules: unknown error while unloading '{}'", _filename); } } @@ -59,7 +62,7 @@ handle::~handle() noexcept { void handle::_close() { if (is_open()) { // Log message. - log_v2::core()->info("modules: closing '{}'", _filename); + _logger->info("modules: closing '{}'", _filename); // Find deinitialization routine. union { @@ -72,28 +75,28 @@ void handle::_close() { // Could not find deinitialization routine. char const* error_str{dlerror()}; if (error_str) { - log_v2::core()->info( + _logger->info( "modules: could not find deinitialization routine in '{}': {}", _filename, error_str); } // Call deinitialization routine. else { - log_v2::core()->debug("modules: running deinitialization routine of '{}'", - _filename); + _logger->debug("modules: running deinitialization routine of '{}'", + _filename); can_unload = (*(sym.code))(); } if (!can_unload) { - log_v2::core()->debug("modules: don't unload library '{}'", _filename); + _logger->debug("modules: don't unload library '{}'", _filename); return; } // Reset library handle. - log_v2::core()->debug("modules: unloading library '{}'", _filename); + _logger->debug("modules: unloading library '{}'", _filename); // Library was not unloaded. if (dlclose(_handle)) { char const* error_str{dlerror()}; - log_v2::core()->info("modules: could not unload library '{}': {}", - _filename, error_str); + _logger->info("modules: could not unload library '{}': {}", _filename, + error_str); } else _handle = nullptr; } @@ -127,7 +130,7 @@ void handle::update(void const* arg) { // Found routine. if (sym.data) { - log_v2::core()->debug("modules: running update routine of '{}'", _filename); + _logger->debug("modules: running update routine of '{}'", _filename); (*(void (*)(void const*))(sym.code))(arg); } } @@ -146,7 +149,6 @@ void handle::_init(void const* arg) { sym.data = dlsym(_handle, initialization); // Call initialization routine. - log_v2::core()->debug("modules: running initialization routine of '{}'", - _filename); + _logger->debug("modules: running initialization routine of '{}'", _filename); (*(void (*)(void const*))(sym.code))(arg); } diff --git a/broker/core/src/persistent_cache.cc b/broker/core/src/persistent_cache.cc index ee099fd7a9b..1495e2f2167 100644 --- a/broker/core/src/persistent_cache.cc +++ b/broker/core/src/persistent_cache.cc @@ -17,32 +17,33 @@ */ #include "com/centreon/broker/persistent_cache.hh" + #include + #include + #include "com/centreon/broker/bbdo/stream.hh" #include "com/centreon/broker/exceptions/shutdown.hh" #include "com/centreon/broker/file/opener.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; +using log_v2 = com::centreon::common::log_v2::log_v2; /** * Constructor. * * @param[in] cache_file Path to the cache file. */ -persistent_cache::persistent_cache(const std::string& cache_file) - : _cache_file(cache_file) { +persistent_cache::persistent_cache( + const std::string& cache_file, + const std::shared_ptr& logger) + : _cache_file(cache_file), _logger{logger} { _open(); } -/** - * Destructor. - */ -persistent_cache::~persistent_cache() {} - /** * @brief Add an event to the persistent cache. * @@ -80,8 +81,7 @@ void persistent_cache::commit() { } // No error checking, this is a secondary issue. if (unlink(_old_file().c_str())) - log_v2::core()->error("removing persistent cache '{}' failed", - _old_file()); + _logger->error("removing persistent cache '{}' failed", _old_file()); } } @@ -178,3 +178,12 @@ void persistent_cache::_open() { // We will access only the BBDO layer. _read_file = std::static_pointer_cast(bs); } + +/** + * @brief Accessor to the logger. + * + * @return A shared pointer to the logger. + */ +std::shared_ptr persistent_cache::logger() const { + return _logger; +} diff --git a/broker/core/src/persistent_file.cc b/broker/core/src/persistent_file.cc index 2d2f9a687b4..397ca10aed9 100644 --- a/broker/core/src/persistent_file.cc +++ b/broker/core/src/persistent_file.cc @@ -1,20 +1,20 @@ /** -* Copyright 2015,2017, 2020-2021 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2015,2017, 2020-2021 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/persistent_file.hh" @@ -22,9 +22,11 @@ #include "com/centreon/broker/compression/stream.hh" #include "com/centreon/broker/file/opener.hh" #include "com/centreon/broker/file/stream.hh" -#include "com/centreon/broker/log_v2.hh" +#include "com/centreon/broker/stats/center.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; +using log_v2 = com::centreon::common::log_v2::log_v2; /** * Constructor. @@ -52,7 +54,7 @@ persistent_file::persistent_file(const std::string& path, QueueFileStats* stats) // Set stream. io::stream::set_substream(bs); if (stats) - stats::center::instance().execute( + stats::center::instance_ptr()->execute( [path, stats, max_file_size = _splitter->max_file_size()] { stats->set_name(path); stats->set_max_file_size(max_file_size); @@ -96,8 +98,9 @@ int32_t persistent_file::write(std::shared_ptr const& d) { */ int32_t persistent_file::stop() { int32_t retval = _substream->stop(); - log_v2::core()->info("persistent file stopped with {} acknowledged events", - retval); + log_v2::instance() + .get(log_v2::CORE) + ->info("persistent file stopped with {} acknowledged events", retval); return retval; } diff --git a/broker/core/src/processing/acceptor.cc b/broker/core/src/processing/acceptor.cc index 72554e14aba..7ab277af3a2 100644 --- a/broker/core/src/processing/acceptor.cc +++ b/broker/core/src/processing/acceptor.cc @@ -1,5 +1,5 @@ /** - * Copyright 2015-2022 Centreon + * Copyright 2015-2024 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,13 +21,15 @@ #include #include "com/centreon/broker/io/endpoint.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/misc.hh" #include "com/centreon/broker/processing/feeder.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::processing; +using log_v2 = com::centreon::common::log_v2::log_v2; + /** * Constructor. * @@ -46,9 +48,11 @@ acceptor::acceptor(std::shared_ptr endp, _read_filters_str(misc::dump_filters(_read_filters)), _write_filters(w_filter), _write_filters_str(misc::dump_filters(_write_filters)) { - log_v2::config()->trace( - "processing::acceptor '{}': read filter <<{}>> ; write filter <<{}>>", - name, _read_filters_str, _write_filters_str); + log_v2::instance() + .get(log_v2::CONFIG) + ->trace( + "processing::acceptor '{}': read filter <<{}>> ; write filter <<{}>>", + name, _read_filters_str, _write_filters_str); } /** @@ -66,12 +70,13 @@ void acceptor::accept() { // Try to accept connection. std::shared_ptr u = _endp->open(); + auto core_logger = log_v2::instance().get(log_v2::CORE); if (u) { // Create feeder thread. std::string name(fmt::format("{}-{}", _name, ++connection_id)); - SPDLOG_LOGGER_INFO(log_v2::core(), "New incoming connection '{}'", name); - log_v2::config()->debug( + SPDLOG_LOGGER_INFO(core_logger, "New incoming connection '{}'", name); + core_logger->debug( "New feeder {} with read_filters {} and write_filters {}", name, _read_filters.get_allowed_categories(), _write_filters.get_allowed_categories()); @@ -81,11 +86,11 @@ void acceptor::accept() { std::lock_guard lock(_stat_mutex); _feeders.push_back(f); - SPDLOG_LOGGER_TRACE(log_v2::core(), + SPDLOG_LOGGER_TRACE(core_logger, "Currently {} connections to acceptor '{}'", _feeders.size(), _name); } else - log_v2::core()->debug("accept ('{}') failed.", _name); + core_logger->debug("accept ('{}') failed.", _name); } /** @@ -191,7 +196,7 @@ void acceptor::_callback() noexcept { _state = running; _state_cv.notify_all(); lock.unlock(); - + auto logger = log_v2::instance().get(log_v2::CORE); // Run as long as no exit request was made. while (!_should_exit) { try { @@ -201,13 +206,14 @@ void acceptor::_callback() noexcept { } catch (std::exception const& e) { _set_listening(false); // Log error. - SPDLOG_LOGGER_ERROR(log_v2::core(), + SPDLOG_LOGGER_ERROR(logger, "acceptor: endpoint '{}' could not accept client: {}", _name, e.what()); // Sleep a while before reconnection. - log_v2::core()->debug( - "acceptor: endpoint '{}' will wait {}s before attempting to accept a " + logger->debug( + "acceptor: endpoint '{}' will wait {}s before attempting to " + "accept a " "new client", _name, _retry_interval); time_t limit{time(nullptr) + _retry_interval}; @@ -220,10 +226,10 @@ void acceptor::_callback() noexcept { { std::lock_guard lock(_stat_mutex); for (auto it = _feeders.begin(), end = _feeders.end(); it != end;) { - SPDLOG_LOGGER_TRACE(log_v2::core(), "acceptor '{}' feeder '{}'", _name, + SPDLOG_LOGGER_TRACE(logger, "acceptor '{}' feeder '{}'", _name, (*it)->get_name()); if ((*it)->is_finished()) { - SPDLOG_LOGGER_INFO(log_v2::core(), "removing '{}' from acceptor '{}'", + SPDLOG_LOGGER_INFO(logger, "removing '{}' from acceptor '{}'", (*it)->get_name(), _name); it = _feeders.erase(it); } else @@ -231,8 +237,7 @@ void acceptor::_callback() noexcept { } } } - SPDLOG_LOGGER_INFO(log_v2::core(), "processing acceptor '{}' finished", - _name); + SPDLOG_LOGGER_INFO(logger, "processing acceptor '{}' finished", _name); _set_listening(false); lock.lock(); diff --git a/broker/core/src/processing/failover.cc b/broker/core/src/processing/failover.cc index 2a7ca7a67f1..3c03f3c98a9 100644 --- a/broker/core/src/processing/failover.cc +++ b/broker/core/src/processing/failover.cc @@ -1,5 +1,5 @@ /** - * Copyright 2011-2017, 2021 Centreon + * Copyright 2011-2017, 2021-2024 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,13 +22,14 @@ #include "com/centreon/broker/exceptions/connection_closed.hh" #include "com/centreon/broker/exceptions/shutdown.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/misc.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::processing; +using log_v2 = com::centreon::common::log_v2::log_v2; /** * Constructor. @@ -43,6 +44,7 @@ failover::failover(std::shared_ptr endp, : endpoint(false, name), _should_exit(false), _state(not_started), + _logger{log_v2::instance().get(log_v2::PROCESSING)}, _buffering_timeout(0), _endpoint(endp), _failover_launched(false), @@ -50,18 +52,16 @@ failover::failover(std::shared_ptr endp, _next_timeout(0), _muxer(mux), _update(false) { - DEBUG(fmt::format("CONSTRUCTOR failover {:p} {} - muxer: {:p}", - static_cast(this), name, - static_cast(mux.get()))); - SPDLOG_LOGGER_TRACE(log_v2::core(), "failover '{}' construction.", _name); + SPDLOG_LOGGER_TRACE(_logger, "failover '{}' construction.", _name); } /** * Destructor. */ failover::~failover() { + _logger->trace("failover::failover destructor {} {}", + static_cast(this), _name); exit(); - DEBUG(fmt::format("DESTRUCTOR failover {:p}", static_cast(this))); } /** @@ -74,6 +74,7 @@ void failover::add_secondary_endpoint(std::shared_ptr endp) { multiplexing::muxer_filter w_filter = endp->get_stream_mandatory_filter(); for (const auto& sec_endpt : _secondary_endpoints) { w_filter |= sec_endpt->get_stream_mandatory_filter(); + w_filter -= sec_endpt->get_stream_forbidden_filter(); } _muxer->set_write_filter(w_filter); } @@ -90,13 +91,12 @@ void failover::add_secondary_endpoint(std::shared_ptr endp) { * writing to the same files. */ void failover::exit() { - SPDLOG_LOGGER_TRACE(log_v2::core(), "failover '{}' exit.", _name); + SPDLOG_LOGGER_TRACE(_logger, "failover '{}' exit.", _name); std::unique_lock lck(_state_m); if (_state != not_started) { if (!_should_exit) { _should_exit = true; - SPDLOG_LOGGER_TRACE(log_v2::processing(), "Waiting for {} to be stopped", - _name); + SPDLOG_LOGGER_TRACE(_logger, "Waiting for {} to be stopped", _name); _state_cv.wait( lck, [this] { return _state == stopped || _state == not_started; }); @@ -105,7 +105,7 @@ void failover::exit() { _thread.join(); } _muxer->wake(); - SPDLOG_LOGGER_TRACE(log_v2::core(), "failover '{}' exited.", _name); + SPDLOG_LOGGER_TRACE(_logger, "failover '{}' exited.", _name); } /** @@ -141,13 +141,13 @@ time_t failover::get_retry_interval() const noexcept { void failover::_run() { std::unique_lock lck(_state_m); // Initial log. - SPDLOG_LOGGER_DEBUG(log_v2::processing(), - "failover: thread of endpoint '{}' is starting", _name); + SPDLOG_LOGGER_DEBUG(_logger, "failover: thread of endpoint '{}' is starting", + _name); // Check endpoint. if (!_endpoint) { SPDLOG_LOGGER_ERROR( - log_v2::processing(), + _logger, "failover: thread of endpoint '{}' has no endpoint object, this is " "likely a software bug that should be reported to Centreon Broker " "developers", @@ -163,8 +163,7 @@ void failover::_run() { try { ack_events = _stream->stop(); } catch (const std::exception& e) { - SPDLOG_LOGGER_ERROR(log_v2::core(), - "Failed to send stop event to stream: {}", + SPDLOG_LOGGER_ERROR(_logger, "Failed to send stop event to stream: {}", e.what()); } _muxer->ack_events(ack_events); @@ -199,12 +198,9 @@ void failover::_run() { _stream = s; set_state(s ? "connected" : "connecting"); if (s) - SPDLOG_LOGGER_DEBUG(log_v2::processing(), - "{} stream {:p} connected", _name, - static_cast(s.get())); + SPDLOG_LOGGER_DEBUG(_logger, "{} stream connected", _name); else - SPDLOG_LOGGER_DEBUG(log_v2::processing(), - "{} fail to create stream", _name); + SPDLOG_LOGGER_DEBUG(_logger, "{} fail to create stream", _name); } _initialized = true; set_last_connection_success(timestamp::now()); @@ -215,7 +211,7 @@ void failover::_run() { // Buffering. if (_buffering_timeout > 0) { // Status. - SPDLOG_LOGGER_DEBUG(log_v2::processing(), + SPDLOG_LOGGER_DEBUG(_logger, "failover: buffering data for endpoint '{}' ({}s)", _name, _buffering_timeout); _update_status("buffering data"); @@ -242,13 +238,13 @@ void failover::_run() { secondaries.push_back(s); else SPDLOG_LOGGER_ERROR( - log_v2::processing(), + _logger, "failover: could not open a secondary of endpoint {}: " "secondary returned a null stream", _name); } catch (std::exception const& e) { SPDLOG_LOGGER_ERROR( - log_v2::processing(), + _logger, "failover: error occured while opening a secondary of endpoint " "'{}': {}", _name, e.what()); @@ -257,7 +253,7 @@ void failover::_run() { // Shutdown failover. if (_failover_launched) { - SPDLOG_LOGGER_DEBUG(log_v2::processing(), + SPDLOG_LOGGER_DEBUG(_logger, "failover: shutting down failover of endpoint '{}'", _name); _update_status("shutting down failover"); @@ -267,9 +263,8 @@ void failover::_run() { } // Event processing loop. - SPDLOG_LOGGER_DEBUG(log_v2::processing(), - "failover: launching event loop of endpoint '{}'", - _name); + SPDLOG_LOGGER_DEBUG( + _logger, "failover: launching event loop of endpoint '{}'", _name); _muxer->nack_events(); bool stream_can_read(true); bool muxer_can_read(true); @@ -279,6 +274,8 @@ void failover::_run() { time_t fill_stats_time = time(nullptr); while (!should_exit()) { + assert(!log_v2::instance().not_threadsafe_configuration()); + // Check for update. if (_update) { std::lock_guard stream_lock(_stream_m); @@ -296,23 +293,22 @@ void failover::_run() { d.reset(); bool timed_out_stream(true); if (stream_can_read) { - SPDLOG_LOGGER_DEBUG(log_v2::processing(), - "failover: reading event from endpoint '{}'", - _name); + SPDLOG_LOGGER_DEBUG( + _logger, "failover: reading event from endpoint '{}'", _name); _update_status("reading event from stream"); try { std::lock_guard stream_lock(_stream_m); timed_out_stream = !_stream->read(d, 0); } catch (exceptions::shutdown const& e) { SPDLOG_LOGGER_DEBUG( - log_v2::processing(), + _logger, "failover: stream of endpoint '{}' shutdown while reading: {}", _name, e.what()); stream_can_read = false; } if (d) { SPDLOG_LOGGER_DEBUG( - log_v2::processing(), + _logger, "failover: writing event of endpoint '{}' to multiplexing " "engine", _name); @@ -329,33 +325,31 @@ void failover::_run() { d.reset(); bool timed_out_muxer(true); if (muxer_can_read) { - SPDLOG_LOGGER_DEBUG(log_v2::processing(), - "failover: reading event from " - "multiplexing engine for endpoint '{}'", + SPDLOG_LOGGER_DEBUG(_logger, + "failover: reading event from multiplexing " + "engine for endpoint '{}'", _name); _update_status("reading event from multiplexing engine"); try { timed_out_muxer = !_muxer->read(d, 0); should_commit = should_commit || d; - } catch (exceptions::shutdown const& e) { - SPDLOG_LOGGER_DEBUG(log_v2::processing(), - "failover: muxer of endpoint '{}' " - "shutdown while reading: {}", - _name, e.what()); + } catch (const exceptions::shutdown& e) { + SPDLOG_LOGGER_DEBUG( + _logger, + "failover: muxer of endpoint '{}' shutdown while reading: {}", + _name, e.what()); muxer_can_read = false; } if (d) { - if (log_v2::processing()->level() == spdlog::level::trace) - SPDLOG_LOGGER_TRACE(log_v2::processing(), + if (_logger->level() == spdlog::level::trace) + SPDLOG_LOGGER_TRACE(_logger, "failover: writing event {} of multiplexing " - "engine to endpoint " - "'{}'", + "engine to endpoint '{}'", *d, _name); else - SPDLOG_LOGGER_DEBUG(log_v2::processing(), + SPDLOG_LOGGER_DEBUG(_logger, "failover: writing event {} of multiplexing " - "engine to endpoint " - "'{}'", + "engine to endpoint '{}'", d->type(), _name); _update_status("writing event to stream"); int we(0); @@ -365,7 +359,7 @@ void failover::_run() { we = _stream->write(d); } catch (exceptions::shutdown const& e) { SPDLOG_LOGGER_DEBUG( - log_v2::processing(), + _logger, "failover: stream of endpoint '{}' shutdown while writing: " "{}", _name, e.what()); @@ -382,7 +376,7 @@ void failover::_run() { ++it; } catch (std::exception const& e) { SPDLOG_LOGGER_ERROR( - log_v2::processing(), + _logger, "failover: error occurred while writing to a secondary of " "endpoint '{}' (secondary will be removed): {}", _name, e.what()); @@ -390,6 +384,8 @@ void failover::_run() { } } _update_status(""); + } else { + _logger->debug("failover: no event read from muxer"); } } @@ -415,16 +411,14 @@ void failover::_run() { } // Some real error occured. catch (const exceptions::connection_closed&) { - SPDLOG_LOGGER_INFO(log_v2::processing(), "failover {}: connection closed", - _name); + SPDLOG_LOGGER_INFO(_logger, "failover {}: connection closed", _name); on_exception_handler(); } catch (const std::exception& e) { - SPDLOG_LOGGER_ERROR(log_v2::processing(), "failover {}: global error: {}", - _name, e.what()); + SPDLOG_LOGGER_ERROR(_logger, "failover: global error: {}", e.what()); on_exception_handler(); } catch (...) { SPDLOG_LOGGER_ERROR( - log_v2::processing(), + _logger, "failover: endpoint '{}' encountered an unknown exception, this is " "likely a software bug that should be reported to Centreon Broker " "developers", @@ -432,8 +426,7 @@ void failover::_run() { on_exception_handler(); } - SPDLOG_LOGGER_DEBUG(log_v2::processing(), - "failover {} end of loop => reconnect", _name); + SPDLOG_LOGGER_DEBUG(_logger, "failover {} end of loop => reconnect", _name); // Clear stream. { @@ -444,9 +437,8 @@ void failover::_run() { try { ack_events = _stream->stop(); } catch (const std::exception& e) { - SPDLOG_LOGGER_ERROR(log_v2::processing(), - "Failed to send stop event to stream: {}", - e.what()); + SPDLOG_LOGGER_ERROR( + _logger, "Failed to send stop event to stream: {}", e.what()); } _muxer->ack_events(ack_events); _stream.reset(); @@ -472,8 +464,7 @@ void failover::_run() { try { ack_events = _stream->stop(); } catch (const std::exception& e) { - SPDLOG_LOGGER_ERROR(log_v2::processing(), - "Failed to send stop event to stream: {}", + SPDLOG_LOGGER_ERROR(_logger, "Failed to send stop event to stream: {}", e.what()); } _muxer->ack_events(ack_events); @@ -485,14 +476,14 @@ void failover::_run() { // Exit failover thread if necessary. if (_failover) { SPDLOG_LOGGER_INFO( - log_v2::processing(), + _logger, "failover: requesting termination of failover of endpoint '{}'", _name); _failover->exit(); } // Exit log. - SPDLOG_LOGGER_DEBUG(log_v2::processing(), - "failover: thread of endpoint '{}' is exiting", _name); + SPDLOG_LOGGER_DEBUG(_logger, "failover: thread of endpoint '{}' is exiting", + _name); lck.lock(); _state = stopped; @@ -609,7 +600,7 @@ uint32_t failover::_get_queued_events() const { * Start the internal thread. */ void failover::start() { - SPDLOG_LOGGER_DEBUG(log_v2::processing(), "start failover '{}'.", _name); + SPDLOG_LOGGER_DEBUG(_logger, "start failover '{}'.", _name); std::unique_lock lck(_state_m); if (_state != running) { _should_exit = false; @@ -617,7 +608,7 @@ void failover::start() { pthread_setname_np(_thread.native_handle(), "proc_failover"); _state_cv.wait(lck, [this] { return _state != not_started; }); } - SPDLOG_LOGGER_TRACE(log_v2::core(), "failover '{}' started.", _name); + SPDLOG_LOGGER_TRACE(_logger, "failover '{}' started.", _name); } /** @@ -630,6 +621,7 @@ bool failover::should_exit() const { } bool failover::wait_for_all_events_written(unsigned ms_timeout) { + _logger->info("processing::failover::wait_for_all_events_written"); std::lock_guard stream_lock(_stream_m); if (_stream) { return _stream->wait_for_all_events_written(ms_timeout); diff --git a/broker/core/src/processing/feeder.cc b/broker/core/src/processing/feeder.cc index 0f338199d30..a433cfcb232 100644 --- a/broker/core/src/processing/feeder.cc +++ b/broker/core/src/processing/feeder.cc @@ -1,20 +1,20 @@ /** -* Copyright 2011-2012,2015,2017, 2020-2021 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2012,2015,2017, 2020-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/processing/feeder.hh" @@ -24,15 +24,16 @@ #include "com/centreon/broker/exceptions/shutdown.hh" #include "com/centreon/broker/io/raw.hh" #include "com/centreon/broker/io/stream.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/misc.hh" #include "com/centreon/broker/multiplexing/muxer.hh" #include "com/centreon/common/pool.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::processing; +using log_v2 = com::centreon::common::log_v2::log_v2; constexpr unsigned max_event_queue_size = 0x10000; @@ -54,9 +55,9 @@ std::shared_ptr feeder::create( const multiplexing::muxer_filter& write_filters) { std::shared_ptr ret( new feeder(name, parent, client, read_filters, write_filters)); + ret->_start_stat_timer(); - ret->_read_from_muxer(); ret->_start_read_from_stream_timer(); return ret; } @@ -85,17 +86,19 @@ feeder::feeder(const std::string& name, false)), _stat_timer(com::centreon::common::pool::io_context()), _read_from_stream_timer(com::centreon::common::pool::io_context()), - _io_context(com::centreon::common::pool::io_context_ptr()) { - DEBUG(fmt::format("CONSTRUCTOR feeder {:p} {} - muxer: {:p}", - static_cast(this), name, - static_cast(_muxer.get()))); + _io_context(com::centreon::common::pool::io_context_ptr()), + _logger{log_v2::instance().get(log_v2::PROCESSING)} { if (!_client) throw msg_fmt("could not process '{}' with no client stream", _name); + _muxer->set_action_on_new_data( + [this](const std::vector>& events) -> uint32_t { + return _write_to_client(events); + }); set_last_connection_attempt(timestamp::now()); set_last_connection_success(timestamp::now()); set_state("connected"); - SPDLOG_LOGGER_DEBUG(log_v2::core(), "create feeder {}, {:p}", name, + SPDLOG_LOGGER_DEBUG(_logger, "create feeder {}, {:p}", name, static_cast(this)); } @@ -103,10 +106,7 @@ feeder::feeder(const std::string& name, * Destructor. */ feeder::~feeder() { - SPDLOG_LOGGER_DEBUG(log_v2::core(), "destroy feeder {}, {:p}", get_name(), - static_cast(this)); stop(); - DEBUG(fmt::format("DESTRUCTOR feeder {:p}", static_cast(this))); } bool feeder::is_finished() const noexcept { @@ -144,59 +144,6 @@ void feeder::_forward_statistic(nlohmann::json& tree) { } } -/***************************************************************************** - * muxer => client - *****************************************************************************/ -/** - * @brief read event from muxer (both synchronous or asynchronous) - * if an event is available => call _write_to_client - * if not, _write_to_client will be called from muxer when event arrive - */ -void feeder::_read_from_muxer() { - bool have_to_terminate = false; - bool other_event_to_read = true; - std::vector> events; - std::chrono::system_clock::time_point timeout_read = - std::chrono::system_clock::now() + std::chrono::milliseconds(100); - std::unique_lock l(_protect); - if (_state != state::running) { - return; - } - events.reserve(_muxer->get_event_queue_size()); - while (other_event_to_read && !have_to_terminate && - std::chrono::system_clock::now() < timeout_read) { - other_event_to_read = - _muxer->read(events, max_event_queue_size, - [me = shared_from_this()]() { me->_read_from_muxer(); }); - - SPDLOG_LOGGER_TRACE(log_v2::processing(), - "feeder '{}': {} events read from muxer", _name, - events.size()); - - // if !other_event_to_read callback is stored and will be called as soon as - // events will be available - if (!events.empty()) { - unsigned written = _write_to_client(events); - if (written > 0) { - _ack_event_to_muxer(written); - // as retention may fill queue we try to read once more - other_event_to_read = false; - } - if (written != events.size()) //_client fails to write all events - have_to_terminate = true; - } - events.clear(); - } - if (have_to_terminate) { - _stop_no_lock(); - return; - } - if (other_event_to_read) { // other events to read => give time to - // asio to work - _io_context->post([me = shared_from_this()]() { me->_read_from_muxer(); }); - } -} - /** * @brief write event to client stream * _protect must be locked @@ -208,34 +155,31 @@ unsigned feeder::_write_to_client( unsigned written = 0; try { for (const std::shared_ptr& event : events) { - if (log_v2::processing()->level() == spdlog::level::trace) { + if (_logger->level() == spdlog::level::trace) { SPDLOG_LOGGER_TRACE( - log_v2::processing(), + _logger, "feeder '{}': sending 1 event {:x} from muxer to stream {}", _name, event->type(), *event); } else { SPDLOG_LOGGER_DEBUG( - log_v2::processing(), - "feeder '{}': sending 1 event {:x} from muxer to stream", _name, - event->type()); + _logger, "feeder '{}': sending 1 event {:x} from muxer to stream", + _name, event->type()); } _client->write(event); ++written; } } catch (exceptions::shutdown const&) { // Normal termination. - SPDLOG_LOGGER_INFO(log_v2::core(), "from muxer feeder '{}' shutdown", - _name); + SPDLOG_LOGGER_INFO(_logger, "from muxer feeder '{}' shutdown", _name); } catch (const exceptions::connection_closed&) { set_last_error(""); - SPDLOG_LOGGER_INFO(log_v2::processing(), "feeder '{}' connection closed", - _name); + SPDLOG_LOGGER_INFO(_logger, "feeder '{}' connection closed", _name); } catch (const std::exception& e) { set_last_error(e.what()); - SPDLOG_LOGGER_ERROR(log_v2::processing(), - "from muxer feeder '{}' error:{} ", _name, e.what()); + SPDLOG_LOGGER_ERROR(_logger, "from muxer feeder '{}' error:{} ", _name, + e.what()); } catch (...) { - SPDLOG_LOGGER_ERROR(log_v2::processing(), + SPDLOG_LOGGER_ERROR(_logger, "from muxer feeder: unknown error occured while " "processing client '{}'", _name); @@ -244,16 +188,16 @@ unsigned feeder::_write_to_client( } /** - * @brief acknowledge event to the muxer and catch exception from it + * @brief acknowledge events to the muxer and catch exception from it * * @param count */ -void feeder::_ack_event_to_muxer(unsigned count) noexcept { +void feeder::_ack_events_on_muxer(unsigned count) noexcept { try { _muxer->ack_events(count); } catch (const std::exception&) { - SPDLOG_LOGGER_ERROR(log_v2::processing(), - " {} fail to acknowledge {} events", _name, count); + SPDLOG_LOGGER_ERROR(_logger, " {} fail to acknowledge {} events", _name, + count); } } @@ -264,7 +208,6 @@ void feeder::_ack_event_to_muxer(unsigned count) noexcept { void feeder::stop() { std::unique_lock l(_protect); _stop_no_lock(); - DEBUG(fmt::format("STOP feeder {:p}", static_cast(this))); } /** @@ -272,8 +215,7 @@ void feeder::stop() { * */ void feeder::_stop_no_lock() { - SPDLOG_LOGGER_INFO(log_v2::processing(), "{} Stop without lock called", - _name); + SPDLOG_LOGGER_INFO(_logger, "{} Stop without lock called", _name); state expected = state::running; if (!_state.compare_exchange_strong(expected, state::finished)) { return; @@ -281,6 +223,7 @@ void feeder::_stop_no_lock() { set_state("disconnected"); + _muxer->clear_action_on_new_data(); // muxer should not receive events _muxer->unsubscribe(); _stat_timer.cancel(); @@ -292,16 +235,18 @@ void feeder::_stop_no_lock() { try { _client->stop(); } catch (const std::exception& e) { - SPDLOG_LOGGER_ERROR(log_v2::processing(), - "{} Failed to send stop event to client: {}", _name, - e.what()); + SPDLOG_LOGGER_ERROR(_logger, "{} Failed to send stop event to client: {}", + _name, e.what()); } - SPDLOG_LOGGER_INFO(log_v2::core(), - "feeder: queue files of client '{}' removed", _name); + SPDLOG_LOGGER_INFO(_logger, "feeder: queue files of client '{}' removed", + _name); _muxer->remove_queue_files(); - SPDLOG_LOGGER_INFO(log_v2::core(), "feeder: {} terminated", _name); - // in order to avoid circular owning - _muxer->clear_read_handler(); + SPDLOG_LOGGER_INFO(_logger, "feeder: {} terminated", _name); + + /* The muxer is in a shared_ptr. When the feeder is destroyed, we must be + * sure the muxer won't write data anymore otherwise we will have a segfault. + */ + _muxer->clear_action_on_new_data(); } /** @@ -394,44 +339,40 @@ void feeder::_read_from_stream_timer_handler( break; } if (event) { // event is null if not decoded by bbdo stream - if (log_v2::processing()->level() == spdlog::level::trace) + if (_logger->level() == spdlog::level::trace) SPDLOG_LOGGER_TRACE( - log_v2::processing(), - "feeder '{}': sending 1 event {} from stream to muxer", _name, - *event); + _logger, "feeder '{}': sending 1 event {} from stream to muxer", + _name, *event); else SPDLOG_LOGGER_DEBUG( - log_v2::processing(), - "feeder '{}': sending 1 event {} from stream to muxer", _name, - event->type()); + _logger, "feeder '{}': sending 1 event {} from stream to muxer", + _name, event->type()); events_to_publish.push_back(event); } } } catch (exceptions::shutdown const&) { // Normal termination. - SPDLOG_LOGGER_INFO(log_v2::core(), "from client feeder '{}' shutdown", - _name); + SPDLOG_LOGGER_INFO(_logger, "from client feeder '{}' shutdown", _name); _muxer->write(events_to_publish); // _client->read shutdown => we stop read and don't restart the read from // stream timer return; } catch (const exceptions::connection_closed&) { set_last_error(""); - SPDLOG_LOGGER_INFO(log_v2::processing(), "feeder '{}', connection closed", - _name); + SPDLOG_LOGGER_INFO(_logger, "feeder '{}', connection closed", _name); _muxer->write(events_to_publish); stop(); return; } catch (const std::exception& e) { set_last_error(e.what()); - SPDLOG_LOGGER_ERROR(log_v2::processing(), - "from client feeder '{}' error:{} ", _name, e.what()); + SPDLOG_LOGGER_ERROR(_logger, "from client feeder '{}' error:{} ", _name, + e.what()); _muxer->write(events_to_publish); stop(); return; } catch (...) { - SPDLOG_LOGGER_ERROR(log_v2::processing(), + SPDLOG_LOGGER_ERROR(_logger, "from client feeder: unknown error occured while " "processing client '{}'", _name); diff --git a/broker/core/src/stats/center.cc b/broker/core/src/stats/center.cc index 4723a6081ea..9eb22c4589b 100644 --- a/broker/core/src/stats/center.cc +++ b/broker/core/src/stats/center.cc @@ -1,5 +1,5 @@ /** - * Copyright 2020-2022 Centreon + * Copyright 2020-2024 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,36 +18,37 @@ #include "com/centreon/broker/stats/center.hh" +#include #include #include #include "com/centreon/broker/config/applier/modules.hh" #include "com/centreon/broker/config/applier/state.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/filesystem.hh" #include "com/centreon/broker/version.hh" +#include "common/log_v2/log_v2.hh" #include "com/centreon/common/pool.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::stats; using namespace google::protobuf::util; using namespace com::centreon::broker::modules; +using com::centreon::common::log_v2::log_v2; -center* center::_instance{nullptr}; +std::shared_ptr
center::_instance; -center& center::instance() { +std::shared_ptr
center::instance_ptr() { assert(_instance); - return *_instance; + return _instance; } void center::load() { - if (_instance == nullptr) - _instance = new center(); + if (!_instance) + _instance = std::make_shared
(); } void center::unload() { - delete _instance; - _instance = nullptr; + _instance.reset(); } center::center() { @@ -84,7 +85,7 @@ center::center() { * @return A pointer to the engine statistics. */ EngineStats* center::register_engine() { - std::lock_guard lck(_stats_m); + absl::MutexLock lck(&_stats_m); return _stats.mutable_processing()->mutable_engine(); } @@ -98,12 +99,12 @@ SqlConnectionStats* center::connection(size_t idx) { * @return A pointer to the connection statistics. */ SqlConnectionStats* center::add_connection() { - std::lock_guard lck(_stats_m); + absl::MutexLock lck(&_stats_m); return _stats.mutable_sql_manager()->add_connections(); } void center::remove_connection(SqlConnectionStats* stats) { - std::lock_guard lck(_stats_m); + absl::MutexLock lck(&_stats_m); auto* c = _stats.mutable_sql_manager()->mutable_connections(); for (auto it = c->begin(); it != c->end(); ++it) { if (&*it == stats) { @@ -123,7 +124,7 @@ void center::remove_connection(SqlConnectionStats* stats) { * @return true on success (it never fails). */ void center::unregister_muxer(const std::string& name) { - std::lock_guard lck(_stats_m); + absl::MutexLock lck(&_stats_m); _stats.mutable_processing()->mutable_muxers()->erase(name); } @@ -139,7 +140,7 @@ void center::update_muxer(std::string name, std::string queue_file, uint32_t size, uint32_t unack) { - std::lock_guard lck(_stats_m); + absl::MutexLock lck(&_stats_m); auto ms = &(*_stats.mutable_processing()->mutable_muxers())[std::move(name)]; if (ms) { ms->mutable_queue_file()->set_name(std::move(queue_file)); @@ -151,7 +152,7 @@ void center::update_muxer(std::string name, void center::init_queue_file(std::string muxer, std::string queue_file, uint32_t max_file_size) { - std::lock_guard lck(_stats_m); + absl::MutexLock lck(&_stats_m); auto qfs = (&(*_stats.mutable_processing()->mutable_muxers())[std::move(muxer)]) ->mutable_queue_file(); @@ -161,111 +162,6 @@ void center::init_queue_file(std::string muxer, } } -/** - * @brief When a feeder needs to write statistics, it primarily has to - * call this function to be registered in the statistic center and to get - * a pointer for its statistics. It is prohibited to directly write into this - * pointer. We must use the center member functions for this purpose. - * - * @param name - * - * @return A pointer to the feeder statistics. - */ -// FeederStats* center::register_feeder(EndpointStats* ep_stats, -// const std::string& name) { -// std::promise p; -// std::future retval = p.get_future(); -// _strand.post([this, ep_stats, &p, &name] { -// auto ep = &(*ep_stats->mutable_feeder())[name]; -// p.set_value(ep); -// }); -// return retval.get(); -//} - -// bool center::unregister_feeder(EndpointStats* ep_stats, -// const std::string& name) { -// std::promise p; -// std::future retval = p.get_future(); -// _strand.post([this, ep_stats, &p, &name] { -// auto ep = (*ep_stats->mutable_feeder()).erase(name); -// p.set_value(true); -// }); -// return retval.get(); -//} - -// MysqlConnectionStats* center::register_mysql_connection( -// MysqlManagerStats* stats) { -// std::promise p; -// std::future retval = p.get_future(); -// _strand.post([this, stats, &p] { -// auto ep = stats->add_connections(); -// p.set_value(ep); -// }); -// return retval.get(); -//} - -// bool center::unregister_mysql_connection(MysqlConnectionStats* c) { -// std::promise p; -// std::future retval = p.get_future(); -// _strand.post([this, c, &p] { -// for (auto -// it = -// _stats.mutable_mysql_manager()->mutable_connections()->begin(), -// end = -// _stats.mutable_mysql_manager()->mutable_connections()->end(); -// it != end; ++it) { -// if (&(*it) == c) { -// _stats.mutable_mysql_manager()->mutable_connections()->erase(it); -// break; -// } -// } -// p.set_value(true); -// }); -// return retval.get(); -//} - -/** - * @brief When an endpoint needs to write statistics, it primarily has to - * call this function to be registered in the statistic center and to get - * a pointer to its statistics. It is prohibited to directly write into this - * pointer. We must use the center member function for this purpose. - * - * @param name - * - * @return A pointer to the endpoint statistics. - */ -// EndpointStats* center::register_endpoint(const std::string& name) { -// std::promise p; -// std::future retval = p.get_future(); -// _strand.post([this, &p, &name] { -// auto ep = _stats.add_endpoint(); -// ep->set_name(name); -// *ep->mutable_memory_file_path() = fmt::format( -// "{}.memory.{}", config::applier::state::instance().cache_dir(), name); -// *ep->mutable_queue_file_path() = fmt::format( -// "{}.queue.{}", config::applier::state::instance().cache_dir(), name); -// -// p.set_value(ep); -// }); -// return retval.get(); -//} - -// bool center::unregister_endpoint(const std::string& name) { -// std::promise p; -// std::future retval = p.get_future(); -// _strand.post([this, &p, &name] { -// for (auto it = _stats.mutable_endpoint()->begin(); -// it != _stats.mutable_endpoint()->end(); ++it) { -// if (it->name() == name) { -// _stats.mutable_endpoint()->erase(it); -// break; -// } -// } -// p.set_value(true); -// }); -// return retval.get(); -//} - /** * @brief To allow the conflict manager to send statistics, it has to call this * function to get a pointer to its statistics container. @@ -275,28 +171,10 @@ void center::init_queue_file(std::string muxer, * @return A pointer to the conflict_manager statistics. */ ConflictManagerStats* center::register_conflict_manager() { - std::lock_guard lck(_stats_m); + absl::MutexLock lck(&_stats_m); return _stats.mutable_conflict_manager(); } -/** - * @brief To allow the conflict manager to send statistics, it has to call this - * function to get a pointer to its statistics container. - * It is prohibited to directly write into the returned pointer. We must use - * the center member functions for this purpose. - * - * @return A pointer to the module statistics. - */ -// ModuleStats* center::register_modules() { -// std::promise p; -// std::future retval = p.get_future(); -// _strand.post([this, &p] { -// auto m = _stats.add_modules(); -// p.set_value(m); -// }); -// return retval.get(); -//} - /** * @brief Convert the protobuf statistics object to a json string. * @@ -305,9 +183,8 @@ ConflictManagerStats* center::register_conflict_manager() { std::string center::to_string() { const JsonPrintOptions options; std::string retval; - std::time_t now; - time(&now); - std::lock_guard lck(_stats_m); + std::time_t now = time(nullptr); + absl::MutexLock lck(&_stats_m); _json_stats_file_creation = now; _stats.set_now(now); MessageToJsonString(_stats, &retval, options); @@ -315,7 +192,7 @@ std::string center::to_string() { } void center::get_sql_manager_stats(SqlManagerStats* response, int32_t id) { - std::lock_guard lck(_stats_m); + absl::MutexLock lck(&_stats_m); if (id == -1) *response = _stats.sql_manager(); else { @@ -326,12 +203,12 @@ void center::get_sql_manager_stats(SqlManagerStats* response, int32_t id) { } void center::get_sql_connection_size(GenericSize* response) { - std::lock_guard lck(_stats_m); + absl::MutexLock lck(&_stats_m); response->set_size(_stats.sql_manager().connections().size()); } void center::get_conflict_manager_stats(ConflictManagerStats* response) { - std::lock_guard lck(_stats_m); + absl::MutexLock lck(&_stats_m); *response = _stats.conflict_manager(); } @@ -340,7 +217,7 @@ int center::get_json_stats_file_creation(void) { } bool center::muxer_stats(const std::string& name, MuxerStats* response) { - std::lock_guard lck(_stats_m); + absl::MutexLock lck(&_stats_m); if (!_stats.processing().muxers().contains(name)) return false; else { @@ -350,17 +227,17 @@ bool center::muxer_stats(const std::string& name, MuxerStats* response) { } MuxerStats* center::muxer_stats(const std::string& name) { - std::lock_guard lck(_stats_m); + absl::MutexLock lck(&_stats_m); return &(*_stats.mutable_processing()->mutable_muxers())[name]; } void center::get_processing_stats(ProcessingStats* response) { - std::lock_guard lck(_stats_m); + absl::MutexLock lck(&_stats_m); *response = _stats.processing(); } void center::clear_muxer_queue_file(const std::string& name) { - std::lock_guard lck(_stats_m); + absl::MutexLock lck(&_stats_m); if (_stats.processing().muxers().contains(name)) _stats.mutable_processing() ->mutable_muxers() @@ -370,11 +247,11 @@ void center::clear_muxer_queue_file(const std::string& name) { } void center::lock() { - _stats_m.lock(); + _stats_m.Lock(); } void center::unlock() { - _stats_m.unlock(); + _stats_m.Unlock(); } const BrokerStats& center::stats() const { diff --git a/broker/core/src/time/timerange.cc b/broker/core/src/time/timerange.cc index 9ded9800162..6c6352f0cdc 100644 --- a/broker/core/src/time/timerange.cc +++ b/broker/core/src/time/timerange.cc @@ -1,27 +1,28 @@ /** -* Copyright 2011-2013 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2013 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/time/timerange.hh" #include -#include "com/centreon/broker/log_v2.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::time; +using log_v2 = com::centreon::common::log_v2::log_v2; /** * Constructor. @@ -163,8 +164,8 @@ uint64_t timerange::end_hour() const throw() { * * @return The minute when the timerange ends. */ -uint64_t timerange::end_minute() const throw() { - return ((_end / 60) % 60); +uint64_t timerange::end_minute() const noexcept { + return (_end / 60) % 60; } /** @@ -187,7 +188,7 @@ bool timerange::to_time_t(struct tm const& midnight, my_tm.tm_hour = end_hour(); my_tm.tm_min = end_minute(); range_end = mktime(&my_tm); - return (true); + return true; } static bool _build_time_t(const std::string_view& time_str, uint64_t& ret) { @@ -195,6 +196,7 @@ static bool _build_time_t(const std::string_view& time_str, uint64_t& ret) { const char* begin_str = time_str.data(); char* endptr; char* endptr1; + auto logger = log_v2::instance().get(log_v2::CORE); // move cursor while we meet blanks while (std::isspace(*begin_str)) { @@ -204,18 +206,16 @@ static bool _build_time_t(const std::string_view& time_str, uint64_t& ret) { uint64_t hours = strtoull(begin_str, &endptr, 10); if (endptr == begin_str || endptr + 2 >= endc || *endptr != ':') { - log_v2::core()->error( - "parser timeranges: error while reading hours '{}' at {}.", begin_str, - endptr - begin_str); + logger->error("parser timeranges: error while reading hours '{}' at {}.", + begin_str, endptr - begin_str); return false; } uint64_t minutes = strtoull(endptr + 1, &endptr1, 10); if (endptr1 == endptr + 1) { - log_v2::core()->error( - "parser timeranges: error while reading minutes '{}' at {}.", begin_str, - endptr1 - begin_str); + logger->error("parser timeranges: error while reading minutes '{}' at {}.", + begin_str, endptr1 - begin_str); return false; } @@ -225,7 +225,7 @@ static bool _build_time_t(const std::string_view& time_str, uint64_t& ret) { } if (endptr1 != endc) { - log_v2::core()->error( + logger->error( "parser timeranges: error while reading end " "of your timerange '{}' at {}.", begin_str, endptr1 - begin_str); diff --git a/broker/core/test/bbdo/output.cc b/broker/core/test/bbdo/output.cc index c05251f6062..d0831d3a51d 100644 --- a/broker/core/test/bbdo/output.cc +++ b/broker/core/test/bbdo/output.cc @@ -24,16 +24,16 @@ #include "com/centreon/broker/config/applier/init.hh" #include "com/centreon/broker/config/applier/modules.hh" #include "com/centreon/broker/io/raw.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/lua/macro_cache.hh" #include "com/centreon/broker/misc/string.hh" #include "com/centreon/broker/misc/variant.hh" #include "com/centreon/broker/neb/instance.hh" #include "com/centreon/broker/persistent_file.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::misc; - +using com::centreon::common::log_v2::log_v2; class into_memory : public io::stream { public: @@ -67,23 +67,27 @@ class into_memory : public io::stream { }; class OutputTest : public ::testing::Test { + protected: + std::shared_ptr _logger; + public: void SetUp() override { + _logger = log_v2::instance().get(log_v2::CORE); io::data::broker_id = 0; try { config::applier::init(0, "broker_test", 0); } catch (std::exception const& e) { (void)e; } - std::shared_ptr pcache( - std::make_shared("/tmp/broker_test_cache")); + std::shared_ptr pcache(std::make_shared( + "/tmp/broker_test_cache", log_v2::instance().get(log_v2::CORE))); } void TearDown() override { // The cache must be destroyed before the applier deinit() call. config::applier::deinit(); ::remove("/tmp/broker_test_cache"); - ::remove(log_v2::instance()->log_name().c_str()); + ::remove(log_v2::instance().filename().c_str()); } }; @@ -91,7 +95,7 @@ class OutputTest : public ::testing::Test { // Then this event is translated into a Lua table and sent to the lua write() // function. TEST_F(OutputTest, WriteService) { - config::applier::modules modules; + config::applier::modules modules(_logger); modules.load_file("./broker/neb/10-neb.so"); std::shared_ptr svc(std::make_shared()); @@ -136,7 +140,7 @@ TEST_F(OutputTest, WriteService) { } TEST_F(OutputTest, WriteLongService) { - config::applier::modules modules; + config::applier::modules modules(_logger); modules.load_file("./broker/neb/10-neb.so"); auto svc = std::make_shared(); @@ -184,7 +188,7 @@ TEST_F(OutputTest, WriteLongService) { } TEST_F(OutputTest, WriteReadService) { - config::applier::modules modules; + config::applier::modules modules(_logger); modules.load_file("./broker/neb/10-neb.so"); std::shared_ptr svc(new neb::service); @@ -228,7 +232,7 @@ TEST_F(OutputTest, WriteReadService) { } TEST_F(OutputTest, ShortPersistentFile) { - config::applier::modules modules; + config::applier::modules modules(_logger); modules.load_file("./broker/neb/10-neb.so"); std::shared_ptr svc(new neb::service_status); @@ -273,7 +277,7 @@ TEST_F(OutputTest, ShortPersistentFile) { } TEST_F(OutputTest, LongPersistentFile) { - config::applier::modules modules; + config::applier::modules modules(_logger); modules.load_file("./broker/neb/10-neb.so"); std::shared_ptr svc(new neb::service); @@ -317,7 +321,7 @@ TEST_F(OutputTest, LongPersistentFile) { } TEST_F(OutputTest, WriteReadBadChksum) { - config::applier::modules modules; + config::applier::modules modules(_logger); modules.load_file("./broker/neb/10-neb.so"); std::shared_ptr svc(new neb::service); @@ -356,7 +360,7 @@ TEST_F(OutputTest, WriteReadBadChksum) { } TEST_F(OutputTest, ServiceTooShort) { - config::applier::modules modules; + config::applier::modules modules(_logger); modules.load_file("./broker/neb/10-neb.so"); std::shared_ptr svc(new neb::service); @@ -402,7 +406,7 @@ TEST_F(OutputTest, ServiceTooShort) { } TEST_F(OutputTest, ServiceTooShortAndAGoodOne) { - config::applier::modules modules; + config::applier::modules modules(_logger); modules.load_file("./broker/neb/10-neb.so"); std::shared_ptr svc(new neb::service); diff --git a/broker/core/test/cache/global_cache_test.cc b/broker/core/test/cache/global_cache_test.cc index 98226e5233c..d65a518cf71 100644 --- a/broker/core/test/cache/global_cache_test.cc +++ b/broker/core/test/cache/global_cache_test.cc @@ -20,15 +20,17 @@ #include #include "com/centreon/broker/cache/global_cache_data.hh" -#include "com/centreon/broker/log_v2.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::cache; +using log_v2 = com::centreon::common::log_v2::log_v2; + class global_cache_test : public testing::Test { public: static void SetUpTestSuite() { - log_v2::core()->set_level(spdlog::level::info); + log_v2::instance().get(log_v2::CORE)->set_level(spdlog::level::trace); srand(time(nullptr)); } }; @@ -368,7 +370,8 @@ TEST_F(global_cache_test, Huge) { unsigned ii; - SPDLOG_LOGGER_INFO(log_v2::core(), "begin construct cache"); + SPDLOG_LOGGER_INFO(log_v2::instance().get(log_v2::CORE), + "begin construct cache"); // 10000 hosts with 30 services with 20 metrics unsigned serv_id = 1; unsigned resource_id = 1; @@ -390,11 +393,13 @@ TEST_F(global_cache_test, Huge) { } } } - SPDLOG_LOGGER_INFO(log_v2::core(), "end construct cache"); + SPDLOG_LOGGER_INFO(log_v2::instance().get(log_v2::CORE), + "end construct cache"); // we search 10000 metrics infos unsigned metric_info_increment = metric_id / 10000; unsigned id_search = 0; for (ii = 0; ii < 10000; ++ii, id_search += metric_info_increment) obj->get_metric_info(id_search); - SPDLOG_LOGGER_INFO(log_v2::core(), "end of 10000 metric search"); + SPDLOG_LOGGER_INFO(log_v2::instance().get(log_v2::CORE), + "end of 10000 metric search"); } diff --git a/broker/core/test/config/parser.cc b/broker/core/test/config/parser.cc index 77663274d6b..4a7d3b5e67c 100644 --- a/broker/core/test/config/parser.cc +++ b/broker/core/test/config/parser.cc @@ -256,8 +256,8 @@ TEST(parser, log) { ASSERT_EQ(s.event_queue_max_size(), 100000); ASSERT_EQ(s.command_file(), "/var/lib/centreon-broker/command.sock"); ASSERT_EQ(s.cache_directory(), "/tmp/"); - ASSERT_EQ(s.log_conf().directory, "/tmp"); - ASSERT_EQ(s.log_conf().max_size, 0u); + ASSERT_EQ(s.log_conf().dirname(), "/tmp"); + ASSERT_EQ(s.log_conf().max_size(), 0u); } TEST(parser, logBadFilename) { @@ -354,10 +354,10 @@ TEST(parser, logDefaultDir) { // Remove temporary file. ::remove(config_file.c_str()); - ASSERT_EQ(s.log_conf().directory, "/tmp"); - ASSERT_EQ(s.log_conf().filename, "toto"); - ASSERT_EQ(s.log_conf().max_size, 12345u); - ASSERT_EQ(s.log_conf().loggers.size(), 2u); + ASSERT_EQ(s.log_conf().dirname(), "/tmp"); + ASSERT_EQ(s.log_conf().filename(), "toto"); + ASSERT_EQ(s.log_conf().max_size(), 12345u); + ASSERT_EQ(s.log_conf().loggers().size(), 2u); } TEST(parser, logBadMaxSize) { @@ -941,8 +941,8 @@ TEST(parser, grpc_full) { ASSERT_EQ(s.event_queue_max_size(), 100000); ASSERT_EQ(s.command_file(), "/var/lib/centreon-broker/command.sock"); ASSERT_EQ(s.cache_directory(), "/tmp/"); - ASSERT_EQ(s.log_conf().directory, "/tmp"); - ASSERT_EQ(s.log_conf().max_size, 0u); + ASSERT_EQ(s.log_conf().dirname(), "/tmp"); + ASSERT_EQ(s.log_conf().max_size(), 0u); } TEST(parser, grpc_in_error) { @@ -1164,7 +1164,7 @@ TEST(parser, boolean1) { ::remove(config_file.c_str()); // Check global params - ASSERT_TRUE(s.log_conf().log_pid); + ASSERT_TRUE(s.log_conf().log_pid()); } TEST(parser, boolean2) { @@ -1254,5 +1254,5 @@ TEST(parser, boolean2) { ::remove(config_file.c_str()); // Check global params - ASSERT_FALSE(s.log_conf().log_pid); + ASSERT_FALSE(s.log_conf().log_pid()); } diff --git a/broker/core/test/main.cc b/broker/core/test/main.cc index 4b016a4ab81..9d819272489 100644 --- a/broker/core/test/main.cc +++ b/broker/core/test/main.cc @@ -17,11 +17,14 @@ * */ #include + #include "com/centreon/broker/config/applier/state.hh" #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/io/protocols.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/common/pool.hh" +#include "common/log_v2/log_v2.hh" + +using com::centreon::common::log_v2::log_v2; std::shared_ptr g_io_context = std::make_shared(); @@ -54,9 +57,9 @@ int main(int argc, char* argv[]) { // Set specific environment. testing::AddGlobalTestEnvironment(new CentreonBrokerEnvironment()); - com::centreon::broker::log_v2::load(g_io_context); + log_v2::load("test"); com::centreon::common::pool::load(g_io_context, - com::centreon::broker::log_v2::core()); + log_v2::instance().get(log_v2::CORE)); com::centreon::common::pool::set_pool_size(0); // Run all tests. diff --git a/broker/core/test/misc/perfdata.cc b/broker/core/test/misc/perfdata.cc index da54dd001ea..bd0169043c9 100644 --- a/broker/core/test/misc/perfdata.cc +++ b/broker/core/test/misc/perfdata.cc @@ -24,8 +24,10 @@ #include "com/centreon/broker/config/applier/init.hh" #include "com/centreon/broker/misc/misc.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; +using com::centreon::common::log_v2::log_v2; /** * Check that the perfdata assignment operator works properly. @@ -193,9 +195,13 @@ TEST(MiscPerfdata, DefaultCtor) { } class MiscParserParsePerfdata : public testing::Test { + protected: + std::shared_ptr _logger; + public: void SetUp() override { config::applier::init(0, "test_broker", 0); + _logger = log_v2::instance().get(log_v2::PERFDATA); } void TearDown() override { config::applier::deinit(); }; }; @@ -206,7 +212,7 @@ class MiscParserParsePerfdata : public testing::Test { TEST_F(MiscParserParsePerfdata, Simple1) { // Parse perfdata. std::list lst{misc::parse_perfdata( - 0, 0, "time=2.45698s;2.000000;5.000000;0.000000;10.000000")}; + 0, 0, "time=2.45698s;2.000000;5.000000;0.000000;10.000000", _logger)}; // Assertions. ASSERT_EQ(lst.size(), 1u); @@ -228,7 +234,7 @@ TEST_F(MiscParserParsePerfdata, Simple1) { TEST_F(MiscParserParsePerfdata, Simple2) { // Parse perfdata. std::list list{ - misc::parse_perfdata(0, 0, "'ABCD12E'=18.00%;15:;10:;0;100")}; + misc::parse_perfdata(0, 0, "'ABCD12E'=18.00%;15:;10:;0;100", _logger)}; // Assertions. ASSERT_EQ(list.size(), 1u); @@ -253,7 +259,8 @@ TEST_F(MiscParserParsePerfdata, Complex1) { 0, 0, "time=2.45698s;;nan;;inf d[metric]=239765B/s;5;;-inf; " "infotraffic=18x;;;; a[foo]=1234;10;11: c[bar]=1234;~:10;20:30 " - "baz=1234;@10:20; 'q u x'=9queries_per_second;@10:;@5:;0;100")}; + "baz=1234;@10:20; 'q u x'=9queries_per_second;@10:;@5:;0;100", + _logger)}; // Assertions. ASSERT_EQ(list.size(), 7u); @@ -353,7 +360,7 @@ TEST_F(MiscParserParsePerfdata, Loop) { for (uint32_t i(0); i < 10000; ++i) { // Parse perfdata string. list = misc::parse_perfdata( - 0, 0, "c[time]=2.45698s;2.000000;5.000000;0.000000;10.000000"); + 0, 0, "c[time]=2.45698s;2.000000;5.000000;0.000000;10.000000", _logger); // Assertions. ASSERT_EQ(list.size(), 1u); @@ -378,7 +385,7 @@ TEST_F(MiscParserParsePerfdata, Loop) { // When parse_perfdata() is called with an invalid string TEST_F(MiscParserParsePerfdata, Incorrect1) { // Attempt to parse perfdata. - auto list{misc::parse_perfdata(0, 0, "metric1= 10 metric2=42")}; + auto list{misc::parse_perfdata(0, 0, "metric1= 10 metric2=42", _logger)}; ASSERT_EQ(list.size(), 1u); ASSERT_EQ(list.back().name(), "metric2"); ASSERT_EQ(list.back().value(), 42); @@ -388,13 +395,13 @@ TEST_F(MiscParserParsePerfdata, Incorrect1) { // When parse_perfdata() is called with a metric without value but with unit TEST_F(MiscParserParsePerfdata, Incorrect2) { // Then - auto list{misc::parse_perfdata(0, 0, "metric=kb/s")}; + auto list{misc::parse_perfdata(0, 0, "metric=kb/s", _logger)}; ASSERT_TRUE(list.empty()); } TEST_F(MiscParserParsePerfdata, LabelWithSpaces) { // Parse perfdata. - auto lst{misc::parse_perfdata(0, 0, " 'foo bar '=2s;2;5;;")}; + auto lst{misc::parse_perfdata(0, 0, " 'foo bar '=2s;2;5;;", _logger)}; // Assertions. ASSERT_EQ(lst.size(), 1u); @@ -413,7 +420,7 @@ TEST_F(MiscParserParsePerfdata, LabelWithSpaces) { TEST_F(MiscParserParsePerfdata, LabelWithSpacesMultiline) { // Parse perfdata. - auto lst{misc::parse_perfdata(0, 0, " 'foo bar '=2s;2;5;;")}; + auto lst{misc::parse_perfdata(0, 0, " 'foo bar '=2s;2;5;;", _logger)}; // Assertions. ASSERT_EQ(lst.size(), 1u); @@ -437,7 +444,8 @@ TEST_F(MiscParserParsePerfdata, Complex2) { "' \n time'=2,45698s;;nan;;inf d[metric]=239765B/s;5;;-inf; " "g[test]=8x;;;;" " infotraffic=18,6x;;;; a[foo]=1234,17;10;11: " - "c[bar]=1234,147;~:10;20:30")}; + "c[bar]=1234,147;~:10;20:30", + _logger)}; // Assertions. ASSERT_EQ(list.size(), 6u); @@ -518,7 +526,7 @@ TEST_F(MiscParserParsePerfdata, Complex2) { // When parse_perfdata() is called with a valid perfdata string // Then perfdata are returned in a list TEST_F(MiscParserParsePerfdata, SimpleWithR) { - auto lst{misc::parse_perfdata(0, 0, "'total'=5;;;0;\r")}; + auto lst{misc::parse_perfdata(0, 0, "'total'=5;;;0;\r", _logger)}; // Assertions. ASSERT_EQ(lst.size(), 1u); @@ -541,7 +549,7 @@ TEST_F(MiscParserParsePerfdata, SimpleWithR) { // When parse_perfdata() is called with a valid perfdata string // Then perfdata are returned in a list TEST_F(MiscParserParsePerfdata, BadMetric) { - auto lst{misc::parse_perfdata(0, 0, "user1=1 user2=2 =1 user3=3")}; + auto lst{misc::parse_perfdata(0, 0, "user1=1 user2=2 =1 user3=3", _logger)}; // Assertions. ASSERT_EQ(lst.size(), 3u); @@ -554,7 +562,8 @@ TEST_F(MiscParserParsePerfdata, BadMetric) { } TEST_F(MiscParserParsePerfdata, BadMetric1) { - auto lst{misc::parse_perfdata(0, 0, "user1=1 user2=2 user4= user3=3")}; + auto lst{ + misc::parse_perfdata(0, 0, "user1=1 user2=2 user4= user3=3", _logger)}; // Assertions. ASSERT_EQ(lst.size(), 3u); diff --git a/broker/core/test/modules/module.cc b/broker/core/test/modules/module.cc index c095b06524a..ac011d7aa3c 100644 --- a/broker/core/test/modules/module.cc +++ b/broker/core/test/modules/module.cc @@ -21,13 +21,19 @@ #include "com/centreon/broker/config/applier/init.hh" #include "com/centreon/broker/config/applier/modules.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; +using com::centreon::common::log_v2::log_v2; class Modules : public testing::Test { + protected: + std::shared_ptr _logger; + public: void SetUp() override { config::applier::init(0, "test_broker", 0); + _logger = log_v2::instance().get(log_v2::CORE); } void TearDown() override { config::applier::deinit(); } @@ -37,13 +43,13 @@ class Modules : public testing::Test { * Verify that the module version checks work. */ TEST_F(Modules, loadNoVersion) { - config::applier::modules modules; + config::applier::modules modules(_logger); ASSERT_FALSE(modules.load_file(CENTREON_BROKER_TEST_MODULE_PATH "./libnull_module.so")); } TEST_F(Modules, loadBadVersion) { - config::applier::modules modules; + config::applier::modules modules(_logger); ASSERT_FALSE(modules.load_file(CENTREON_BROKER_TEST_MODULE_PATH "./libbad_version_module.so")); } diff --git a/broker/core/test/processing/acceptor.cc b/broker/core/test/processing/acceptor.cc index 7b54a84f8aa..5479d4ca87e 100644 --- a/broker/core/test/processing/acceptor.cc +++ b/broker/core/test/processing/acceptor.cc @@ -22,11 +22,12 @@ #include "com/centreon/broker/config/applier/init.hh" #include "com/centreon/broker/io/raw.hh" #include "com/centreon/broker/multiplexing/muxer_filter.hh" -#include "com/centreon/broker/log_v2.hh" +#include "common/log_v2/log_v2.hh" #include "temporary_endpoint.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::processing; +using com::centreon::common::log_v2::log_v2; class ProcessingTest : public ::testing::Test { public: @@ -37,7 +38,7 @@ class ProcessingTest : public ::testing::Test { (void)e; } - log_v2::core()->set_level(spdlog::level::info); + log_v2::instance().get(log_v2::CORE)->set_level(spdlog::level::info); _endpoint = std::make_shared(); } diff --git a/broker/core/test/processing/feeder.cc b/broker/core/test/processing/feeder.cc index 73c3562b43f..0f9a33fef5e 100644 --- a/broker/core/test/processing/feeder.cc +++ b/broker/core/test/processing/feeder.cc @@ -1,5 +1,5 @@ /** - * Copyright 2020-2021 Centreon (https://www.centreon.com/) + * Copyright 2020-2024 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/broker/core/test/processing/temporary_endpoint.hh b/broker/core/test/processing/temporary_endpoint.hh index 5580526328c..1ff6afe018e 100644 --- a/broker/core/test/processing/temporary_endpoint.hh +++ b/broker/core/test/processing/temporary_endpoint.hh @@ -21,6 +21,7 @@ #define CCB_TEMPORARY_ENDPOINT_HH #include "com/centreon/broker/io/endpoint.hh" +#include "com/centreon/broker/multiplexing/muxer_filter.hh" #include "temporary_stream.hh" namespace com::centreon::broker { @@ -41,7 +42,11 @@ class temporary_endpoint : public io::endpoint { * @param[in] id The temporary id. */ temporary_endpoint(std::string const& id = "") - : io::endpoint(false, {}), _id(id) {} + : io::endpoint(false, + {}, + multiplexing::muxer_filter( + multiplexing::muxer_filter::zero_init())), + _id(id) {} /** * Copy constructor. * @@ -72,6 +77,6 @@ class temporary_endpoint : public io::endpoint { } }; -} +} // namespace com::centreon::broker #endif // !CCB_TEMPORARY_ENDPOINT_HH diff --git a/broker/core/test/rpc/brokerrpc.cc b/broker/core/test/rpc/brokerrpc.cc index f7af312c30e..a0ab4b189ff 100644 --- a/broker/core/test/rpc/brokerrpc.cc +++ b/broker/core/test/rpc/brokerrpc.cc @@ -26,7 +26,6 @@ #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/io/protocols.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/version.hh" using namespace com::centreon; @@ -92,9 +91,10 @@ TEST_F(BrokerRpc, GetMuxerStats) { "unacknowledged_events: " "1790\n"}; - stats::center::instance().update_muxer("mx1", "qufl_", 18u, 1789u); + auto center = stats::center::instance_ptr(); + center->update_muxer("mx1", "qufl_", 18u, 1789u); - stats::center::instance().update_muxer("mx2", "_qufl", 18u, 1790u); + center->update_muxer("mx2", "_qufl", 18u, 1790u); std::list output = execute("GetMuxerStats mx1 mx2"); diff --git a/broker/doc/broker-doc.md b/broker/doc/broker-doc.md index 82ecaaa30f4..89b8587b71b 100644 --- a/broker/doc/broker-doc.md +++ b/broker/doc/broker-doc.md @@ -4,6 +4,10 @@ - [Broker documentation {#mainpage}](#broker-documentation-mainpage) - [Table of content](#table-of-content) + - [BBDO events](#BbdoEvents) + - [Multiplexing](#Multiplexing) + - [Muxer](#Muxer) + - [Engine](#Engine) - [Processing](#processing) - [Feeder](#feeder) - [Initialization](#initialization) @@ -24,9 +28,74 @@ - [Main classes](#main-classes) - [generate\_proto.py](#generate_protopy) +## BBDO events +Broker is a software that gets events on some inputs and sends them on some outputs. We +can apply filters on all these inputs/outputs. + +Events are divided by categories, they are: + * *neb:* For Nagios Event broker. They are the main events received from Engine. + * *bbdo:* They are the cops of the BBDO events. Essentially created by Broker to + control others events. + * *storage:* This category represents all the events created by the sql streams + after transformation of some neb events. + * *dumper:* not used. + * *bam:* the bam events. + * *extcmd:* If you use the Broker API, then the sent commands will generate + such category events. + * *generator:* not used. + * *local:* That is an internal category. **Events here can not pass through + network**. They stay inside the generator software. + * *internal:* Others cops events. They are very few. + +## Multiplexing +### Muxer +A muxer can be plugged to an input or an output stream. +Muxers exchange data through the Engine object. Each muxer holds a shared pointer to the Engine. So the Engine is destroyed when all the muxers are removed from Broker. + +We can send a data `d` to the muxer by using the `write(d)` method. With that method, the Muxer publishes to the Engine the data `d`. And then the Engine stacks on its queue the event. In case, the Engine is running, the task finishes by calling an internal function `_send_to_subscribers()` that empties the queue and sends all the data to each muxer on its own queue. + +So, when a data is written to a muxer, it is stacked on all the muxers using the Engine, even the muxer at the origin of the data. + +The `_send_to_subscribers()` internal function is a complex function. It can take a callback as argument. Let's take a look at it. + +Firstly, it checks if `_sending_to_subscribers` is `true`, that means the action of sending data to subscribers is already running and the function returns. + +If `_sending_to_subscribers` is `false`, it is changed to `true` and a copy of the Engine queue is made as a shared pointer to give it to each muxer. To send that queue, the thread pool is used and its task is just to call the `publish()` method of the muxers to push the events on their stack. +In case of a callback is given as argument, it will be called once all the tasks are finished. + +This callback is rarely used. It is essentially used when we want to be sure that no more data are sent to the subscribers. In this context, the callback is just a promise to wait until all the tasks are finished. We can see this in: +* the `stop()` method of Engine: If we want to stop it, we must be sure that no events have to be written somewhere. +* the `unsubscribe_muxer()` method of Engine: This method removes the muxer from the Engine list of subscribers. So if we remove one muxer from it but there are still events to write into it, we have the risk of an access to a removed muxer. + +#### Muxer filter + +To limit data in muxers, they work with filters. Each muxer is created with two filters: + +* mandatory filter: it contains data types mandatory for the good work of the muxer. Each stream defines its mandatory filter, and when the muxer is created, this filter is transferred to the muxer. +* forbidden filter: This filter declares what event type we don't want to see in the muxer + +From these two filters, and with the configuration given by the user, a map of filters is defined in the muxer and each time an event arrives, we check that the event is authorized to go through the muxer. + +If the user allows events that make part of the forbidden filter, an error message is raised in the logs but the events are forbidden to be coherent with the forbidden filter. If the user doesn't declare events that are mandatory, broker will add them into the filter to allow them. + +### Engine + +The Broker engine is hold by its subscriber muxers. Each one has a shared pointer +to it. So the engine can be removed only when there are no more muxers. + +The engine has an array of weak pointers to these muxers. So when it is time +to stop it, we wait for each muxer to be removed from the array. This is produced +when the muxers themselves are stopped. If there are still data in the engine, they +are saved to an *unprocessed* file that will be loaded on next Broker start. + +The engine class is the root of events dispatching. Events arrive from a stream, +are transfered to a muxer and then to engine (at the root of the tree). +This one then sends events to all its children. Each muxer receives these events +and sends them to its stream. + ## Processing -There are two main classes in the broker Processing: +There are two main classes in the Broker processing: * **failover**: This is mainly used to get events from broker and send them to a stream. @@ -38,9 +107,7 @@ There are two main classes in the broker Processing: A feeder has two roles: -1. The feeder can read events from its muxer. This is the case with a reverse - connections, the feeder gets its events from the broker engine through the - muxer and writes them to the stream client. +1. The feeder can read events from its muxer. This is the case with a reverse connections, the feeder gets its events from the Broker engine through the muxer and writes them to the stream client. 2. The feeder can also read events from its stream client. This is more usual. @@ -53,17 +120,16 @@ A feeder is created with a static function `feeder::create()`. This function: * starts the statistics timer * starts its main loop. -The main loop runs with a thread pool managed by ASIO so don't expect to see -an std::thread somewhere. +The main loop runs with a thread pool managed by ASIO so don't expect to see an std::thread somewhere. A feeder is initialized with: -* name: name of the feeder. -* client: the stream to exchange events with. -* read\_filters: read filters, that is to say events allowed to be read by the +* `name`: name of the feeder. +* `client`: the stream to exchange events with. +* `read_filters`: read filters, that is to say events allowed to be read by the feeder. Events that don't obey to these filters are ignored and thrown away by the feeder. -* write\_filters: same as read filters, but concerning writing. +* `write_filters`: same as `read_filters`, but concerning writing. After the construction, the feeder has its statistics started. Statistics are handled by an ASIO timer, every 5s the handler `feeder::_stat_timer_handler()` is called. @@ -289,4 +355,4 @@ std::shared_ptr create_event_with_data(const std::shared_ptr const& cache); std::shared_ptr open() override; }; -} // namespace graphite - -} +} // namespace com::centreon::broker::graphite #endif // !CCB_GRAPHITE_CONNECTOR_HH diff --git a/broker/graphite/inc/com/centreon/broker/graphite/factory.hh b/broker/graphite/inc/com/centreon/broker/graphite/factory.hh index dfade5ea0b5..07505b3dc83 100644 --- a/broker/graphite/inc/com/centreon/broker/graphite/factory.hh +++ b/broker/graphite/inc/com/centreon/broker/graphite/factory.hh @@ -1,29 +1,28 @@ /* -** Copyright 2014-2015 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ + * Copyright 2014-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_GRAPHITE_FACTORY_HH #define CCB_GRAPHITE_FACTORY_HH #include "com/centreon/broker/io/factory.hh" -namespace com::centreon::broker { +namespace com::centreon::broker::graphite { -namespace graphite { /** * @class factory factory.hh "com/centreon/broker/graphite/factory.hh" * @brief Graphite layer factory. @@ -43,8 +42,6 @@ class factory : public io::factory { bool& is_acceptor, std::shared_ptr cache) const override; }; -} // namespace graphite - -} +} // namespace com::centreon::broker::graphite #endif // !CCB_GRAPHITE_FACTORY_HH diff --git a/broker/graphite/inc/com/centreon/broker/graphite/internal.hh b/broker/graphite/inc/com/centreon/broker/graphite/internal.hh index 92cdeb31d2c..427223fee00 100644 --- a/broker/graphite/inc/com/centreon/broker/graphite/internal.hh +++ b/broker/graphite/inc/com/centreon/broker/graphite/internal.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_GRAPHITE_INTERNAL_HH #define CCB_GRAPHITE_INTERNAL_HH @@ -23,9 +23,8 @@ #include "bbdo/storage.pb.h" #include "com/centreon/broker/io/protobuf.hh" -namespace com::centreon::broker { +namespace com::centreon::broker::storage { -namespace storage { using pb_index_mapping = io::protobuf; @@ -37,7 +36,6 @@ using pb_metric = using pb_status = io::protobuf; -} // namespace storage -} +} // namespace com::centreon::broker::storage #endif // !CCB_GRAPHITE_INTERNAL_HH diff --git a/broker/graphite/inc/com/centreon/broker/graphite/macro_cache.hh b/broker/graphite/inc/com/centreon/broker/graphite/macro_cache.hh index ed0c64af037..84976001bf9 100644 --- a/broker/graphite/inc/com/centreon/broker/graphite/macro_cache.hh +++ b/broker/graphite/inc/com/centreon/broker/graphite/macro_cache.hh @@ -1,35 +1,36 @@ -/* -** Copyright 2015 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2015, 2023-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_GRAPHITE_MACRO_CACHE_HH #define CCB_GRAPHITE_MACRO_CACHE_HH #include + #include "com/centreon/broker/graphite/internal.hh" #include "com/centreon/broker/io/factory.hh" + #include "com/centreon/broker/neb/host.hh" #include "com/centreon/broker/neb/instance.hh" #include "com/centreon/broker/neb/service.hh" #include "com/centreon/broker/persistent_cache.hh" -namespace com::centreon::broker { +namespace com::centreon::broker::graphite { -namespace graphite { /** * @class macro_cache macro_cache.hh * "com/centreon/broker/graphite/macro_cache.hh" @@ -72,8 +73,6 @@ class macro_cache { uint64_t service_id) const; const std::string& get_instance(uint64_t instance_id) const; }; -} // namespace graphite - -} +} // namespace com::centreon::broker::graphite #endif // !CCB_GRAPHITE_MACRO_CACHE_HH diff --git a/broker/graphite/inc/com/centreon/broker/graphite/query.hh b/broker/graphite/inc/com/centreon/broker/graphite/query.hh index 1c7140c2afc..6d76cd0ff61 100644 --- a/broker/graphite/inc/com/centreon/broker/graphite/query.hh +++ b/broker/graphite/inc/com/centreon/broker/graphite/query.hh @@ -1,29 +1,28 @@ -/* -** Copyright 2015,2017 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2015,2017, 2023-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_GRAPHITE_QUERY_HH #define CCB_GRAPHITE_QUERY_HH #include "com/centreon/broker/graphite/macro_cache.hh" -namespace com::centreon::broker { +namespace com::centreon::broker::graphite { -namespace graphite { /** * @class query query.hh "com/centreon/broker/graphite/query.hh" * @brief Query compiling/generation. @@ -79,8 +78,7 @@ class query { void _get_metric_id(io::data const& d, std::ostream& is); void _get_metric_name(io::data const& d, std::ostream& is); }; -} // namespace graphite -} +} // namespace com::centreon::broker::graphite #endif // !CCB_GRAPHITE_QUERY_HH diff --git a/broker/graphite/inc/com/centreon/broker/graphite/stream.hh b/broker/graphite/inc/com/centreon/broker/graphite/stream.hh index 6ba0c55c08d..ef0ff13c2c7 100644 --- a/broker/graphite/inc/com/centreon/broker/graphite/stream.hh +++ b/broker/graphite/inc/com/centreon/broker/graphite/stream.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2015-2017 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2015-2017, 2023-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_GRAPHITE_STREAM_HH #define CCB_GRAPHITE_STREAM_HH @@ -56,9 +56,6 @@ class stream : public io::stream { std::string _status; mutable std::mutex _statusm; - // Cache - macro_cache _cache; - // Query query _metric_query; query _status_query; @@ -67,6 +64,12 @@ class stream : public io::stream { asio::io_context _io_context; asio::ip::tcp::socket _socket; + // Logger + std::shared_ptr _logger; + + // Cache + macro_cache _cache; + // Process metric/status and generate query. bool _process_metric(storage::metric const& me); bool _process_status(storage::status const& st); @@ -94,6 +97,6 @@ class stream : public io::stream { }; } // namespace graphite -} +} // namespace com::centreon::broker #endif // !CCB_GRAPHITE_STREAM_HH diff --git a/broker/graphite/src/connector.cc b/broker/graphite/src/connector.cc index 055fc5b3a24..25e4146bbe0 100644 --- a/broker/graphite/src/connector.cc +++ b/broker/graphite/src/connector.cc @@ -1,20 +1,20 @@ /** -* Copyright 2015,2017 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2015,2017 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/graphite/connector.hh" #include "bbdo/storage/index_mapping.hh" @@ -39,10 +39,15 @@ static constexpr multiplexing::muxer_filter _graphite_stream_filter = { storage::pb_metric_mapping::static_type(), make_type(io::extcmd, extcmd::de_pb_bench)}; +static constexpr multiplexing::muxer_filter _graphite_forbidden_filter = + multiplexing::muxer_filter(_graphite_stream_filter).reverse(); + /** * Default constructor. */ -connector::connector() : io::endpoint(false, _graphite_stream_filter) {} +connector::connector() + : io::endpoint(false, _graphite_stream_filter, _graphite_forbidden_filter) { +} /** * Set connection parameters. diff --git a/broker/graphite/src/macro_cache.cc b/broker/graphite/src/macro_cache.cc index c9e6f062ff1..323b9a0ae29 100644 --- a/broker/graphite/src/macro_cache.cc +++ b/broker/graphite/src/macro_cache.cc @@ -1,25 +1,24 @@ /** -* Copyright 2011-2015, 2019 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2015, 2019-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/graphite/macro_cache.hh" #include "bbdo/storage/index_mapping.hh" #include "bbdo/storage/metric_mapping.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon::broker; @@ -31,7 +30,7 @@ using namespace com::centreon::exceptions; * * @param[in] cache Persistent cache used by the macro cache. */ -macro_cache::macro_cache(std::shared_ptr const& cache) +macro_cache::macro_cache(const std::shared_ptr& cache) : _cache(cache) { if (_cache != nullptr) { std::shared_ptr d; @@ -50,7 +49,7 @@ macro_cache::~macro_cache() { try { _save_to_disk(); } catch (std::exception const& e) { - log_v2::graphite()->error( + _cache->logger()->error( "graphite: macro cache couldn't save data to disk: '{}'", e.what()); } } diff --git a/broker/graphite/src/main.cc b/broker/graphite/src/main.cc index bba5f6c99f6..d7a19e53ad7 100644 --- a/broker/graphite/src/main.cc +++ b/broker/graphite/src/main.cc @@ -1,20 +1,20 @@ /** -* Copyright 2011-2013, 2020-2021 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2013, 2020-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "bbdo/storage/index_mapping.hh" #include "bbdo/storage/metric_mapping.hh" @@ -22,9 +22,10 @@ #include "com/centreon/broker/graphite/stream.hh" #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/io/protocols.hh" -#include "com/centreon/broker/log_v2.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; +using log_v2 = com::centreon::common::log_v2::log_v2; // Load count. static uint32_t instances(0); @@ -65,11 +66,12 @@ bool broker_module_deinit() { void broker_module_init(void const* arg) { (void)arg; + auto logger = log_v2::instance().get(log_v2::GRAPHITE); // Increment instance number. if (!instances++) { // Storage module. - log_v2::graphite()->info("graphite: module for Centreon Broker {}", - CENTREON_BROKER_VERSION); + logger->info("graphite: module for Centreon Broker {}", + CENTREON_BROKER_VERSION); io::events& e(io::events::instance()); diff --git a/broker/graphite/src/query.cc b/broker/graphite/src/query.cc index 7287c420209..0f87a0f62ce 100644 --- a/broker/graphite/src/query.cc +++ b/broker/graphite/src/query.cc @@ -1,29 +1,30 @@ /** -* Copyright 2015-2017 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2015-2017 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/graphite/query.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/string.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::exceptions; using namespace com::centreon::broker::graphite; +using log_v2 = com::centreon::common::log_v2::log_v2; /** * Constructor. @@ -72,10 +73,10 @@ std::string query::generate_metric(storage::pb_metric const& me) { iss << escaped; tmp.str(""); } - } catch (std::exception const& e) { - log_v2::graphite()->error( - "graphite: couldn't generate query for metric {}: {}", - me.obj().metric_id(), e.what()); + } catch (const std::exception& e) { + auto logger = log_v2::instance().get(log_v2::GRAPHITE); + logger->error("graphite: couldn't generate query for metric {}: {}", + me.obj().metric_id(), e.what()); return ""; } @@ -112,9 +113,9 @@ std::string query::generate_status(storage::pb_status const& st) { tmp.str(""); } } catch (std::exception const& e) { - log_v2::graphite()->error( - "graphite: couldn't generate query for status {}: {}", - st.obj().index_id(), e.what()); + auto logger = log_v2::instance().get(log_v2::GRAPHITE); + logger->error("graphite: couldn't generate query for status {}: {}", + st.obj().index_id(), e.what()); return ""; } @@ -175,9 +176,10 @@ void query::_compile_naming_scheme(std::string const& naming_scheme, _compiled_getters.push_back(&query::_get_metric_name); } else if (macro == "$INDEXID$") { _compiled_getters.push_back(&query::_get_index_id); - } else - log_v2::graphite()->info("graphite: unknown macro '{}': ignoring it", - macro); + } else { + auto logger = log_v2::instance().get(log_v2::GRAPHITE); + logger->info("graphite: unknown macro '{}': ignoring it", macro); + } found_macro = end_macro = end_macro + 1; } std::string substr = naming_scheme.substr(end_macro, found_macro - end_macro); diff --git a/broker/graphite/src/stream.cc b/broker/graphite/src/stream.cc index 5aedb77ee38..7e1d22afacf 100644 --- a/broker/graphite/src/stream.cc +++ b/broker/graphite/src/stream.cc @@ -1,35 +1,36 @@ /** -* Copyright 2011-2015,2017 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2015,2017 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/graphite/stream.hh" #include "bbdo/storage/metric.hh" #include "com/centreon/broker/exceptions/shutdown.hh" #include "com/centreon/broker/io/events.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/string.hh" #include "com/centreon/broker/multiplexing/engine.hh" #include "com/centreon/broker/multiplexing/publisher.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace asio; using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::graphite; +using log_v2 = com::centreon::common::log_v2::log_v2; /** * Constructor. @@ -56,10 +57,12 @@ stream::stream(std::string const& metric_naming, _pending_queries{0}, _actual_query{0}, _commit_flag{false}, - _cache{cache}, _metric_query{_metric_naming, escape_string, query::metric, _cache}, _status_query{_status_naming, escape_string, query::status, _cache}, - _socket{_io_context} { + _socket{_io_context}, + _logger{log_v2::instance().get(log_v2::GRAPHITE)}, + _cache{cache} { + _logger->trace("graphite::stream constructor {}", static_cast(this)); // Create the basic HTTP authentification header. if (!_db_user.empty() && !_db_password.empty()) { std::string auth{_db_user}; @@ -107,7 +110,9 @@ stream::stream(std::string const& metric_naming, /** * Destructor. */ -stream::~stream() {} +stream::~stream() { + _logger->trace("graphite::stream destructor {}", static_cast(this)); +} /** * Flush the stream. @@ -115,7 +120,7 @@ stream::~stream() {} * @return Number of events acknowledged. */ int32_t stream::flush() { - log_v2::graphite()->debug("graphite: commiting {} queries", _actual_query); + _logger->debug("graphite: commiting {} queries", _actual_query); int32_t ret(_pending_queries); if (_actual_query != 0) _commit(); @@ -131,8 +136,9 @@ int32_t stream::flush() { * @return the number of acknowledged events. */ int32_t stream::stop() { + _logger->trace("graphite::stream stop {}", static_cast(this)); int32_t retval = flush(); - log_v2::core()->info("graphite stopped with {} events acknowledged", retval); + _logger->info("graphite stopped with {} events acknowledged", retval); return retval; } diff --git a/broker/graphite/test/query.cc b/broker/graphite/test/query.cc index 1aee949183c..d11c739916c 100644 --- a/broker/graphite/test/query.cc +++ b/broker/graphite/test/query.cc @@ -22,12 +22,14 @@ #include "bbdo/storage/index_mapping.hh" #include "bbdo/storage/metric_mapping.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; +using com::centreon::common::log_v2::log_v2; TEST(graphiteQuery, ComplexMetric) { - std::shared_ptr pcache{nullptr}; + std::shared_ptr pcache; graphite::macro_cache cache(pcache); storage::pb_metric m_event; Metric& m = m_event.mut_obj(); @@ -81,7 +83,7 @@ TEST(graphiteQuery, ComplexMetric) { } TEST(graphiteQuery, ComplexStatus) { - std::shared_ptr pcache{nullptr}; + std::shared_ptr pcache; graphite::macro_cache cache(pcache); storage::pb_status s_event; Status& s = s_event.mut_obj(); @@ -133,7 +135,7 @@ TEST(graphiteQuery, ComplexStatus) { } TEST(graphiteQuery, ComplexPbMetric) { - std::shared_ptr pcache{nullptr}; + std::shared_ptr pcache; graphite::macro_cache cache(pcache); storage::pb_metric m_event; Metric& m = m_event.mut_obj(); @@ -186,7 +188,7 @@ TEST(graphiteQuery, ComplexPbMetric) { } TEST(graphiteQuery, ComplexPbStatus) { - std::shared_ptr pcache{nullptr}; + std::shared_ptr pcache; graphite::macro_cache cache(pcache); storage::pb_status s_event; Status& s = s_event.mut_obj(); @@ -237,7 +239,7 @@ TEST(graphiteQuery, ComplexPbStatus) { } TEST(graphiteQuery, Except) { - std::shared_ptr pcache{nullptr}; + std::shared_ptr pcache; graphite::macro_cache cache(pcache); storage::pb_status s; storage::pb_metric m; diff --git a/broker/grpc/CMakeLists.txt b/broker/grpc/CMakeLists.txt index f1bfa4e8dc1..4e8a7fd65dd 100644 --- a/broker/grpc/CMakeLists.txt +++ b/broker/grpc/CMakeLists.txt @@ -21,7 +21,7 @@ set(MODULE_DIR "${PROJECT_SOURCE_DIR}/grpc") set(INC_DIR "${MODULE_DIR}/inc/com/centreon/broker/grpc") set(SRC_DIR "${MODULE_DIR}/src") set(TEST_DIR "${MODULE_DIR}/test") -include_directories(${MODULE_DIR}/inc ${SRC_DIR} ${CMAKE_SOURCE_DIR}/bbdo) +include_directories(${MODULE_DIR}/inc ${SRC_DIR} ${CMAKE_SOURCE_DIR}/bbdo ${CMAKE_SOURCE_DIR}/common) # Sources. set(SOURCES diff --git a/broker/grpc/generate_proto.py b/broker/grpc/generate_proto.py index b1b71cf9948..8bd044ddb9e 100755 --- a/broker/grpc/generate_proto.py +++ b/broker/grpc/generate_proto.py @@ -60,8 +60,10 @@ #include "com/centreon/broker/io/protobuf.hh" #include "com/centreon/broker/grpc/stream.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; +using com::centreon::common::log_v2::log_v2; namespace com::centreon::broker::grpc { namespace detail { @@ -148,7 +150,10 @@ class received_protobuf : public io::protobuf { """ cc_file_create_event_with_data_function_end = """ default: - SPDLOG_LOGGER_ERROR(log_v2::grpc(), "unknown event type: {}", *event); + { + auto logger = log_v2::instance().get(log_v2::GRPC); + SPDLOG_LOGGER_ERROR(logger, "unknown event type: {}", *event); + } } if (ret) { ret->grpc_event.set_destination_id(event->destination_id); @@ -238,9 +243,12 @@ class received_protobuf : public io::protobuf { fp.write(cc_file_begin_content) fp.write(cc_file_protobuf_to_event_function) fp.write(""" default: - SPDLOG_LOGGER_ERROR(log_v2::grpc(), "unknown content type: {} => ignored", - static_cast(stream_content->content_case())); - return std::shared_ptr(); + { + auto logger = log_v2::instance().get(log_v2::GRPC); + SPDLOG_LOGGER_ERROR(logger, "unknown content type: {} => ignored", + static_cast(stream_content->content_case())); + return std::shared_ptr(); + } } } diff --git a/broker/grpc/inc/com/centreon/broker/grpc/acceptor.hh b/broker/grpc/inc/com/centreon/broker/grpc/acceptor.hh index 2f5dcdba872..f130c25766c 100644 --- a/broker/grpc/inc/com/centreon/broker/grpc/acceptor.hh +++ b/broker/grpc/inc/com/centreon/broker/grpc/acceptor.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2022 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_GRPC_ACCEPTOR_HH #define CCB_GRPC_ACCEPTOR_HH diff --git a/broker/grpc/inc/com/centreon/broker/grpc/connector.hh b/broker/grpc/inc/com/centreon/broker/grpc/connector.hh index 5c33a9f9915..3ce464ae6b8 100644 --- a/broker/grpc/inc/com/centreon/broker/grpc/connector.hh +++ b/broker/grpc/inc/com/centreon/broker/grpc/connector.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2022 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_GRPC_CONNECTOR_HH #define CCB_GRPC_CONNECTOR_HH diff --git a/broker/grpc/inc/com/centreon/broker/grpc/factory.hh b/broker/grpc/inc/com/centreon/broker/grpc/factory.hh index 86d4e8af29e..b0e2bcddff0 100644 --- a/broker/grpc/inc/com/centreon/broker/grpc/factory.hh +++ b/broker/grpc/inc/com/centreon/broker/grpc/factory.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2022 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_GRPC_FACTORY_HH #define CCB_GRPC_FACTORY_HH @@ -50,6 +50,6 @@ class factory : public io::factory { }; } // namespace grpc -} +} // namespace com::centreon::broker #endif // !CCB_GRPC_FACTORY_HH diff --git a/broker/grpc/inc/com/centreon/broker/grpc/grpc_bridge.hh b/broker/grpc/inc/com/centreon/broker/grpc/grpc_bridge.hh index 7bc3a8ff58e..37628a846c9 100644 --- a/broker/grpc/inc/com/centreon/broker/grpc/grpc_bridge.hh +++ b/broker/grpc/inc/com/centreon/broker/grpc/grpc_bridge.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2023 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_GRPC_BRIDGE_HH #define CCB_GRPC_BRIDGE_HH @@ -22,16 +22,12 @@ #include "com/centreon/broker/io/protobuf.hh" #include "grpc_stream.pb.h" -namespace com::centreon::broker { - -namespace grpc { +namespace com::centreon::broker::grpc { std::shared_ptr protobuf_to_event(const event_ptr& stream_content); std::shared_ptr create_event_with_data( const std::shared_ptr& event); -}; // namespace grpc - -} // namespace com::centreon::broker +} // namespace com::centreon::broker::grpc #endif diff --git a/broker/grpc/inc/com/centreon/broker/grpc/grpc_config.hh b/broker/grpc/inc/com/centreon/broker/grpc/grpc_config.hh index 61b7230a07f..bbdebd8a45b 100644 --- a/broker/grpc/inc/com/centreon/broker/grpc/grpc_config.hh +++ b/broker/grpc/inc/com/centreon/broker/grpc/grpc_config.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2022 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_GRPC_CONFIG_HH #define CCB_GRPC_CONFIG_HH @@ -90,6 +90,6 @@ class grpc_config { } }; }; // namespace grpc -} +} // namespace com::centreon::broker #endif // !CCB_GRPC_CONFIG_HH diff --git a/broker/grpc/inc/com/centreon/broker/grpc/stream.hh b/broker/grpc/inc/com/centreon/broker/grpc/stream.hh index 4e841c05d17..358b5a5d6e8 100644 --- a/broker/grpc/inc/com/centreon/broker/grpc/stream.hh +++ b/broker/grpc/inc/com/centreon/broker/grpc/stream.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2022 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_GRPC_STREAM_HH__ #define CCB_GRPC_STREAM_HH__ @@ -119,6 +119,9 @@ class stream : public io::stream, // called only by public stop virtual void shutdown(); + /* Logger */ + std::shared_ptr _logger; + public: virtual ~stream(); diff --git a/broker/grpc/precomp_inc/precomp.hh b/broker/grpc/precomp_inc/precomp.hh index 314725225f0..e642bb0c13f 100644 --- a/broker/grpc/precomp_inc/precomp.hh +++ b/broker/grpc/precomp_inc/precomp.hh @@ -52,7 +52,6 @@ namespace asio = boost::asio; #include "com/centreon/broker/io/endpoint.hh" #include "com/centreon/broker/io/raw.hh" #include "com/centreon/broker/io/stream.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/exceptions/msg_fmt.hh" using system_clock = std::chrono::system_clock; diff --git a/broker/grpc/src/acceptor.cc b/broker/grpc/src/acceptor.cc index b18e7369826..a7bf6239bfe 100644 --- a/broker/grpc/src/acceptor.cc +++ b/broker/grpc/src/acceptor.cc @@ -21,9 +21,18 @@ #include "com/centreon/broker/grpc/acceptor.hh" #include "com/centreon/broker/grpc/stream.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::grpc; +using com::centreon::common::log_v2::log_v2; + +static constexpr multiplexing::muxer_filter _grpc_stream_filter = + multiplexing::muxer_filter(multiplexing::muxer_filter::zero_init()); + +static constexpr multiplexing::muxer_filter _grpc_forbidden_filter = + multiplexing::muxer_filter(multiplexing::muxer_filter::zero_init()) + .add_category(io::local); namespace com::centreon::broker::grpc { @@ -98,20 +107,20 @@ service_impl::service_impl(const grpc_config::pointer& conf) : _conf(conf) {} ::grpc::ServerBidiReactor<::com::centreon::broker::stream::CentreonEvent, ::com::centreon::broker::stream::CentreonEvent>* service_impl::exchange(::grpc::CallbackServerContext* context) { + auto logger = log_v2::instance().get(log_v2::GRPC); if (!_conf->get_authorization().empty()) { const auto& metas = context->client_metadata(); auto header_search = metas.lower_bound(authorization_header); if (header_search == metas.end()) { - SPDLOG_LOGGER_ERROR(log_v2::grpc(), "header {} not found from {}", + SPDLOG_LOGGER_ERROR(logger, "header {} not found from {}", authorization_header, context->peer()); return nullptr; } bool found = false; for (; header_search != metas.end() && !found; ++header_search) { if (header_search->first != authorization_header) { - SPDLOG_LOGGER_ERROR(log_v2::grpc(), - "Wrong client authorization token from {}", + SPDLOG_LOGGER_ERROR(logger, "Wrong client authorization token from {}", context->peer()); return nullptr; } @@ -119,8 +128,7 @@ service_impl::exchange(::grpc::CallbackServerContext* context) { } } - SPDLOG_LOGGER_DEBUG(log_v2::grpc(), "connection accepted from {}", - context->peer()); + SPDLOG_LOGGER_DEBUG(logger, "connection accepted from {}", context->peer()); std::shared_ptr next_stream = std::make_shared(_conf, shared_from_this()); @@ -234,9 +242,11 @@ void service_impl::unregister( * @param conf */ acceptor::acceptor(const grpc_config::pointer& conf) - : io::endpoint(true, {}), _service(std::make_shared(conf)) { + : io::endpoint(true, _grpc_stream_filter, _grpc_forbidden_filter), + _service(std::make_shared(conf)) { ::grpc::ServerBuilder builder; + auto logger = log_v2::instance().get(log_v2::GRPC); std::shared_ptr<::grpc::ServerCredentials> server_creds; if (conf->is_crypted() && !conf->get_cert().empty() && !conf->get_key().empty()) { @@ -244,7 +254,7 @@ acceptor::acceptor(const grpc_config::pointer& conf) conf->get_key(), conf->get_cert()}; SPDLOG_LOGGER_INFO( - log_v2::grpc(), + logger, "encrypted server listening on {} cert: {}..., key: {}..., ca: {}....", conf->get_hostport(), conf->get_cert().substr(0, 10), conf->get_key().substr(0, 10), conf->get_ca().substr(0, 10)); @@ -255,7 +265,7 @@ acceptor::acceptor(const grpc_config::pointer& conf) server_creds = ::grpc::SslServerCredentials(ssl_opts); } else { - SPDLOG_LOGGER_INFO(log_v2::grpc(), "unencrypted server listening on {}", + SPDLOG_LOGGER_INFO(logger, "unencrypted server listening on {}", conf->get_hostport()); server_creds = ::grpc::InsecureServerCredentials(); } @@ -276,10 +286,9 @@ acceptor::acceptor(const grpc_config::pointer& conf) GRPC_COMPRESS_LEVEL_HIGH, calc_accept_all_compression_mask()); const char* algo_name; if (grpc_compression_algorithm_name(algo, &algo_name)) - SPDLOG_LOGGER_DEBUG(log_v2::grpc(), "server default compression {}", - algo_name); + SPDLOG_LOGGER_DEBUG(logger, "server default compression {}", algo_name); else - SPDLOG_LOGGER_DEBUG(log_v2::grpc(), "server default compression unknown"); + SPDLOG_LOGGER_DEBUG(logger, "server default compression unknown"); builder.SetDefaultCompressionAlgorithm(algo); builder.SetDefaultCompressionLevel(GRPC_COMPRESS_LEVEL_HIGH); @@ -292,14 +301,15 @@ acceptor::acceptor(const grpc_config::pointer& conf) * */ acceptor::~acceptor() { + auto logger = log_v2::instance().get(log_v2::GRPC); if (_server) { - SPDLOG_LOGGER_DEBUG(log_v2::grpc(), "begin shutdown of acceptor {} ", + SPDLOG_LOGGER_DEBUG(logger, "begin shutdown of acceptor {} ", _service->get_conf()->get_hostport()); _service->shutdown_all_wait(); _service->shutdown_all_accepted(); _server->Shutdown(std::chrono::system_clock::now() + std::chrono::seconds(15)); - SPDLOG_LOGGER_DEBUG(log_v2::grpc(), "end shutdown of acceptor {} ", + SPDLOG_LOGGER_DEBUG(logger, "end shutdown of acceptor {} ", _service->get_conf()->get_hostport()); } } diff --git a/broker/grpc/src/connector.cc b/broker/grpc/src/connector.cc index d9edd5dfd2b..4a2d835873d 100644 --- a/broker/grpc/src/connector.cc +++ b/broker/grpc/src/connector.cc @@ -17,13 +17,23 @@ * */ +#include "com/centreon/broker/multiplexing/muxer_filter.hh" #include "grpc_stream.grpc.pb.h" #include "com/centreon/broker/grpc/connector.hh" #include "com/centreon/broker/grpc/stream.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::grpc; +using log_v2 = com::centreon::common::log_v2::log_v2; + +static constexpr multiplexing::muxer_filter _grpc_stream_filter = + multiplexing::muxer_filter(multiplexing::muxer_filter::zero_init()); + +static constexpr multiplexing::muxer_filter _grpc_forbidden_filter = + multiplexing::muxer_filter(multiplexing::muxer_filter::zero_init()) + .add_category(io::local); /** * @brief Constructor of the connector that will connect to the given host at @@ -33,7 +43,9 @@ using namespace com::centreon::broker::grpc; * @param port The port used for the connection. */ connector::connector(const grpc_config::pointer& conf) - : io::limit_endpoint(false, {}), _conf(conf) { + : io::limit_endpoint(false, _grpc_stream_filter, _grpc_forbidden_filter), + _conf(conf) { + auto logger = log_v2::instance().get(log_v2::GRPC); ::grpc::ChannelArguments args; args.SetInt(GRPC_ARG_KEEPALIVE_PERMIT_WITHOUT_CALLS, 1); args.SetInt(GRPC_ARG_KEEPALIVE_TIME_MS, @@ -49,11 +61,11 @@ connector::connector(const grpc_config::pointer& conf) const char* algo_name; if (grpc_compression_algorithm_name(algo, &algo_name)) { - log_v2::grpc()->debug("client this={:p} activate compression {}", - static_cast(this), algo_name); + logger->debug("client this={:p} activate compression {}", + static_cast(this), algo_name); } else { - log_v2::grpc()->debug("client this={:p} activate compression unknown", - static_cast(this)); + logger->debug("client this={:p} activate compression unknown", + static_cast(this)); } args.SetCompressionAlgorithm(algo); } @@ -62,8 +74,7 @@ connector::connector(const grpc_config::pointer& conf) ::grpc::SslCredentialsOptions ssl_opts = {conf->get_ca(), conf->get_key(), conf->get_cert()}; SPDLOG_LOGGER_INFO( - log_v2::grpc(), - "encrypted connection to {} cert: {}..., key: {}..., ca: {}...", + logger, "encrypted connection to {} cert: {}..., key: {}..., ca: {}...", conf->get_hostport(), conf->get_cert().substr(0, 10), conf->get_key().substr(0, 10), conf->get_ca().substr(0, 10)); creds = ::grpc::SslCredentials(ssl_opts); @@ -75,7 +86,7 @@ connector::connector(const grpc_config::pointer& conf) } #endif } else { - SPDLOG_LOGGER_INFO(log_v2::grpc(), "unencrypted connection to {}", + SPDLOG_LOGGER_INFO(logger, "unencrypted connection to {}", conf->get_hostport()); creds = ::grpc::InsecureChannelCredentials(); } @@ -91,13 +102,13 @@ connector::connector(const grpc_config::pointer& conf) * @return std::unique_ptr */ std::shared_ptr connector::open() { - SPDLOG_LOGGER_INFO(log_v2::grpc(), "Connecting to {}", _conf->get_hostport()); + auto logger = log_v2::instance().get(log_v2::GRPC); + SPDLOG_LOGGER_INFO(logger, "Connecting to {}", _conf->get_hostport()); try { return limit_endpoint::open(); } catch (const std::exception& e) { SPDLOG_LOGGER_DEBUG( - log_v2::tcp(), - "Unable to establish the connection to {} (attempt {}): {}", + logger, "Unable to establish the connection to {} (attempt {}): {}", _conf->get_hostport(), _is_ready_count, e.what()); return nullptr; } diff --git a/broker/grpc/src/factory.cc b/broker/grpc/src/factory.cc index 479db71103a..7631f2b339f 100644 --- a/broker/grpc/src/factory.cc +++ b/broker/grpc/src/factory.cc @@ -27,10 +27,12 @@ #include "com/centreon/broker/grpc/acceptor.hh" #include "com/centreon/broker/grpc/connector.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::grpc; using namespace com::centreon::exceptions; +using com::centreon::common::log_v2::log_v2; /** * Check if a configuration supports this protocol. @@ -98,10 +100,12 @@ io::endpoint* factory::new_endpoint( host = it->second; if (!host.empty() && (std::isspace(host[0]) || std::isspace(host[host.size() - 1]))) { - log_v2::grpc()->error( - "GRPC: 'host' must be a string matching a host, not beginning or " - "ending with spaces for endpoint {}, it contains '{}'", - cfg.name, host); + log_v2::instance() + .get(log_v2::CORE) + ->error( + "GRPC: 'host' must be a string matching a host, not beginning or " + "ending with spaces for endpoint {}, it contains '{}'", + cfg.name, host); throw msg_fmt( "GRPC: invalid host value '{}' defined for endpoint '{}" "', it must not begin or end with spaces.", @@ -112,16 +116,19 @@ io::endpoint* factory::new_endpoint( uint16_t port; it = cfg.params.find("port"); if (it == cfg.params.end()) { - log_v2::grpc()->error("GRPC: no 'port' defined for endpoint '{}'", - cfg.name); + log_v2::instance() + .get(log_v2::CORE) + ->error("GRPC: no 'port' defined for endpoint '{}'", cfg.name); throw msg_fmt("GRPC: no 'port' defined for endpoint '{}'", cfg.name); } { uint32_t port32; if (!absl::SimpleAtoi(it->second, &port32)) { - log_v2::grpc()->error( - "GRPC: 'port' must be an integer and not '{}' for endpoint '{}'", - it->second, cfg.name); + log_v2::instance() + .get(log_v2::CORE) + ->error( + "GRPC: 'port' must be an integer and not '{}' for endpoint '{}'", + it->second, cfg.name); throw msg_fmt("GRPC: invalid port value '{}' defined for endpoint '{}'", it->second, cfg.name); } @@ -147,8 +154,9 @@ io::endpoint* factory::new_endpoint( try { certificate = read_file(it->second); } catch (const std::exception& e) { - SPDLOG_LOGGER_ERROR(log_v2::grpc(), "Failed to open cert file '{}': {}", - it->second, e.what()); + SPDLOG_LOGGER_ERROR(log_v2::instance().get(log_v2::TLS), + "Failed to open cert file '{}': {}", it->second, + e.what()); throw msg_fmt("Failed to open cert file '{}': {}", it->second, e.what()); } } @@ -160,7 +168,7 @@ io::endpoint* factory::new_endpoint( try { certificate_key = read_file(it->second); } catch (const std::exception& e) { - SPDLOG_LOGGER_ERROR(log_v2::grpc(), + SPDLOG_LOGGER_ERROR(log_v2::instance().get(log_v2::TLS), "Failed to open certificate key file '{}': {}", it->second, e.what()); throw msg_fmt("Failed to open certificate key file '{}': {}", it->second, @@ -175,7 +183,7 @@ io::endpoint* factory::new_endpoint( try { certificate_authority = read_file(it->second); } catch (const std::exception& e) { - SPDLOG_LOGGER_ERROR(log_v2::grpc(), + SPDLOG_LOGGER_ERROR(log_v2::instance().get(log_v2::TLS), "Failed to open authority certificate file '{}': {}", it->second, e.what()); throw msg_fmt("Failed to open authority certificate file '{}': {}", @@ -212,9 +220,12 @@ io::endpoint* factory::new_endpoint( it = cfg.params.find("keepalive_interval"); if (it != cfg.params.end()) { if (!absl::SimpleAtoi(it->second, &keepalive_interval)) { - log_v2::grpc()->error( - "GRPC: 'keepalive_interval' field should be an integer and not '{}'", - it->second); + log_v2::instance() + .get(log_v2::CORE) + ->error( + "GRPC: 'keepalive_interval' field should be an integer and not " + "'{}'", + it->second); throw msg_fmt( "GRPC: 'keepalive_interval' field should be an integer and not '{}'", it->second); @@ -239,14 +250,18 @@ io::endpoint* factory::new_endpoint( // Acceptor. if (is_acceptor) { - log_v2::grpc()->debug("GRPC: encryption {} on gRPC server port {}", - encrypted ? "enabled" : "disabled", port); + log_v2::instance() + .get(log_v2::CORE) + ->debug("GRPC: encryption {} on gRPC server port {}", + encrypted ? "enabled" : "disabled", port); endp = std::make_unique(conf); } // Connector. else { - log_v2::grpc()->debug("GRPC: encryption {} on gRPC client port {}", - encrypted ? "enabled" : "disabled", port); + log_v2::instance() + .get(log_v2::CORE) + ->debug("GRPC: encryption {} on gRPC client port {}", + encrypted ? "enabled" : "disabled", port); endp = std::make_unique(conf); } @@ -274,10 +289,12 @@ io::endpoint* factory::_new_endpoint_bbdo_cs( host = it->second; if (!host.empty() && (std::isspace(host[0]) || std::isspace(host[host.size() - 1]))) { - log_v2::grpc()->error( - "GRPC: 'host' must be a string matching a host, not beginning or " - "ending with spaces for endpoint {}, it contains '{}'", - cfg.name, host); + log_v2::instance() + .get(log_v2::CORE) + ->error( + "GRPC: 'host' must be a string matching a host, not beginning or " + "ending with spaces for endpoint {}, it contains '{}'", + cfg.name, host); throw msg_fmt( "GRPC: invalid host value '{}' defined for endpoint '{}" "', it must not begin or end with spaces.", @@ -294,16 +311,19 @@ io::endpoint* factory::_new_endpoint_bbdo_cs( uint16_t port; it = cfg.params.find("port"); if (it == cfg.params.end()) { - log_v2::grpc()->error("GRPC: no 'port' defined for endpoint '{}'", - cfg.name); + log_v2::instance() + .get(log_v2::CORE) + ->error("GRPC: no 'port' defined for endpoint '{}'", cfg.name); throw msg_fmt("GRPC: no 'port' defined for endpoint '{}'", cfg.name); } { uint32_t port32; if (!absl::SimpleAtoi(it->second, &port32)) { - log_v2::grpc()->error( - "GRPC: 'port' must be an integer and not '{}' for endpoint '{}'", - it->second, cfg.name); + log_v2::instance() + .get(log_v2::CORE) + ->error( + "GRPC: 'port' must be an integer and not '{}' for endpoint '{}'", + it->second, cfg.name); throw msg_fmt("GRPC: invalid port value '{}' defined for endpoint '{}'", it->second, cfg.name); } @@ -319,8 +339,9 @@ io::endpoint* factory::_new_endpoint_bbdo_cs( it = cfg.params.find("authorization"); if (it != cfg.params.end()) authorization = it->second; - log_v2::grpc()->debug("GRPC: 'authorization' field contains '{}'", - authorization); + log_v2::instance() + .get(log_v2::CORE) + ->debug("GRPC: 'authorization' field contains '{}'", authorization); // Find ca_name token (if exists). std::string ca_name; @@ -330,15 +351,18 @@ io::endpoint* factory::_new_endpoint_bbdo_cs( if (it != cfg.params.end()) ca_name = it->second; - log_v2::grpc()->debug("GRPC: 'ca_name' field contains '{}'", ca_name); + log_v2::instance() + .get(log_v2::CORE) + ->debug("GRPC: 'ca_name' field contains '{}'", ca_name); bool encryption = false; it = cfg.params.find("encryption"); if (it != cfg.params.end()) { if (!absl::SimpleAtob(it->second, &encryption)) { - log_v2::grpc()->error( - "GRPC: 'encryption' field should be a boolean and not '{}'", - it->second); + log_v2::instance() + .get(log_v2::CORE) + ->error("GRPC: 'encryption' field should be a boolean and not '{}'", + it->second); throw msg_fmt("GRPC: 'encryption' field should be a boolean and not '{}'", it->second); } @@ -352,15 +376,16 @@ io::endpoint* factory::_new_endpoint_bbdo_cs( try { private_key = read_file(it->second); } catch (const std::exception& e) { - SPDLOG_LOGGER_ERROR(log_v2::grpc(), + SPDLOG_LOGGER_ERROR(log_v2::instance().get(log_v2::TLS), "Failed to open private key file '{}': {}", it->second, e.what()); throw msg_fmt("Failed to open private key file '{}': {}", it->second, e.what()); } } else - log_v2::grpc()->warn( - "GRPC: 'private_key' ignored since 'encryption' is disabled"); + log_v2::instance() + .get(log_v2::CORE) + ->warn("GRPC: 'private_key' ignored since 'encryption' is disabled"); } // Certificate. @@ -371,15 +396,16 @@ io::endpoint* factory::_new_endpoint_bbdo_cs( try { certificate = read_file(it->second); } catch (const std::exception& e) { - SPDLOG_LOGGER_ERROR(log_v2::grpc(), + SPDLOG_LOGGER_ERROR(log_v2::instance().get(log_v2::TLS), "Failed to open certificate file '{}': {}", it->second, e.what()); throw msg_fmt("Failed to open certificate file '{}': {}", it->second, e.what()); } } else - log_v2::grpc()->warn( - "GRPC: 'certificate' ignored since 'encryption' is disabled"); + log_v2::instance() + .get(log_v2::CORE) + ->warn("GRPC: 'certificate' ignored since 'encryption' is disabled"); } // CA Certificate. @@ -391,15 +417,17 @@ io::endpoint* factory::_new_endpoint_bbdo_cs( ca_certificate = read_file(it->second); } catch (const std::exception& e) { SPDLOG_LOGGER_ERROR( - log_v2::grpc(), + log_v2::instance().get(log_v2::TLS), "Failed to open authority certificate file '{}': {}", it->second, e.what()); throw msg_fmt("Failed to open authority certificate file '{}': {}", it->second, e.what()); } } else - log_v2::grpc()->warn( - "GRPC: 'ca_certificate' ignored since 'encryption' is disabled"); + log_v2::instance() + .get(log_v2::CORE) + ->warn( + "GRPC: 'ca_certificate' ignored since 'encryption' is disabled"); } bool compression = false; @@ -430,9 +458,12 @@ io::endpoint* factory::_new_endpoint_bbdo_cs( it = cfg.params.find("keepalive_interval"); if (it != cfg.params.end()) { if (!absl::SimpleAtoi(it->second, &keepalive_interval)) { - log_v2::grpc()->error( - "GRPC: 'keepalive_interval' field should be an integer and not '{}'", - it->second); + log_v2::instance() + .get(log_v2::CORE) + ->error( + "GRPC: 'keepalive_interval' field should be an integer and not " + "'{}'", + it->second); throw msg_fmt( "GRPC: 'keepalive_interval' field should be an integer and not '{}'", it->second); @@ -456,15 +487,19 @@ io::endpoint* factory::_new_endpoint_bbdo_cs( // Acceptor. std::unique_ptr endp; if (is_acceptor) { - log_v2::grpc()->debug("GRPC: encryption {} on gRPC server port {}", - encryption ? "enabled" : "disabled", port); + log_v2::instance() + .get(log_v2::CORE) + ->debug("GRPC: encryption {} on gRPC server port {}", + encryption ? "enabled" : "disabled", port); endp = std::make_unique(conf); } // Connector. else { - log_v2::grpc()->debug("GRPC: encryption {} on gRPC client port {}", - encryption ? "enabled" : "disabled", port); + log_v2::instance() + .get(log_v2::CORE) + ->debug("GRPC: encryption {} on gRPC client port {}", + encryption ? "enabled" : "disabled", port); endp = std::make_unique(conf); } diff --git a/broker/grpc/src/main.cc b/broker/grpc/src/main.cc index 540b542c1b8..fe4d508bc92 100644 --- a/broker/grpc/src/main.cc +++ b/broker/grpc/src/main.cc @@ -18,9 +18,10 @@ */ #include "com/centreon/broker/grpc/factory.hh" #include "com/centreon/broker/io/protocols.hh" -#include "com/centreon/broker/log_v2.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; +using log_v2 = com::centreon::common::log_v2::log_v2; // Load count. static uint32_t instances(0); @@ -60,11 +61,12 @@ bool broker_module_deinit() { */ void broker_module_init(void const* arg) { (void)arg; + auto logger = log_v2::instance().get(log_v2::GRPC); // Increment instance number. if (!instances++) { // TCP module. - SPDLOG_LOGGER_INFO(log_v2::grpc(), "Module for Centreon Broker {}", + SPDLOG_LOGGER_INFO(logger, "Module for Centreon Broker {}", CENTREON_BROKER_VERSION); // Register TCP protocol. diff --git a/broker/grpc/src/stream.cc b/broker/grpc/src/stream.cc index 582cafb2778..ca4942abc2b 100644 --- a/broker/grpc/src/stream.cc +++ b/broker/grpc/src/stream.cc @@ -26,17 +26,11 @@ #include "com/centreon/broker/misc/string.hh" #include "com/centreon/common/pool.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker::grpc; using namespace com::centreon::exceptions; - -// namespace fmt { - -// // mandatory to log -// template <> -// struct formatter : ostream_formatter {}; - -// } // namespace fmt +using log_v2 = com::centreon::common::log_v2::log_v2; namespace com::centreon::broker { namespace stream { @@ -126,8 +120,8 @@ std::mutex stream::_instances_m; template stream::stream(const grpc_config::pointer& conf, const std::string_view& class_name) - : io::stream("GRPC"), _conf(conf), _class_name(class_name) { - SPDLOG_LOGGER_DEBUG(log_v2::grpc(), "create {} this={:p}", _class_name, + : io::stream("GRPC"), _conf(conf), _class_name(class_name), _logger{log_v2::instance().get(log_v2::GRPC)} { + SPDLOG_LOGGER_DEBUG(_logger, "create {} this={:p}", _class_name, static_cast(this)); } @@ -138,7 +132,7 @@ stream::stream(const grpc_config::pointer& conf, */ template stream::~stream() { - SPDLOG_LOGGER_DEBUG(log_v2::grpc(), "delete {} this={:p}", _class_name, + SPDLOG_LOGGER_DEBUG(_logger, "delete {} this={:p}", _class_name, static_cast(this)); } @@ -174,7 +168,7 @@ void stream::start_read() { } to_read = _read_current = std::make_shared(); } - SPDLOG_LOGGER_TRACE(log_v2::grpc(), "{:p} {} Start read", + SPDLOG_LOGGER_TRACE(_logger, "{:p} {} Start read", static_cast(this), _class_name); bireactor_class::StartRead(to_read.get()); } @@ -191,7 +185,7 @@ void stream::OnReadDone(bool ok) { if (ok) { { std::unique_lock l(_read_m); - SPDLOG_LOGGER_TRACE(log_v2::grpc(), "{:p} {} receive: {}", + SPDLOG_LOGGER_TRACE(_logger, "{:p} {} receive: {}", static_cast(this), _class_name, *_read_current); _read_queue.push(_read_current); @@ -200,7 +194,7 @@ void stream::OnReadDone(bool ok) { _read_cond.notify_one(); start_read(); } else { - SPDLOG_LOGGER_ERROR(log_v2::grpc(), "{:p} {} fail read from stream", + SPDLOG_LOGGER_ERROR(_logger, "{:p} {} fail read from stream", static_cast(this), _class_name); stop(); } @@ -229,14 +223,14 @@ bool stream::read(std::shared_ptr& d, d = std::make_shared(); std::static_pointer_cast(d)->_buffer.assign( to_convert.buffer().begin(), to_convert.buffer().end()); - SPDLOG_LOGGER_TRACE(log_v2::grpc(), "{:p} {} read:{}", + SPDLOG_LOGGER_TRACE(_logger, "{:p} {} read:{}", static_cast(this), _class_name, *std::static_pointer_cast(d)); return true; } else { d = protobuf_to_event(first); if (d) { - SPDLOG_LOGGER_TRACE(log_v2::grpc(), "{:p} {} read:{}", + SPDLOG_LOGGER_TRACE(_logger, "{:p} {} read:{}", static_cast(this), _class_name, *d); } return d ? true : false; @@ -283,11 +277,11 @@ void stream::start_write() { } if (to_send->bbdo_event) - SPDLOG_LOGGER_TRACE(log_v2::grpc(), "{:p} {} write: {}", + SPDLOG_LOGGER_TRACE(_logger, "{:p} {} write: {}", static_cast(this), _class_name, *to_send->bbdo_event); else - SPDLOG_LOGGER_TRACE(log_v2::grpc(), "{:p} {} write: {}", + SPDLOG_LOGGER_TRACE(_logger, "{:p} {} write: {}", static_cast(this), _class_name, to_send->grpc_event); @@ -309,11 +303,11 @@ void stream::OnWriteDone(bool ok) { std::unique_lock l(_write_m); event_with_data::pointer written = _write_queue.front(); if (written->bbdo_event) - SPDLOG_LOGGER_TRACE(log_v2::grpc(), "{:p} {} write done: {}", + SPDLOG_LOGGER_TRACE(_logger, "{:p} {} write done: {}", static_cast(this), _class_name, *written->bbdo_event); else - SPDLOG_LOGGER_TRACE(log_v2::grpc(), "{:p} {} write done: {}", + SPDLOG_LOGGER_TRACE(_logger, "{:p} {} write done: {}", static_cast(this), _class_name, written->grpc_event); @@ -323,7 +317,7 @@ void stream::OnWriteDone(bool ok) { _write_cond.notify_one(); start_write(); } else { - SPDLOG_LOGGER_ERROR(log_v2::grpc(), "{:p} {} fail write to stream", + SPDLOG_LOGGER_ERROR(_logger, "{:p} {} fail write to stream", static_cast(this), _class_name); stop(); } @@ -376,9 +370,9 @@ void stream::OnDone() { */ common::pool::io_context().post( [me = std::enable_shared_from_this< - stream>::shared_from_this()]() { + stream>::shared_from_this(), logger = _logger]() { std::lock_guard l(_instances_m); - SPDLOG_LOGGER_DEBUG(log_v2::grpc(), "{:p} server::OnDone()", + SPDLOG_LOGGER_DEBUG(logger, "{:p} server::OnDone()", static_cast(me.get())); _instances.erase(std::static_pointer_cast>(me)); }); @@ -402,9 +396,9 @@ void stream::OnDone(const ::grpc::Status& status) { common::pool::io_context().post( [me = std::enable_shared_from_this< stream>::shared_from_this(), - status]() { + status, logger=_logger]() { std::lock_guard l(_instances_m); - SPDLOG_LOGGER_DEBUG(log_v2::grpc(), "{:p} client::OnDone({}) {}", + SPDLOG_LOGGER_DEBUG(logger, "{:p} client::OnDone({}) {}", static_cast(me.get()), status.error_message(), status.error_details()); _instances.erase(std::static_pointer_cast>(me)); @@ -418,7 +412,7 @@ void stream::OnDone(const ::grpc::Status& status) { */ template void stream::shutdown() { - SPDLOG_LOGGER_DEBUG(log_v2::grpc(), "{:p} {}::shutdown", + SPDLOG_LOGGER_DEBUG(_logger, "{:p} {}::shutdown", static_cast(this), _class_name); } @@ -443,7 +437,7 @@ template int32_t stream::stop() { std::lock_guard l(_protect); if (_alive) { - SPDLOG_LOGGER_DEBUG(log_v2::grpc(), "{:p} {}::stop", + SPDLOG_LOGGER_DEBUG(_logger, "{:p} {}::stop", static_cast(this), _class_name); _alive = false; this->shutdown(); @@ -475,4 +469,4 @@ template class stream< ::grpc::ServerBidiReactor<::com::centreon::broker::stream::CentreonEvent, ::com::centreon::broker::stream::CentreonEvent>>; -} // namespace com::centreon::broker::grpc \ No newline at end of file +} // namespace com::centreon::broker::grpc diff --git a/broker/grpc/test/acceptor.cc b/broker/grpc/test/acceptor.cc index 15c71d92ae9..5737d9cae2e 100644 --- a/broker/grpc/test/acceptor.cc +++ b/broker/grpc/test/acceptor.cc @@ -52,6 +52,8 @@ TEST_F(GrpcTlsTest, TlsStream) { /* Let's prepare certificates */ std::string hostname = misc::exec("hostname --fqdn"); hostname = misc::string::trim(hostname); + if (hostname.empty()) + hostname = "localhost"; std::string server_cmd( fmt::format("openssl req -new -newkey rsa:2048 -days 365 -nodes -x509 " "-keyout /tmp/server.key -out /tmp/server.crt -subj '/CN={}'", @@ -150,10 +152,9 @@ TEST_F(GrpcTlsTest, TlsStreamBadCaHostname) { std::cout << client_cmd << std::endl; system(client_cmd.c_str()); - std::atomic_bool cbd_finished{false}; std::atomic_bool centengine_finished{false}; - std::thread cbd([&cbd_finished, ¢engine_finished] { + std::thread cbd([¢engine_finished] { auto conf{std::make_shared( "0.0.0.0:4141", true, read_file("/tmp/server.crt"), read_file("/tmp/server.key"), read_file("/tmp/client.crt"), "", diff --git a/broker/grpc/test/grpc_test_include.hh b/broker/grpc/test/grpc_test_include.hh index 1f22ba3f1d3..32a15876503 100644 --- a/broker/grpc/test/grpc_test_include.hh +++ b/broker/grpc/test/grpc_test_include.hh @@ -43,8 +43,6 @@ using time_point = system_clock::time_point; using duration = system_clock::duration; using unique_lock = std::unique_lock; -#include "com/centreon/broker/log_v2.hh" - #include "com/centreon/broker/grpc/acceptor.hh" #include "com/centreon/broker/grpc/connector.hh" #include "com/centreon/broker/grpc/stream.hh" diff --git a/broker/grpc/test/stream_test.cc b/broker/grpc/test/stream_test.cc index 476d1884c00..400a9b9cea6 100644 --- a/broker/grpc/test/stream_test.cc +++ b/broker/grpc/test/stream_test.cc @@ -21,12 +21,13 @@ #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/io/protocols.hh" - +#include "common/log_v2/log_v2.hh" #include "grpc_test_include.hh" #include "tcp_relais.hh" using namespace com::centreon::broker; using namespace com::centreon::exceptions; +using com::centreon::common::log_v2::log_v2; com::centreon::broker::grpc::grpc_config::pointer conf( std::make_shared( @@ -72,10 +73,12 @@ std::shared_ptr create_event(const test_param& param) { class grpc_test_server : public ::testing::TestWithParam { protected: static std::unique_ptr s; + static std::shared_ptr _logger; public: static void SetUpTestSuite() { - log_v2::grpc()->set_level(spdlog::level::trace); + _logger = log_v2::instance().get(log_v2::GRPC); + //_logger->set_level(spdlog::level::trace); s = std::make_unique(conf); std::this_thread::sleep_for(std::chrono::milliseconds(50)); io::protocols::load(); @@ -93,6 +96,7 @@ class grpc_test_server : public ::testing::TestWithParam { }; std::unique_ptr grpc_test_server::s; +std::shared_ptr grpc_test_server::_logger; #define COMPARE_EVENT(read_ret, received, param) \ ASSERT_TRUE(read_ret); \ @@ -120,14 +124,14 @@ TEST_P(grpc_test_server, ClientToServerSendReceive) { param.dest += test_ind; param.buffer += "_"; param.buffer += std::to_string(test_ind); - SPDLOG_LOGGER_DEBUG(log_v2::grpc(), "{} write param.data_type={}", - __PRETTY_FUNCTION__, param.data_type); + _logger->debug("{} write param.data_type={}", __PRETTY_FUNCTION__, + param.data_type); client->write(create_event(param)); std::shared_ptr receive; bool read_ret = accepted->read(receive, time(nullptr) + 2); - SPDLOG_LOGGER_DEBUG(log_v2::grpc(), "{} read_ret={} param.data_type={}", - __PRETTY_FUNCTION__, read_ret, param.data_type); + _logger->debug("{} read_ret={} param.data_type={}", __PRETTY_FUNCTION__, + read_ret, param.data_type); COMPARE_EVENT(read_ret, receive, param); } client->stop(); @@ -151,14 +155,14 @@ TEST_P(grpc_test_server, ServerToClientSendReceive) { param.dest += test_ind; param.buffer += "_"; param.buffer += std::to_string(test_ind); - SPDLOG_LOGGER_DEBUG(log_v2::grpc(), "{} write param.data_type={}", - __PRETTY_FUNCTION__, param.data_type); + _logger->debug("{} write param.data_type={}", __PRETTY_FUNCTION__, + param.data_type); accepted->write(create_event(param)); std::shared_ptr receive; bool read_ret = client->read(receive, time(nullptr) + 2); - SPDLOG_LOGGER_DEBUG(log_v2::grpc(), "{} read_ret={} param.data_type={}", - __PRETTY_FUNCTION__, read_ret, param.data_type); + _logger->debug("{} read_ret={} param.data_type={}", __PRETTY_FUNCTION__, + read_ret, param.data_type); COMPARE_EVENT(read_ret, receive, param); } client->stop(); @@ -169,11 +173,13 @@ class grpc_comm_failure : public ::testing::TestWithParam { protected: static std::unique_ptr s; static std::unique_ptr relay; + static std::shared_ptr _logger; public: static void SetUpTestSuite() { srand(time(nullptr)); - // log_v2::grpc()->set_level(spdlog::level::trace); + _logger = log_v2::instance().get(log_v2::GRPC); + //_logger->set_level(spdlog::level::trace); s = std::make_unique(conf_relay_out); relay = std::make_unique( "127.0.0.1", relay_listen_port, "127.0.0.1", server_listen_port); @@ -192,6 +198,7 @@ class grpc_comm_failure : public ::testing::TestWithParam { std::unique_ptr grpc_comm_failure::s; std::unique_ptr grpc_comm_failure::relay; +std::shared_ptr grpc_comm_failure::_logger; INSTANTIATE_TEST_SUITE_P(grpc_comm_failure, grpc_comm_failure, @@ -204,13 +211,13 @@ TEST_P(grpc_comm_failure, ClientToServerFailureBeforeWrite) { ASSERT_NE(accepted.get(), nullptr); test_param param = GetParam(); - SPDLOG_LOGGER_DEBUG(log_v2::grpc(), "{} write param.data_type={}", - __PRETTY_FUNCTION__, param.data_type); + _logger->debug("{} write param.data_type={}", __PRETTY_FUNCTION__, + param.data_type); client->write(create_event(GetParam())); std::shared_ptr receive; bool read_ret = accepted->read(receive, time(nullptr) + 2); - SPDLOG_LOGGER_DEBUG(log_v2::grpc(), "{} read_ret={} param.data_type={}", - __PRETTY_FUNCTION__, read_ret, param.data_type); + _logger->debug("{} read_ret={} param.data_type={}", __PRETTY_FUNCTION__, + read_ret, param.data_type); COMPARE_EVENT(read_ret, receive, param); relay->shutdown_relays(); @@ -228,13 +235,13 @@ TEST_P(grpc_comm_failure, ClientToServerFailureAfterWrite) { ASSERT_NE(accepted.get(), nullptr); test_param param = GetParam(); - SPDLOG_LOGGER_DEBUG(log_v2::grpc(), "{} write param.data_type={}", - __PRETTY_FUNCTION__, param.data_type); + _logger->debug("{} write param.data_type={}", __PRETTY_FUNCTION__, + param.data_type); client->write(create_event(param)); std::shared_ptr receive; bool read_ret = accepted->read(receive, time(nullptr) + 2); - SPDLOG_LOGGER_DEBUG(log_v2::grpc(), "{} read_ret={} param.data_type={}", - __PRETTY_FUNCTION__, read_ret, param.data_type); + _logger->debug("{} read_ret={} param.data_type={}", __PRETTY_FUNCTION__, + read_ret, param.data_type); COMPARE_EVENT(read_ret, receive, param); unsigned offset = rand(); @@ -263,13 +270,13 @@ TEST_P(grpc_comm_failure, ServerToClientFailureBeforeWrite) { ASSERT_NE(accepted.get(), nullptr); test_param param = GetParam(); - SPDLOG_LOGGER_DEBUG(log_v2::grpc(), "{} write param.data_type={}", - __PRETTY_FUNCTION__, param.data_type); + _logger->debug("{} write param.data_type={}", __PRETTY_FUNCTION__, + param.data_type); accepted->write(create_event(param)); std::shared_ptr receive; bool read_ret = client->read(receive, time(nullptr) + 2); - SPDLOG_LOGGER_DEBUG(log_v2::grpc(), "{} read_ret={} param.data_type={}", - __PRETTY_FUNCTION__, read_ret, param.data_type); + _logger->debug("{} read_ret={} param.data_type={}", __PRETTY_FUNCTION__, + read_ret, param.data_type); COMPARE_EVENT(read_ret, receive, param); std::this_thread::sleep_for(std::chrono::milliseconds(5)); @@ -291,7 +298,7 @@ TEST_P(grpc_comm_failure, ServerToClientFailureBeforeWrite) { ASSERT_NE(accepted2.get(), nullptr); accepted2->write(create_event(param)); read_ret = client2->read(receive, time(nullptr) + 2); - SPDLOG_LOGGER_DEBUG(log_v2::grpc(), "{} read_ret={} param.data_type={}", + SPDLOG_LOGGER_DEBUG(_logger, "{} read_ret={} param.data_type={}", __PRETTY_FUNCTION__, read_ret, param.data_type); COMPARE_EVENT(read_ret, receive, param); client->stop(); @@ -309,13 +316,13 @@ TEST_P(grpc_comm_failure, ServerToClientFailureAfterWrite) { ASSERT_NE(accepted.get(), nullptr); test_param param = GetParam(); - SPDLOG_LOGGER_DEBUG(log_v2::grpc(), "{} write param.data_type={}", - __PRETTY_FUNCTION__, param.data_type); + _logger->debug("{} write param.data_type={}", __PRETTY_FUNCTION__, + param.data_type); accepted->write(create_event(param)); std::shared_ptr receive; bool read_ret = client->read(receive, time(nullptr) + 2); - SPDLOG_LOGGER_DEBUG(log_v2::grpc(), "{} read_ret={} param.data_type={}", - __PRETTY_FUNCTION__, read_ret, param.data_type); + _logger->debug("{} read_ret={} param.data_type={}", __PRETTY_FUNCTION__, + read_ret, param.data_type); COMPARE_EVENT(read_ret, receive, param); unsigned offset = rand(); @@ -337,7 +344,7 @@ TEST_P(grpc_comm_failure, ServerToClientFailureAfterWrite) { ASSERT_NE(accepted2.get(), nullptr); accepted2->write(create_event(param)); read_ret = client2->read(receive, time(nullptr) + 2); - SPDLOG_LOGGER_DEBUG(log_v2::grpc(), "{} read_ret={} param.data_type={}", + SPDLOG_LOGGER_DEBUG(_logger, "{} read_ret={} param.data_type={}", __PRETTY_FUNCTION__, read_ret, param.data_type); COMPARE_EVENT(read_ret, receive, param); client->stop(); @@ -388,10 +395,12 @@ com::centreon::broker::grpc::grpc_config::pointer conf_crypted_client1234( class grpc_test_server_crypted : public ::testing::TestWithParam { protected: static std::unique_ptr s; + static std::shared_ptr _logger; public: static void SetUpTestSuite() { - // log_v2::grpc()->set_level(spdlog::level::trace); + _logger = log_v2::instance().get(log_v2::GRPC); + //_logger->set_level(spdlog::level::trace); s = std::make_unique( conf_crypted_server1234); } @@ -405,6 +414,7 @@ class grpc_test_server_crypted : public ::testing::TestWithParam { std::unique_ptr grpc_test_server_crypted::s; +std::shared_ptr grpc_test_server_crypted::_logger; INSTANTIATE_TEST_SUITE_P(grpc_test_server_crypted, grpc_test_server_crypted, @@ -423,13 +433,13 @@ TEST_P(grpc_test_server_crypted, ServerToClientWithKeySendReceive) { param.dest += test_ind; param.buffer += "_"; param.buffer += std::to_string(test_ind); - SPDLOG_LOGGER_DEBUG(log_v2::grpc(), "{} write param.data_type={}", + SPDLOG_LOGGER_DEBUG(_logger, "{} write param.data_type={}", __PRETTY_FUNCTION__, param.data_type); accepted->write(create_event(param)); std::shared_ptr receive; bool read_ret = client->read(receive, time(nullptr) + 2); - SPDLOG_LOGGER_DEBUG(log_v2::grpc(), "{} read_ret={} param.data_type={}", + SPDLOG_LOGGER_DEBUG(_logger, "{} read_ret={} param.data_type={}", __PRETTY_FUNCTION__, read_ret, param.data_type); COMPARE_EVENT(read_ret, receive, param); } diff --git a/broker/http_tsdb/inc/com/centreon/broker/http_tsdb/column.hh b/broker/http_tsdb/inc/com/centreon/broker/http_tsdb/column.hh index b96b9705bea..241291e326b 100644 --- a/broker/http_tsdb/inc/com/centreon/broker/http_tsdb/column.hh +++ b/broker/http_tsdb/inc/com/centreon/broker/http_tsdb/column.hh @@ -1,25 +1,24 @@ -/* -** Copyright 2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2022 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_HTTP_TSDB_COLUMN_HH #define CCB_HTTP_TSDB_COLUMN_HH - namespace com::centreon::broker { namespace http_tsdb { @@ -51,6 +50,6 @@ class column { }; } // namespace http_tsdb -} +} // namespace com::centreon::broker #endif // !CCB_HTTP_TSDB_COLUMN_HH diff --git a/broker/http_tsdb/inc/com/centreon/broker/http_tsdb/factory.hh b/broker/http_tsdb/inc/com/centreon/broker/http_tsdb/factory.hh index acb08f9192c..81f53d3a202 100644 --- a/broker/http_tsdb/inc/com/centreon/broker/http_tsdb/factory.hh +++ b/broker/http_tsdb/inc/com/centreon/broker/http_tsdb/factory.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2022 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_HTTP_TSDB_FACTORY_HH #define CCB_HTTP_TSDB_FACTORY_HH @@ -55,6 +55,6 @@ class factory : public io::factory { }; } // namespace http_tsdb -} +} // namespace com::centreon::broker #endif // !CCB_HTTP_TSDB_FACTORY_HH diff --git a/broker/http_tsdb/inc/com/centreon/broker/http_tsdb/internal.hh b/broker/http_tsdb/inc/com/centreon/broker/http_tsdb/internal.hh index 487ad261f62..96bff077674 100644 --- a/broker/http_tsdb/inc/com/centreon/broker/http_tsdb/internal.hh +++ b/broker/http_tsdb/inc/com/centreon/broker/http_tsdb/internal.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2022 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_HTTP_TSDB_INTERNAL_HH #define CCB_HTTP_TSDB_INTERNAL_HH @@ -39,6 +39,6 @@ using pb_status = io::protobuf; } // namespace storage -} +} // namespace com::centreon::broker #endif // !CCB_HTTP_TSDB_INTERNAL_HH diff --git a/broker/http_tsdb/inc/com/centreon/broker/http_tsdb/line_protocol_query.hh b/broker/http_tsdb/inc/com/centreon/broker/http_tsdb/line_protocol_query.hh index a05c86d39e6..85167900ae0 100644 --- a/broker/http_tsdb/inc/com/centreon/broker/http_tsdb/line_protocol_query.hh +++ b/broker/http_tsdb/inc/com/centreon/broker/http_tsdb/line_protocol_query.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2022 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_HTTP_TSDB_LINE_PROTOCOL_QUERY_HH #define CCB_HTTP_TSDB_LINE_PROTOCOL_QUERY_HH @@ -122,13 +122,13 @@ class line_protocol_query { std::ostream& is) const; void _get_tag_host_cat_id(io::data const& d, - unsigned& string_index, + unsigned& string_index [[maybe_unused]], std::ostream& is) const { _get_tag_host_id(d, TagType::HOSTCATEGORY, is); } void _get_tag_host_group_id(io::data const& d, - unsigned& string_index, + unsigned& string_index [[maybe_unused]], std::ostream& is) const { _get_tag_host_id(d, TagType::HOSTGROUP, is); } @@ -138,13 +138,13 @@ class line_protocol_query { std::ostream& is) const; void _get_tag_host_cat_name(io::data const& d, - unsigned& string_index, + unsigned& string_index [[maybe_unused]], std::ostream& is) const { _get_tag_host_name(d, TagType::HOSTCATEGORY, is); } void _get_tag_host_group_name(io::data const& d, - unsigned& string_index, + unsigned& string_index [[maybe_unused]], std::ostream& is) const { _get_tag_host_name(d, TagType::HOSTGROUP, is); } @@ -154,13 +154,13 @@ class line_protocol_query { std::ostream& is) const; void _get_tag_serv_cat_id(io::data const& d, - unsigned& string_index, + unsigned& string_index [[maybe_unused]], std::ostream& is) const { _get_tag_serv_id(d, TagType::SERVICECATEGORY, is); } void _get_tag_serv_group_id(io::data const& d, - unsigned& string_index, + unsigned& string_index [[maybe_unused]], std::ostream& is) const { _get_tag_serv_id(d, TagType::SERVICEGROUP, is); } @@ -170,13 +170,13 @@ class line_protocol_query { std::ostream& is) const; void _get_tag_serv_cat_name(io::data const& d, - unsigned& string_index, + unsigned& string_index [[maybe_unused]], std::ostream& is) const { _get_tag_serv_name(d, TagType::SERVICECATEGORY, is); } void _get_tag_serv_group_name(io::data const& d, - unsigned& string_index, + unsigned& string_index [[maybe_unused]], std::ostream& is) const { _get_tag_serv_name(d, TagType::SERVICEGROUP, is); } @@ -212,6 +212,6 @@ class line_protocol_query { }; } // namespace http_tsdb -} +} // namespace com::centreon::broker #endif // !CCB_HTTP_TSDB_LINE_PROTOCOL_QUERY_HH diff --git a/broker/http_tsdb/src/line_protocol_query.cc b/broker/http_tsdb/src/line_protocol_query.cc index f4617b299e4..c2d2b1f7981 100644 --- a/broker/http_tsdb/src/line_protocol_query.cc +++ b/broker/http_tsdb/src/line_protocol_query.cc @@ -1,25 +1,24 @@ /** -* Copyright 2015-2017 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2015-2017 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/http_tsdb/line_protocol_query.hh" #include "com/centreon/broker/cache/global_cache.hh" #include "com/centreon/broker/http_tsdb/internal.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/string.hh" #include "com/centreon/exceptions/msg_fmt.hh" @@ -362,7 +361,7 @@ void line_protocol_query::_throw_on_invalid(data_type macro_type) { */ template void line_protocol_query::_get_member(io::data const& d, - unsigned& string_index, + unsigned& string_index [[maybe_unused]], std::ostream& is) const { is << static_cast(d).*member; } @@ -387,7 +386,8 @@ void line_protocol_query::_get_string(io::data const& d, * @param[in] is The stream. */ void line_protocol_query::_get_dollar_sign(io::data const& d, - unsigned& string_index, + unsigned& string_index + [[maybe_unused]], std::ostream& is) const { (void)d; is << "$"; @@ -429,7 +429,7 @@ uint64_t line_protocol_query::_get_index_id(io::data const& d) const { * @param[out] is The stream. */ void line_protocol_query::_get_index_id(io::data const& d, - unsigned& string_index, + unsigned& string_index [[maybe_unused]], std::ostream& is) const { cache::global_cache::lock l; is << _get_index_id(d); @@ -442,7 +442,7 @@ void line_protocol_query::_get_index_id(io::data const& d, * @param is The stream. */ void line_protocol_query::_get_host(io::data const& d, - unsigned& string_index, + unsigned& string_index [[maybe_unused]], std::ostream& is) const { uint64_t host_id = d.type() == storage::pb_metric::static_type() @@ -477,7 +477,7 @@ uint64_t line_protocol_query::_get_host_id(io::data const& d) const { * @param is The stream. */ void line_protocol_query::_get_host_id(io::data const& d, - unsigned& string_index, + unsigned& string_index [[maybe_unused]], std::ostream& is) const { is << _get_host_id(d); } @@ -489,7 +489,7 @@ void line_protocol_query::_get_host_id(io::data const& d, * @param is The stream. */ void line_protocol_query::_get_service(io::data const& d, - unsigned& string_index, + unsigned& string_index [[maybe_unused]], std::ostream& is) const { cache::host_serv_pair host_serv = _get_service_id(d); cache::global_cache::lock l; @@ -524,7 +524,8 @@ cache::host_serv_pair line_protocol_query::_get_service_id( * @param is The stream. */ void line_protocol_query::_get_service_id(io::data const& d, - unsigned& string_index, + unsigned& string_index + [[maybe_unused]], std::ostream& is) const { is << _get_service_id(d).second; } @@ -536,7 +537,7 @@ void line_protocol_query::_get_service_id(io::data const& d, * @param is The stream. */ void line_protocol_query::_get_instance(io::data const& d, - unsigned& string_index, + unsigned& string_index [[maybe_unused]], std::ostream& is) const { cache::global_cache::lock l; const cache::string* instance_name = @@ -554,7 +555,8 @@ void line_protocol_query::_get_instance(io::data const& d, * @param is */ void line_protocol_query::_get_host_group(io::data const& d, - unsigned& string_index, + unsigned& string_index + [[maybe_unused]], std::ostream& is) const { cache::global_cache::lock l; cache::global_cache::instance_ptr()->append_host_group(_get_host_id(d), is); @@ -568,7 +570,8 @@ void line_protocol_query::_get_host_group(io::data const& d, * @param is */ void line_protocol_query::_get_service_group(io::data const& d, - unsigned& string_index, + unsigned& string_index + [[maybe_unused]], std::ostream& is) const { cache::host_serv_pair host_serv = _get_service_id(d); cache::global_cache::lock l; @@ -584,7 +587,7 @@ void line_protocol_query::_get_service_group(io::data const& d, * @param is */ void line_protocol_query::_get_min(io::data const& d, - unsigned& string_index, + unsigned& string_index [[maybe_unused]], std::ostream& is) const { cache::global_cache::lock l; const cache::metric_info* infos = _get_metric_info(d); @@ -601,7 +604,7 @@ void line_protocol_query::_get_min(io::data const& d, * @param is */ void line_protocol_query::_get_max(io::data const& d, - unsigned& string_index, + unsigned& string_index [[maybe_unused]], std::ostream& is) const { cache::global_cache::lock l; const cache::metric_info* infos = _get_metric_info(d); @@ -618,7 +621,8 @@ void line_protocol_query::_get_max(io::data const& d, * @param is */ void line_protocol_query::_get_resource_id(io::data const& d, - unsigned& string_index, + unsigned& string_index + [[maybe_unused]], std::ostream& is) const { cache::host_serv_pair host_serv = _get_service_id(d); cache::global_cache::lock l; @@ -723,7 +727,8 @@ void line_protocol_query::_get_tag_serv_name(io::data const& d, * @param is */ void line_protocol_query::_get_metric_name(io::data const& d, - unsigned& string_index, + unsigned& string_index + [[maybe_unused]], std::ostream& is) const { is << static_cast(d).obj().name(); } @@ -735,7 +740,8 @@ void line_protocol_query::_get_metric_name(io::data const& d, * @param is */ void line_protocol_query::_get_metric_id(io::data const& d, - unsigned& string_index, + unsigned& string_index + [[maybe_unused]], std::ostream& is) const { is << static_cast(d).obj().metric_id(); } @@ -747,7 +753,8 @@ void line_protocol_query::_get_metric_id(io::data const& d, * @param is */ void line_protocol_query::_get_metric_value(io::data const& d, - unsigned& string_index, + unsigned& string_index + [[maybe_unused]], std::ostream& is) const { is << static_cast(d).obj().value(); } @@ -759,7 +766,8 @@ void line_protocol_query::_get_metric_value(io::data const& d, * @param is */ void line_protocol_query::_get_metric_time(io::data const& d, - unsigned& string_index, + unsigned& string_index + [[maybe_unused]], std::ostream& is) const { is << static_cast(d).obj().time(); } @@ -771,7 +779,8 @@ void line_protocol_query::_get_metric_time(io::data const& d, * @param is */ void line_protocol_query::_get_status_state(io::data const& d, - unsigned& string_index, + unsigned& string_index + [[maybe_unused]], std::ostream& is) const { is << static_cast(d).obj().state(); } @@ -783,7 +792,8 @@ void line_protocol_query::_get_status_state(io::data const& d, * @param is */ void line_protocol_query::_get_status_time(io::data const& d, - unsigned& string_index, + unsigned& string_index + [[maybe_unused]], std::ostream& is) const { is << static_cast(d).obj().time(); } diff --git a/broker/http_tsdb/src/stream.cc b/broker/http_tsdb/src/stream.cc index dc78b102350..103fe09f242 100644 --- a/broker/http_tsdb/src/stream.cc +++ b/broker/http_tsdb/src/stream.cc @@ -185,8 +185,6 @@ bool stream::read(std::shared_ptr& d, time_t) { * @param tree */ void stream::statistics(nlohmann::json& tree) const { - time_t now = time(nullptr); - auto extract_stat = [&](const char* label, const stat_average& data) { if (!data.empty()) { tree[label] = data.get_average(); diff --git a/broker/http_tsdb/test/factory_test.cc b/broker/http_tsdb/test/factory_test.cc index 3dc57db1818..f9c6b60f789 100644 --- a/broker/http_tsdb/test/factory_test.cc +++ b/broker/http_tsdb/test/factory_test.cc @@ -38,7 +38,8 @@ extern std::shared_ptr g_io_context; class factory_test : public http_tsdb::factory { public: factory_test(const std::string& name, - const std::shared_ptr& io_context) + const std::shared_ptr& io_context + [[maybe_unused]]) : http_tsdb::factory(name, g_io_context) {} io::endpoint* new_endpoint( diff --git a/broker/http_tsdb/test/stream_test.cc b/broker/http_tsdb/test/stream_test.cc index c5cee36daaf..4e6d9db0ade 100644 --- a/broker/http_tsdb/test/stream_test.cc +++ b/broker/http_tsdb/test/stream_test.cc @@ -30,9 +30,9 @@ using duration = system_clock::duration; #include "com/centreon/broker/file/disk_accessor.hh" #include "com/centreon/broker/http_tsdb/stream.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/common/pool.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; @@ -42,27 +42,35 @@ using namespace nlohmann; extern std::shared_ptr g_io_context; class http_tsdb_stream_test : public ::testing::Test { + protected: + static std::shared_ptr _logger; + public: static void SetUpTestSuite() { srand(time(nullptr)); - log_v2::tcp()->set_level(spdlog::level::info); + _logger = log_v2::log_v2::instance().get(log_v2::log_v2::TCP); + _logger->set_level(spdlog::level::info); file::disk_accessor::load(1000); } }; +std::shared_ptr http_tsdb_stream_test::_logger; + class request_test : public http_tsdb::request { uint _request_id; + std::shared_ptr _logger; public: static std::atomic_uint id_gen; request_test() : _request_id(id_gen.fetch_add(1)) { - SPDLOG_LOGGER_TRACE(log_v2::tcp(), "create request {}", _request_id); + _logger = log_v2::log_v2::instance().get(log_v2::log_v2::TCP); + SPDLOG_LOGGER_TRACE(_logger, "create request {}", _request_id); } ~request_test() { - SPDLOG_LOGGER_TRACE(log_v2::tcp(), "delete request {}", _request_id); + SPDLOG_LOGGER_TRACE(_logger, "delete request {}", _request_id); } void add_metric(const storage::pb_metric& metric) override { ++_nb_metric; } @@ -85,7 +93,7 @@ class stream_test : public http_tsdb::stream { http::connection_creator conn_creator) : http_tsdb::stream("stream_test", g_io_context, - log_v2::tcp(), + log_v2::log_v2::instance().get(log_v2::log_v2::TCP), conf, conn_creator) {} http_tsdb::request::pointer create_request() const override { @@ -96,7 +104,9 @@ class stream_test : public http_tsdb::stream { TEST_F(http_tsdb_stream_test, NotRead) { auto conf = std::make_shared(); http::connection_creator conn_creator = [conf]() { - return http::http_connection::load(g_io_context, log_v2::tcp(), conf); + return http::http_connection::load( + g_io_context, log_v2::log_v2::instance().get(log_v2::log_v2::TCP), + conf); }; stream_test test(conf, conn_creator); @@ -132,7 +142,7 @@ class connection_send_bagot : public http::connection_base { } else { if (rand() & 3) { SPDLOG_LOGGER_ERROR( - log_v2::tcp(), "fail id:{} nb_data={}", + _logger, "fail id:{} nb_data={}", std::static_pointer_cast(request)->get_request_id(), std::static_pointer_cast(request)->get_nb_data()); _io_context->post([cb = std::move(callback), request]() { @@ -149,7 +159,7 @@ class connection_send_bagot : public http::connection_base { ->get_nb_metric()); success_cond.notify_one(); SPDLOG_LOGGER_DEBUG( - log_v2::tcp(), "success id:{} nb_data={}", + _logger, "success id:{} nb_data={}", std::static_pointer_cast(request)->get_request_id(), std::static_pointer_cast(request)->get_nb_data()); _io_context->post([cb = std::move(callback)]() { @@ -185,7 +195,8 @@ TEST_F(http_tsdb_stream_test, all_event_sent) { std::shared_ptr str( std::make_shared(tsdb_conf, [tsdb_conf]() { auto dummy_conn = std::make_shared( - g_io_context, log_v2::tcp(), tsdb_conf); + g_io_context, log_v2::log_v2::instance().get(log_v2::log_v2::TCP), + tsdb_conf); return dummy_conn; })); @@ -201,7 +212,7 @@ TEST_F(http_tsdb_stream_test, all_event_sent) { std::chrono::milliseconds(1)); // to let io_context thread fo the job } str->flush(); - SPDLOG_LOGGER_DEBUG(log_v2::tcp(), "wait"); + SPDLOG_LOGGER_DEBUG(_logger, "wait"); std::mutex dummy; std::unique_lock l(dummy); connection_send_bagot::success_cond.wait_for( diff --git a/broker/influxdb/inc/com/centreon/broker/influxdb/column.hh b/broker/influxdb/inc/com/centreon/broker/influxdb/column.hh index a9d2c665785..6aaceab45a2 100644 --- a/broker/influxdb/inc/com/centreon/broker/influxdb/column.hh +++ b/broker/influxdb/inc/com/centreon/broker/influxdb/column.hh @@ -1,28 +1,26 @@ -/* -** Copyright 2011-2013 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2011-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_INFLUXDB_COLUMN_HH #define CCB_INFLUXDB_COLUMN_HH +namespace com::centreon::broker::influxdb { -namespace com::centreon::broker { - -namespace influxdb { /** * @class column column.hh "com/centreon/broker/influxdb/column.hh" * @brief Store the data for a column in the query. @@ -51,8 +49,7 @@ class column { bool _is_flag; type _type; }; -} // namespace influxdb -} +} // namespace com::centreon::broker::influxdb #endif // !CCB_INFLUXDB_COLUMN_HH diff --git a/broker/influxdb/inc/com/centreon/broker/influxdb/connector.hh b/broker/influxdb/inc/com/centreon/broker/influxdb/connector.hh index 5d5be8e7296..906cf3132d4 100644 --- a/broker/influxdb/inc/com/centreon/broker/influxdb/connector.hh +++ b/broker/influxdb/inc/com/centreon/broker/influxdb/connector.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2015-2017, 2021 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2015-2017, 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_INFLUXDB_CONNECTOR_HH #define CCB_INFLUXDB_CONNECTOR_HH @@ -23,9 +23,8 @@ #include "com/centreon/broker/io/endpoint.hh" #include "com/centreon/broker/sql/database_config.hh" -namespace com::centreon::broker { +namespace com::centreon::broker::influxdb { -namespace influxdb { /** * @class connector connector.hh "com/centreon/broker/influxdb/connector.hh" * @brief Connect to an influxdb stream. @@ -62,8 +61,7 @@ class connector : public io::endpoint { std::vector _metric_cols; std::shared_ptr _cache; }; -} // namespace influxdb -} +} // namespace com::centreon::broker::influxdb #endif // !CCB_INFLUXDB_CONNECTOR_HH diff --git a/broker/influxdb/inc/com/centreon/broker/influxdb/factory.hh b/broker/influxdb/inc/com/centreon/broker/influxdb/factory.hh index 3c79cddf489..8b751bfe496 100644 --- a/broker/influxdb/inc/com/centreon/broker/influxdb/factory.hh +++ b/broker/influxdb/inc/com/centreon/broker/influxdb/factory.hh @@ -1,29 +1,28 @@ -/* -** Copyright 2014-2015 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2014-2015 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_INFLUXDB_FACTORY_HH #define CCB_INFLUXDB_FACTORY_HH #include "com/centreon/broker/io/factory.hh" -namespace com::centreon::broker { +namespace com::centreon::broker::influxdb { -namespace influxdb { /** * @class factory factory.hh "com/centreon/broker/influxdb/factory.hh" * @brief Influxdb layer factory. @@ -42,8 +41,7 @@ class factory : public io::factory { bool& is_acceptor, std::shared_ptr cache) const override; }; -} // namespace influxdb -} +} // namespace com::centreon::broker::influxdb #endif // !CCB_INFLUXDB_FACTORY_HH diff --git a/broker/influxdb/inc/com/centreon/broker/influxdb/influxdb.hh b/broker/influxdb/inc/com/centreon/broker/influxdb/influxdb.hh index 1da1bf9b987..e70eaafd9cd 100644 --- a/broker/influxdb/inc/com/centreon/broker/influxdb/influxdb.hh +++ b/broker/influxdb/inc/com/centreon/broker/influxdb/influxdb.hh @@ -1,5 +1,5 @@ /** - * Copyright 2015-2017 Centreon + * Copyright 2015-2024 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,12 +35,22 @@ namespace com::centreon::broker::influxdb { */ class influxdb { public: - influxdb(std::string const& user, std::string const& passwd, - std::string const& addr, uint16_t port, std::string const& db, - std::string const& status_ts, std::vector const& status_cols, - std::string const& metric_ts, std::vector const& metric_cols, - macro_cache const& cache); - ~influxdb(); + influxdb(std::string const& user, + std::string const& passwd, + std::string const& addr, + uint16_t port, + std::string const& db, + std::string const& status_ts, + std::vector const& status_cols, + std::string const& metric_ts, + std::vector const& metric_cols, + macro_cache const& cache, + const std::shared_ptr& logger); + + /** + * Destructor. + */ + ~influxdb() noexcept = default; influxdb(influxdb const& f) = delete; influxdb& operator=(influxdb const& f) = delete; @@ -66,11 +76,17 @@ class influxdb { macro_cache const& _cache; + /* Logger */ + std::shared_ptr _logger; + void _connect_socket(); - bool _check_answer_string(std::string const& ans, const std::string& addr, + bool _check_answer_string(std::string const& ans, + const std::string& addr, uint16_t port); - void _create_queries(std::string const& user, std::string const& passwd, - std::string const& db, std::string const& status_ts, + void _create_queries(std::string const& user, + std::string const& passwd, + std::string const& db, + std::string const& status_ts, std::vector const& status_cols, std::string const& metric_ts, std::vector const& metric_cols); diff --git a/broker/influxdb/inc/com/centreon/broker/influxdb/internal.hh b/broker/influxdb/inc/com/centreon/broker/influxdb/internal.hh index 0cd8949aed8..e9d4841bc88 100644 --- a/broker/influxdb/inc/com/centreon/broker/influxdb/internal.hh +++ b/broker/influxdb/inc/com/centreon/broker/influxdb/internal.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2013, 2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2013, 2022 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_INFLUXDB_INTERNAL_HH #define CCB_INFLUXDB_INTERNAL_HH @@ -23,9 +23,8 @@ #include "bbdo/storage.pb.h" #include "com/centreon/broker/io/protobuf.hh" -namespace com::centreon::broker { +namespace com::centreon::broker::storage { -namespace storage { // Data elements. using pb_index_mapping = io::protobuf; -} // namespace storage - -} +} // namespace com::centreon::broker::storage #endif // !CCB_INFLUXDB_INTERNAL_HH diff --git a/broker/influxdb/inc/com/centreon/broker/influxdb/line_protocol_query.hh b/broker/influxdb/inc/com/centreon/broker/influxdb/line_protocol_query.hh index b1d21789aa6..475342ad92c 100644 --- a/broker/influxdb/inc/com/centreon/broker/influxdb/line_protocol_query.hh +++ b/broker/influxdb/inc/com/centreon/broker/influxdb/line_protocol_query.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2015-2017 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2015-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_INFLUXDB_LINE_PROTOCOL_QUERY_HH #define CCB_INFLUXDB_LINE_PROTOCOL_QUERY_HH @@ -24,9 +24,8 @@ #include "com/centreon/broker/influxdb/column.hh" #include "com/centreon/broker/influxdb/macro_cache.hh" -namespace com::centreon::broker { +namespace com::centreon::broker::influxdb { -namespace influxdb { /** * @class line_protocol_query line_protocol_query.hh * "com/centreon/broker/graphite/line_protocol_query.hh" @@ -94,8 +93,7 @@ class line_protocol_query { // Macro cache macro_cache const* _cache; }; -} // namespace influxdb -} +} // namespace com::centreon::broker::influxdb #endif // !CCB_INFLUXDB_LINE_PROTOCOL_QUERY_HH diff --git a/broker/influxdb/inc/com/centreon/broker/influxdb/macro_cache.hh b/broker/influxdb/inc/com/centreon/broker/influxdb/macro_cache.hh index 4329ea29b64..fe5659eace7 100644 --- a/broker/influxdb/inc/com/centreon/broker/influxdb/macro_cache.hh +++ b/broker/influxdb/inc/com/centreon/broker/influxdb/macro_cache.hh @@ -1,34 +1,35 @@ -/* -** Copyright 2015 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2015 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_INFLUXDB_MACRO_CACHE_HH #define CCB_INFLUXDB_MACRO_CACHE_HH #include + #include "com/centreon/broker/influxdb/internal.hh" #include "com/centreon/broker/io/factory.hh" #include "com/centreon/broker/neb/host.hh" #include "com/centreon/broker/neb/instance.hh" #include "com/centreon/broker/neb/service.hh" #include "com/centreon/broker/persistent_cache.hh" -namespace com::centreon::broker { -namespace influxdb { +namespace com::centreon::broker::influxdb { + /** * @class macro_cache macro_cache.hh * "com/centreon/broker/influxdb/macro_cache.hh" @@ -71,8 +72,6 @@ class macro_cache { uint64_t service_id) const; std::string const& get_instance(uint64_t instance_id) const; }; -} // namespace influxdb - -} +} // namespace com::centreon::broker::influxdb #endif // !CCB_INFLUXDB_MACRO_CACHE_HH diff --git a/broker/influxdb/inc/com/centreon/broker/influxdb/stream.hh b/broker/influxdb/inc/com/centreon/broker/influxdb/stream.hh index dbe00f55404..4a96ccae577 100644 --- a/broker/influxdb/inc/com/centreon/broker/influxdb/stream.hh +++ b/broker/influxdb/inc/com/centreon/broker/influxdb/stream.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2011-2017 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2011-2017 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_INFLUXDB_STREAM_HH #define CCB_INFLUXDB_STREAM_HH @@ -23,6 +23,7 @@ #include "com/centreon/broker/influxdb/influxdb.hh" #include "com/centreon/broker/influxdb/macro_cache.hh" #include "com/centreon/broker/io/stream.hh" + #include "com/centreon/broker/persistent_cache.hh" namespace com::centreon::broker { @@ -44,20 +45,24 @@ class stream : public io::stream { const std::string _address; const std::string _db; uint32_t _queries_per_transaction; - std::unique_ptr _influx_db; // Internal working members int _pending_queries; uint32_t _actual_query; bool _commit; - // Cache - macro_cache _cache; - // Status members std::string _status; mutable std::mutex _statusm; + // Cache + macro_cache _cache; + + /* Logger */ + std::shared_ptr _logger; + + std::unique_ptr _influx_db; + public: stream(std::string const& user, std::string const& passwd, @@ -70,7 +75,11 @@ class stream : public io::stream { std::string const& metric_ts, std::vector const& metric_cols, std::shared_ptr const& cache); - ~stream(); + + /** + * Destructor. + */ + ~stream() noexcept = default; int flush() override; bool read(std::shared_ptr& d, time_t deadline) override; void statistics(nlohmann::json& tree) const override; @@ -79,6 +88,6 @@ class stream : public io::stream { }; } // namespace influxdb -} +} // namespace com::centreon::broker #endif // !CCB_INFLUXDB_STREAM_HH diff --git a/broker/influxdb/src/connector.cc b/broker/influxdb/src/connector.cc index 46266612f25..79c4bcc9f99 100644 --- a/broker/influxdb/src/connector.cc +++ b/broker/influxdb/src/connector.cc @@ -1,20 +1,20 @@ /** -* Copyright 2011-2017, 2021 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2017, 2021 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/influxdb/connector.hh" #include "bbdo/storage/index_mapping.hh" @@ -26,12 +26,6 @@ using namespace com::centreon::broker; using namespace com::centreon::broker::influxdb; -/************************************** - * * - * Public Methods * - * * - **************************************/ - static constexpr multiplexing::muxer_filter _influxdb_stream_filter = { storage::metric::static_type(), storage::status::static_type(), storage::pb_metric::static_type(), storage::pb_status::static_type(), @@ -45,10 +39,15 @@ static constexpr multiplexing::muxer_filter _influxdb_stream_filter = { storage::pb_metric_mapping::static_type(), make_type(io::extcmd, extcmd::de_pb_bench)}; +static constexpr multiplexing::muxer_filter _influxdb_forbidden_filter = + multiplexing::muxer_filter(_influxdb_stream_filter).reverse(); + /** * Default constructor. */ -connector::connector() : io::endpoint(false, _influxdb_stream_filter) {} +connector::connector() + : io::endpoint(false, _influxdb_stream_filter, _influxdb_forbidden_filter) { +} /** * Set connection parameters. diff --git a/broker/influxdb/src/influxdb.cc b/broker/influxdb/src/influxdb.cc index 63d0de59cdb..8a8f0c2a190 100644 --- a/broker/influxdb/src/influxdb.cc +++ b/broker/influxdb/src/influxdb.cc @@ -1,30 +1,31 @@ /** -* Copyright 2011-2017, 2021 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2017, 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/influxdb/influxdb.hh" #include -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/string.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace asio; using namespace com::centreon::exceptions; using namespace com::centreon::broker::influxdb; +using log_v2 = com::centreon::common::log_v2::log_v2; static const char* query_footer = "\n"; @@ -40,20 +41,20 @@ influxdb::influxdb(std::string const& user, std::vector const& status_cols, std::string const& metric_ts, std::vector const& metric_cols, - macro_cache const& cache) - : _socket{_io_context}, _host(addr), _port(port), _cache(cache) { + macro_cache const& cache, + const std::shared_ptr& logger) + : _socket{_io_context}, + _host(addr), + _port(port), + _cache(cache), + _logger{logger} { // Try to connect to the server. - log_v2::influxdb()->debug("influxdb: connecting using 1.2 Line Protocol"); + _logger->debug("influxdb: connecting using 1.2 Line Protocol"); _connect_socket(); _create_queries(user, passwd, db, status_ts, status_cols, metric_ts, metric_cols); } -/** - * Destructor. - */ -influxdb::~influxdb() {} - /** * Clear the query. */ @@ -225,8 +226,8 @@ bool influxdb::_check_answer_string(std::string const& ans, return false; std::string first_line_str = ans.substr(0, first_line); - log_v2::influxdb()->debug("influxdb: received an anwser from {}:{}: {}", addr, - port, ans); + _logger->debug("influxdb: received an anwser from {}:{}: {}", addr, port, + ans); // Split the first line using the power of std. std::istringstream iss(first_line_str); @@ -245,7 +246,7 @@ bool influxdb::_check_answer_string(std::string const& ans, return true; else if (ans.find("partial write: points beyond retention policy dropped") != std::string::npos) { - log_v2::influxdb()->info( + _logger->info( "influxdb: sending points beyond " "Influxdb database configured " "retention policy"); diff --git a/broker/influxdb/src/line_protocol_query.cc b/broker/influxdb/src/line_protocol_query.cc index ff1c61910fa..5ad28f91ae9 100644 --- a/broker/influxdb/src/line_protocol_query.cc +++ b/broker/influxdb/src/line_protocol_query.cc @@ -1,29 +1,30 @@ /** -* Copyright 2015-2017 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2015-2014 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/influxdb/line_protocol_query.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/string.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::influxdb; using namespace com::centreon::exceptions; +using log_v2 = com::centreon::common::log_v2::log_v2; /** * Create an empty query. @@ -193,9 +194,9 @@ std::string line_protocol_query::generate_metric(const storage::pb_metric& me) { } } } catch (std::exception const& e) { - log_v2::influxdb()->error( - "influxdb: could not generate query for metric {}: {}", - me.obj().metric_id(), e.what()); + auto logger = log_v2::instance().get(log_v2::INFLUXDB); + logger->error("influxdb: could not generate query for metric {}: {}", + me.obj().metric_id(), e.what()); return ""; } return iss.str(); @@ -229,9 +230,9 @@ std::string line_protocol_query::generate_status(const storage::pb_status& st) { } } } catch (std::exception const& e) { - log_v2::influxdb()->error( - "influxdb: could not generate query for status {}: {}", - st.obj().index_id(), e.what()); + auto logger = log_v2::instance().get(log_v2::INFLUXDB); + logger->error("influxdb: could not generate query for status {}: {}", + st.obj().index_id(), e.what()); return ""; } @@ -328,9 +329,10 @@ void line_protocol_query::_compile_scheme( else if (_type == status) _append_compiled_getter(&line_protocol_query::_get_status_time, escaper); - } else - log_v2::influxdb()->info("influxdb: unknown macro '{}': ignoring it", - macro); + } else { + auto logger = log_v2::instance().get(log_v2::INFLUXDB); + logger->info("influxdb: unknown macro '{}': ignoring it", macro); + } found_macro = end_macro = end_macro + 1; } diff --git a/broker/influxdb/src/macro_cache.cc b/broker/influxdb/src/macro_cache.cc index e3a2e1bb17d..2d3fbbf43ea 100644 --- a/broker/influxdb/src/macro_cache.cc +++ b/broker/influxdb/src/macro_cache.cc @@ -1,25 +1,24 @@ /** -* Copyright 2011-2015, 2019-2022 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2015, 2019-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/influxdb/macro_cache.hh" #include "bbdo/storage/index_mapping.hh" #include "bbdo/storage/metric_mapping.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon::exceptions; @@ -50,7 +49,7 @@ macro_cache::~macro_cache() { try { _save_to_disk(); } catch (std::exception const& e) { - log_v2::influxdb()->error( + _cache->logger()->error( "influxdb: macro cache couldn't save data to disk: '{}'", e.what()); } } diff --git a/broker/influxdb/src/main.cc b/broker/influxdb/src/main.cc index bc962f8ec44..cc9902dd798 100644 --- a/broker/influxdb/src/main.cc +++ b/broker/influxdb/src/main.cc @@ -1,20 +1,20 @@ /** -* Copyright 2011-2013, 2020-2022 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2013, 2020-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "bbdo/storage/index_mapping.hh" #include "bbdo/storage/metric_mapping.hh" @@ -23,12 +23,13 @@ #include "com/centreon/broker/influxdb/stream.hh" #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/io/protocols.hh" -#include "com/centreon/broker/log_v2.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; +using com::centreon::common::log_v2::log_v2; // Load count. -static uint32_t instances(0); +static uint32_t instances = 0; extern "C" { /** @@ -66,11 +67,12 @@ bool broker_module_deinit() { void broker_module_init(void const* arg) { (void)arg; + auto logger = log_v2::instance().get(log_v2::INFLUXDB); // Increment instance number. if (!instances++) { // Storage module. - log_v2::influxdb()->info("influxdb: module for Centreon Broker {}", - CENTREON_BROKER_VERSION); + logger->info("influxdb: module for Centreon Broker {}", + CENTREON_BROKER_VERSION); io::events& e(io::events::instance()); diff --git a/broker/influxdb/src/stream.cc b/broker/influxdb/src/stream.cc index e06c28e2b05..ee0ba081fc9 100644 --- a/broker/influxdb/src/stream.cc +++ b/broker/influxdb/src/stream.cc @@ -1,32 +1,33 @@ /** -* Copyright 2011-2017 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/influxdb/stream.hh" #include "bbdo/storage/metric.hh" #include "com/centreon/broker/exceptions/shutdown.hh" #include "com/centreon/broker/influxdb/influxdb.hh" #include "com/centreon/broker/io/events.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/multiplexing/engine.hh" #include "com/centreon/broker/multiplexing/publisher.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::influxdb; +using log_v2 = com::centreon::common::log_v2::log_v2; /** * Constructor. @@ -53,23 +54,30 @@ stream::stream(std::string const& user, _pending_queries(0), _actual_query(0), _commit(false), - _cache(cache) { - _influx_db.reset(new influxdb(user, passwd, addr, port, db, status_ts, - status_cols, metric_ts, metric_cols, _cache)); + _cache(cache), + _logger{cache ? cache->logger() + : log_v2::instance().get(log_v2::INFLUXDB)}, + _influx_db{std::make_unique(user, + passwd, + addr, + port, + db, + status_ts, + status_cols, + metric_ts, + metric_cols, + _cache, + _logger)} { + _logger->trace("influxdb::stream constructor {}", static_cast(this)); } -/** - * Destructor. - */ -stream::~stream() {} - /** * Flush the stream. * * @return Number of events acknowledged. */ int32_t stream::flush() { - log_v2::influxdb()->debug("influxdb: commiting {} queries", _actual_query); + _logger->debug("influxdb: commiting {} queries", _actual_query); int ret(_pending_queries); _actual_query = 0; _pending_queries = 0; @@ -84,9 +92,9 @@ int32_t stream::flush() { * @return Number of acknowledged events. */ int32_t stream::stop() { + _logger->trace("influxdb::stream stop {}", static_cast(this)); int32_t retval = flush(); - log_v2::core()->info("influxdb stream stopped with {} acknowledged events", - retval); + _logger->info("influxdb stream stopped with {} acknowledged events", retval); return retval; } diff --git a/broker/influxdb/test/influxdb.cc b/broker/influxdb/test/influxdb.cc index dd2c6e3c90e..a25e9353597 100644 --- a/broker/influxdb/test/influxdb.cc +++ b/broker/influxdb/test/influxdb.cc @@ -21,9 +21,11 @@ #include #include "../../core/test/test_server.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; +using com::centreon::common::log_v2::log_v2; class InfluxDB12 : public testing::Test { public: @@ -32,6 +34,7 @@ class InfluxDB12 : public testing::Test { _thread = std::thread(&test_server::run, &_server); _server.wait_for_init(); + _logger = log_v2::instance().get(log_v2::INFLUXDB); } void TearDown() override { _server.stop(); @@ -40,6 +43,7 @@ class InfluxDB12 : public testing::Test { test_server _server; std::thread _thread; + std::shared_ptr _logger; }; TEST_F(InfluxDB12, BadConnection) { @@ -48,10 +52,11 @@ TEST_F(InfluxDB12, BadConnection) { std::vector mcolumns; std::vector scolumns; - ASSERT_THROW(influxdb::influxdb idb("centreon", "pass", "localhost", 4243, - "centreon", "host_status", scolumns, - "host_metrics", mcolumns, mcache), - msg_fmt); + ASSERT_THROW( + influxdb::influxdb idb("centreon", "pass", "localhost", 4243, "centreon", + "host_status", scolumns, "host_metrics", mcolumns, + mcache, _logger), + msg_fmt); } TEST_F(InfluxDB12, Empty) { @@ -62,7 +67,7 @@ TEST_F(InfluxDB12, Empty) { influxdb::influxdb idb("centreon", "pass", "localhost", 4242, "centreon", "host_status", scolumns, "host_metrics", mcolumns, - mcache); + mcache, _logger); idb.clear(); ASSERT_NO_THROW(idb.commit()); } @@ -95,7 +100,7 @@ TEST_F(InfluxDB12, Simple) { influxdb::influxdb idb("centreon", "pass", "localhost", 4242, "centreon", "host_status", scolumns, "host_metrics", mcolumns, - mcache); + mcache, _logger); m1.set_time(2000llu); m1.set_interval(60); m1.set_metric_id(42u); @@ -143,7 +148,7 @@ TEST_F(InfluxDB12, BadServerResponse1) { influxdb::influxdb idb("centreon", "fail1", "localhost", 4242, "centreon", "host_status", scolumns, "host_metrics", mcolumns, - mcache); + mcache, _logger); m1.set_time(2000llu); m1.set_interval(60); @@ -210,7 +215,7 @@ TEST_F(InfluxDB12, BadServerResponse2) { influxdb::influxdb idb("centreon", "fail2", "localhost", 4242, "centreon", "host_status", scolumns, "host_metrics", mcolumns, - mcache); + mcache, _logger); m1.set_time(2000llu); m1.set_interval(60); diff --git a/broker/influxdb/test/line_protocol_query.cc b/broker/influxdb/test/line_protocol_query.cc index b616b535bba..fab86a76c17 100644 --- a/broker/influxdb/test/line_protocol_query.cc +++ b/broker/influxdb/test/line_protocol_query.cc @@ -22,9 +22,11 @@ #include "bbdo/storage/index_mapping.hh" #include "bbdo/storage/metric_mapping.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; +using com::centreon::common::log_v2::log_v2; TEST(InfluxDBLineProtoQuery, EscapeKey) { influxdb::line_protocol_query lpq; @@ -50,7 +52,7 @@ TEST(InfluxDBLineProtoQuery, EscapeValue) { TEST(InfluxDBLineProtoQuery, GenerateMetricExcept) { influxdb::line_protocol_query lpq1; std::vector columns; - std::shared_ptr pcache{nullptr}; + std::shared_ptr pcache; influxdb::macro_cache cache(pcache); influxdb::line_protocol_query lpq2( "test", columns, influxdb::line_protocol_query::status, cache); @@ -65,7 +67,7 @@ TEST(InfluxDBLineProtoQuery, GenerateMetricExcept) { TEST(InfluxDBLineProtoQuery, GenerateMetric) { std::vector columns; - std::shared_ptr pcache{nullptr}; + std::shared_ptr pcache; influxdb::macro_cache cache(pcache); storage::pb_metric pb_m1, pb_m2, pb_m3; Metric &m1 = pb_m1.mut_obj(), &m2 = pb_m2.mut_obj(), &m3 = pb_m3.mut_obj(); @@ -121,7 +123,7 @@ TEST(InfluxDBLineProtoQuery, GenerateMetric) { TEST(InfluxDBLineProtoQuery, ComplexMetric) { std::vector columns; - std::shared_ptr pcache{nullptr}; + std::shared_ptr pcache; influxdb::macro_cache cache(pcache); storage::pb_metric m; Metric& m_obj = m.mut_obj(); @@ -189,7 +191,7 @@ TEST(InfluxDBLineProtoQuery, ComplexMetric) { TEST(InfluxDBLineProtoQuery, ComplexStatus) { std::vector columns; - std::shared_ptr pcache{nullptr}; + std::shared_ptr pcache; influxdb::macro_cache cache(pcache); storage::pb_status s; Status& obj_s = s.mut_obj(); @@ -253,7 +255,7 @@ TEST(InfluxDBLineProtoQuery, ComplexStatus) { TEST(InfluxDBLineProtoQuery, ComplexPbMetric) { std::vector columns; - std::shared_ptr pcache{nullptr}; + std::shared_ptr pcache; influxdb::macro_cache cache(pcache); storage::pb_metric m; Metric& m_obj = m.mut_obj(); @@ -313,7 +315,7 @@ TEST(InfluxDBLineProtoQuery, ComplexPbMetric) { TEST(InfluxDBLineProtoQuery, ComplexPBStatus) { std::vector columns; - std::shared_ptr pcache{nullptr}; + std::shared_ptr pcache; influxdb::macro_cache cache(pcache); storage::pb_status s; Status& obj_s = s.mut_obj(); @@ -371,7 +373,7 @@ TEST(InfluxDBLineProtoQuery, ComplexPBStatus) { TEST(InfluxDBLineProtoQuery, Except) { std::vector columns; - std::shared_ptr pcache{nullptr}; + std::shared_ptr pcache; influxdb::macro_cache cache(pcache); storage::pb_metric m; storage::pb_status s; diff --git a/broker/lua/inc/com/centreon/broker/lua/broker_cache.hh b/broker/lua/inc/com/centreon/broker/lua/broker_cache.hh index 96536e43c1b..2c526260d79 100644 --- a/broker/lua/inc/com/centreon/broker/lua/broker_cache.hh +++ b/broker/lua/inc/com/centreon/broker/lua/broker_cache.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2018 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2018 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_LUA_BROKER_CACHE_HH #define CCB_LUA_BROKER_CACHE_HH @@ -27,9 +27,8 @@ extern "C" { #include "lualib.h" } -namespace com::centreon::broker { +namespace com::centreon::broker::lua { -namespace lua { /** * @class broker_cache broker_cache.hh * "com/centreon/broker/lua/broker_cache.hh" @@ -43,8 +42,7 @@ class broker_cache { macro_cache const& cache, uint32_t api_version); }; -} // namespace lua -} +} // namespace com::centreon::broker::lua #endif // !CCB_LUA_BROKER_CACHE_HH diff --git a/broker/lua/inc/com/centreon/broker/lua/broker_event.hh b/broker/lua/inc/com/centreon/broker/lua/broker_event.hh index a5496a0787a..3fc272ac5ab 100644 --- a/broker/lua/inc/com/centreon/broker/lua/broker_event.hh +++ b/broker/lua/inc/com/centreon/broker/lua/broker_event.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2020 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2020 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_LUA_BROKER_EVENT_HH #define CCB_LUA_BROKER_EVENT_HH @@ -27,9 +27,8 @@ extern "C" { #include "lualib.h" } -namespace com::centreon::broker { +namespace com::centreon::broker::lua { -namespace lua { /** * @class broker_event broker_event.hh * "com/centreon/broker/lua/broker_event.hh" @@ -66,8 +65,7 @@ class broker_event { static void create_as_table(lua_State* L, const io::data& e); static void lua_close(const lua_State* L); }; -} // namespace lua -} // namespace com::centreon::broker +} // namespace com::centreon::broker::lua #endif // !CCB_LUA_BROKER_EVENT_HH diff --git a/broker/lua/inc/com/centreon/broker/lua/broker_log.hh b/broker/lua/inc/com/centreon/broker/lua/broker_log.hh index 43dec8e20c0..cbb4e8b1159 100644 --- a/broker/lua/inc/com/centreon/broker/lua/broker_log.hh +++ b/broker/lua/inc/com/centreon/broker/lua/broker_log.hh @@ -1,29 +1,28 @@ -/* -** Copyright 2018 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2018 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_LUA_BROKER_LOG_HH #define CCB_LUA_BROKER_LOG_HH #include "com/centreon/broker/lua/luabinding.hh" -namespace com::centreon::broker { +namespace com::centreon::broker::lua { -namespace lua { /** * @class broker_log broker_log.hh "com/centreon/broker/lua/broker_log.hh" * @brief Class managing the Lua connector logs @@ -45,8 +44,6 @@ class broker_log { std::string _file; int _level; }; -} // namespace lua - -} +} // namespace com::centreon::broker::lua #endif // !CCB_LUA_BROKER_LOG_HH diff --git a/broker/lua/inc/com/centreon/broker/lua/broker_socket.hh b/broker/lua/inc/com/centreon/broker/lua/broker_socket.hh index 118bfd10a4b..72f00dc8a5c 100644 --- a/broker/lua/inc/com/centreon/broker/lua/broker_socket.hh +++ b/broker/lua/inc/com/centreon/broker/lua/broker_socket.hh @@ -1,34 +1,32 @@ -/* -** Copyright 2018 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2018 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_LUA_BROKER_SOCKET_HH #define CCB_LUA_BROKER_SOCKET_HH - extern "C" { #include "lauxlib.h" #include "lua.h" #include "lualib.h" } -namespace com::centreon::broker { +namespace com::centreon::broker::lua { -namespace lua { /** * @class broker_socket broker_socket.hh * "com/centreon/broker/lua/broker_socket.hh" @@ -40,8 +38,7 @@ class broker_socket { public: static void broker_socket_reg(lua_State* L); }; -} // namespace lua -} +} // namespace com::centreon::broker::lua #endif // !CCB_LUA_BROKER_SOCKET_HH diff --git a/broker/lua/inc/com/centreon/broker/lua/broker_utils.hh b/broker/lua/inc/com/centreon/broker/lua/broker_utils.hh index 959bb7b5002..df7899ad8aa 100644 --- a/broker/lua/inc/com/centreon/broker/lua/broker_utils.hh +++ b/broker/lua/inc/com/centreon/broker/lua/broker_utils.hh @@ -1,34 +1,32 @@ -/* -** Copyright 2018 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2018 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_LUA_BROKER_UTILS_HH #define CCB_LUA_BROKER_UTILS_HH - extern "C" { #include "lauxlib.h" #include "lua.h" #include "lualib.h" } -namespace com::centreon::broker { +namespace com::centreon::broker::lua { -namespace lua { /** * @class broker_utils broker_utils.hh * "com/centreon/broker/lua/broker_utils.hh" @@ -40,8 +38,7 @@ class broker_utils { public: static void broker_utils_reg(lua_State* L); }; -} // namespace lua -} +} // namespace com::centreon::broker::lua #endif // !CCB_LUA_BROKER_UTILS_HH diff --git a/broker/lua/inc/com/centreon/broker/lua/connector.hh b/broker/lua/inc/com/centreon/broker/lua/connector.hh index ff7f273a3f4..84776e2ac80 100644 --- a/broker/lua/inc/com/centreon/broker/lua/connector.hh +++ b/broker/lua/inc/com/centreon/broker/lua/connector.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2017-2018 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2017-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_LUA_CONNECTOR_HH #define CCB_LUA_CONNECTOR_HH @@ -22,9 +22,8 @@ #include "com/centreon/broker/io/endpoint.hh" #include "com/centreon/broker/misc/variant.hh" -namespace com::centreon::broker { +namespace com::centreon::broker::lua { -namespace lua { /** * @class connector connector.hh "com/centreon/broker/lua/connector.hh" * @brief Connect to a lua interpreter. @@ -47,8 +46,7 @@ class connector : public io::endpoint { std::map _conf_params; std::shared_ptr _cache; }; -} // namespace lua -} +} // namespace com::centreon::broker::lua #endif // !CCB_LUA_CONNECTOR_HH diff --git a/broker/lua/inc/com/centreon/broker/lua/factory.hh b/broker/lua/inc/com/centreon/broker/lua/factory.hh index 2d7a8359c6c..0214a417a92 100644 --- a/broker/lua/inc/com/centreon/broker/lua/factory.hh +++ b/broker/lua/inc/com/centreon/broker/lua/factory.hh @@ -1,29 +1,28 @@ -/* -** Copyright 2017-2018 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2017-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_LUA_FACTORY_HH #define CCB_LUA_FACTORY_HH #include "com/centreon/broker/io/factory.hh" -namespace com::centreon::broker { +namespace com::centreon::broker::lua { -namespace lua { /** * @class factory factory.hh "com/centreon/broker/lua/factory.hh" * @brief lua layer factory. @@ -43,8 +42,7 @@ class factory : public io::factory { std::shared_ptr cache = std::shared_ptr()) const override; }; -} // namespace lua -} +} // namespace com::centreon::broker::lua #endif // !CCB_LUA_FACTORY_HH diff --git a/broker/lua/inc/com/centreon/broker/lua/internal.hh b/broker/lua/inc/com/centreon/broker/lua/internal.hh index 888d06b6424..d32113b8b31 100644 --- a/broker/lua/inc/com/centreon/broker/lua/internal.hh +++ b/broker/lua/inc/com/centreon/broker/lua/internal.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_LUA_INTERNAL_HH #define CCB_LUA_INTERNAL_HH @@ -23,16 +23,15 @@ #include "bbdo/storage.pb.h" #include "com/centreon/broker/io/protobuf.hh" -namespace com::centreon::broker { +namespace com::centreon::broker::storage { -namespace storage { using pb_index_mapping = io::protobuf; using pb_metric_mapping = io::protobuf; -} // namespace storage -} + +} // namespace com::centreon::broker::storage #endif // !CCB_LUA_INTERNAL_HH diff --git a/broker/lua/inc/com/centreon/broker/lua/luabinding.hh b/broker/lua/inc/com/centreon/broker/lua/luabinding.hh index 74b5a048ce0..919c34588a0 100644 --- a/broker/lua/inc/com/centreon/broker/lua/luabinding.hh +++ b/broker/lua/inc/com/centreon/broker/lua/luabinding.hh @@ -28,9 +28,7 @@ extern "C" { #include "lualib.h" } -namespace com::centreon::broker { - -namespace lua { +namespace com::centreon::broker::lua { /** * @class luabinding luabinding.hh * "com/centreon/broker/luabinding/luabinding.hh" @@ -101,6 +99,9 @@ class luabinding { // Api version among (1, 2) uint32_t _broker_api_version; + // logger. + std::shared_ptr _logger; + lua_State* _load_interpreter(); void _load_script(const std::string& lua_script); void _init_script(std::map const& conf_params); @@ -123,8 +124,6 @@ class luabinding { // Event conversion to Lua table. void push_event_as_table(lua_State* L, io::data const& d); -} // namespace lua - -} // namespace com::centreon::broker +} // namespace com::centreon::broker::lua #endif // !CCB_LUA_LUA_HH diff --git a/broker/lua/inc/com/centreon/broker/lua/macro_cache.hh b/broker/lua/inc/com/centreon/broker/lua/macro_cache.hh index 210ecc8aa1f..616f2afe377 100644 --- a/broker/lua/inc/com/centreon/broker/lua/macro_cache.hh +++ b/broker/lua/inc/com/centreon/broker/lua/macro_cache.hh @@ -32,9 +32,8 @@ #include "com/centreon/broker/neb/service_group_member.hh" #include "com/centreon/broker/persistent_cache.hh" -namespace com::centreon::broker { +namespace com::centreon::broker::lua { -namespace lua { /** * @class macro_cache macro_cache.hh "com/centreon/broker/lua/macro_cache.hh" * @brief Data cache for Lua macro. @@ -68,7 +67,8 @@ class macro_cache { _dimension_bv_events; public: - macro_cache(std::shared_ptr const& cache); + macro_cache(const std::shared_ptr& cache); + macro_cache(const macro_cache&) = delete; ~macro_cache(); void write(std::shared_ptr const& data); @@ -109,7 +109,6 @@ class macro_cache { uint64_t id) const; private: - macro_cache(macro_cache const& f); macro_cache& operator=(macro_cache const& f); void _process_instance(std::shared_ptr const& data); @@ -145,8 +144,6 @@ class macro_cache { void _save_to_disk(); }; -} // namespace lua - -} // namespace com::centreon::broker +} // namespace com::centreon::broker::lua #endif // !CCB_LUA_MACRO_CACHE_HH diff --git a/broker/lua/inc/com/centreon/broker/lua/stream.hh b/broker/lua/inc/com/centreon/broker/lua/stream.hh index 86705e29567..381aadbaaac 100644 --- a/broker/lua/inc/com/centreon/broker/lua/stream.hh +++ b/broker/lua/inc/com/centreon/broker/lua/stream.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2018-2021 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2018-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_LUA_STREAM_HH #define CCB_LUA_STREAM_HH @@ -25,9 +25,7 @@ #include "com/centreon/broker/lua/macro_cache.hh" #include "com/centreon/broker/misc/variant.hh" -namespace com::centreon::broker { - -namespace lua { +namespace com::centreon::broker::lua { /** * @class stream stream.hh "com/centreon/broker/lua/stream.hh" @@ -51,12 +49,14 @@ namespace lua { * exit, the thread waits for 500ms before rechecking events. */ class stream : public io::stream { - /* Macro cache */ - macro_cache _cache; - /* The Lua engine */ luabinding _luabinding; + std::shared_ptr _logger; + + /* Macro cache */ + macro_cache _cache; + public: stream(std::string const& lua_script, std::map const& conf_params, @@ -69,8 +69,7 @@ class stream : public io::stream { int32_t flush() override; int32_t stop() override; }; -} // namespace lua -} +} // namespace com::centreon::broker::lua #endif // !CCB_LUA_STREAM_HH diff --git a/broker/lua/src/broker_cache.cc b/broker/lua/src/broker_cache.cc index 1c5b708d67e..817e4570d5e 100644 --- a/broker/lua/src/broker_cache.cc +++ b/broker/lua/src/broker_cache.cc @@ -1,20 +1,20 @@ /** -* Copyright 2018 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2018 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/lua/broker_cache.hh" diff --git a/broker/lua/src/broker_log.cc b/broker/lua/src/broker_log.cc index 7e92ea53b8d..cdefc36fdd6 100644 --- a/broker/lua/src/broker_log.cc +++ b/broker/lua/src/broker_log.cc @@ -1,26 +1,27 @@ /** -* Copyright 2018 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2018 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/lua/broker_log.hh" -#include "com/centreon/broker/log_v2.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::lua; +using com::centreon::common::log_v2::log_v2; /** * The broker_log destructor @@ -58,27 +59,27 @@ int _log_func(int log_level, lua_State* L, const char* header) { broker_log* bl( *static_cast(luaL_checkudata(L, 1, "lua_broker_log"))); int level(lua_tointeger(L, 2)); - char const* text(lua_tostring(L, 3)); + const char* text = lua_tostring(L, 3); + auto logger = log_v2::instance().get(log_v2::LUA); if (level <= bl->get_level()) { if (bl->get_file().empty()) { switch (log_level) { case 0: - log_v2::lua()->info(text); + logger->info(text); break; case 1: - log_v2::lua()->warn(text); + logger->warn(text); break; - case 2: - log_v2::lua()->error(text); + default: + logger->error(text); break; } } else { std::ofstream of; of.open(bl->get_file().c_str(), std::ios_base::app); - if (of.fail()) - log_v2::lua()->error("Unable to open the log file '{}'", - bl->get_file()); - else { + if (of.fail()) { + logger->error("Unable to open the log file '{}'", bl->get_file()); + } else { time_t now(time(nullptr)); struct tm tmp; localtime_r(&now, &tmp); diff --git a/broker/lua/src/broker_utils.cc b/broker/lua/src/broker_utils.cc index 9c03b1759fa..3cb18b162dc 100644 --- a/broker/lua/src/broker_utils.cc +++ b/broker/lua/src/broker_utils.cc @@ -34,15 +34,16 @@ #include "com/centreon/broker/io/data.hh" #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/io/protobuf.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/mapping/entry.hh" #include "com/centreon/broker/misc/misc.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::lua; using namespace com::centreon::exceptions; using namespace nlohmann; +using com::centreon::common::log_v2::log_v2; static void broker_json_encode(lua_State* L, std::ostringstream& oss); static void broker_json_decode(lua_State* L, const json& it); @@ -470,7 +471,8 @@ static int l_broker_json_encode(lua_State* L) noexcept { lua_pushlstring(L, s.c_str(), s.size()); return 1; } catch (const std::exception& e) { - log_v2::lua()->error("lua: json_encode encountered an error: {}", e.what()); + auto logger = log_v2::instance().get(log_v2::LUA); + logger->error("lua: json_encode encountered an error: {}", e.what()); } return 0; } @@ -624,7 +626,8 @@ static auto l_stacktrace = [](lua_State* L) -> void { static int l_broker_parse_perfdata(lua_State* L) { char const* perf_data(lua_tostring(L, 1)); int full(lua_toboolean(L, 2)); - std::list pds{misc::parse_perfdata(0, 0, perf_data)}; + auto logger = log_v2::instance().get(log_v2::LUA); + std::list pds{misc::parse_perfdata(0, 0, perf_data, logger)}; lua_createtable(L, 0, pds.size()); for (auto const& pd : pds) { lua_pushlstring(L, pd.name().c_str(), pd.name().size()); diff --git a/broker/lua/src/connector.cc b/broker/lua/src/connector.cc index c148a111302..bfd870df5b6 100644 --- a/broker/lua/src/connector.cc +++ b/broker/lua/src/connector.cc @@ -1,23 +1,24 @@ /** -* Copyright 2017-2018 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2017-2018 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/lua/connector.hh" #include "com/centreon/broker/lua/stream.hh" +#include "com/centreon/broker/multiplexing/muxer_filter.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::lua; @@ -25,7 +26,12 @@ using namespace com::centreon::broker::lua; /** * Default constructor. */ -connector::connector() : io::endpoint(false, {}) {} +connector::connector() + : io::endpoint( + false, + multiplexing::muxer_filter(multiplexing::muxer_filter::zero_init()), + multiplexing::muxer_filter(multiplexing::muxer_filter::zero_init()) + .add_category(io::local)) {} /** * Copy constructor. diff --git a/broker/lua/src/luabinding.cc b/broker/lua/src/luabinding.cc index 59f8483d9f1..b71948aace0 100644 --- a/broker/lua/src/luabinding.cc +++ b/broker/lua/src/luabinding.cc @@ -20,18 +20,20 @@ #include -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/lua/broker_cache.hh" #include "com/centreon/broker/lua/broker_event.hh" #include "com/centreon/broker/lua/broker_log.hh" #include "com/centreon/broker/lua/broker_socket.hh" #include "com/centreon/broker/lua/broker_utils.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::lua; using namespace com::centreon::exceptions; +using com::centreon::common::log_v2::log_v2; + #ifdef LUA51 static int l_pairs(lua_State* L) { if (!luaL_getmetafield(L, 1, "__next")) @@ -61,14 +63,14 @@ luabinding::luabinding(std::string const& lua_script, _flush{false}, _cache(cache), _total{0}, - _broker_api_version{1} { + _broker_api_version{1}, + _logger{log_v2::instance().get(log_v2::LUA)} { size_t pos(lua_script.find_last_of('/')); std::string path(lua_script.substr(0, pos)); _L = _load_interpreter(); _update_lua_path(path); - SPDLOG_LOGGER_DEBUG(log_v2::lua(), - "lua: initializing the Lua virtual machine"); + SPDLOG_LOGGER_DEBUG(_logger, "lua: initializing the Lua virtual machine"); try { _load_script(lua_script); @@ -177,7 +179,7 @@ void luabinding::_load_script(const std::string& lua_script) { lua_getglobal(_L, "filter"); if (!lua_isfunction(_L, lua_gettop(_L))) { SPDLOG_LOGGER_DEBUG( - log_v2::lua(), + _logger, "lua: filter() global function is missing, the write() function will " "be called for each event"); _filter = false; @@ -190,16 +192,14 @@ void luabinding::_load_script(const std::string& lua_script) { if (lua_pcall(_L, 2, 1, 0) != 0) { const char* ret = lua_tostring(_L, -1); if (ret) - log_v2::lua()->error( - "lua: The filter() function doesn't work correctly: {}", ret); + _logger->error("lua: The filter() function doesn't work correctly: {}", + ret); else - log_v2::lua()->error( - "lua: The filter() function doesn't work correctly"); + _logger->error("lua: The filter() function doesn't work correctly"); _filter = false; } else { if (!lua_isboolean(_L, -1)) { - log_v2::lua()->error( - "lua: The filter() function should return a boolean."); + _logger->error("lua: The filter() function should return a boolean."); _filter = false; } } @@ -209,8 +209,7 @@ void luabinding::_load_script(const std::string& lua_script) { // Checking for flush() availability: this function is optional lua_getglobal(_L, "flush"); if (!lua_isfunction(_L, lua_gettop(_L))) { - SPDLOG_LOGGER_DEBUG(log_v2::lua(), - "lua: flush() global function is not defined"); + SPDLOG_LOGGER_DEBUG(_logger, "lua: flush() global function is not defined"); _flush = false; } else _flush = true; @@ -233,7 +232,7 @@ void luabinding::_load_script(const std::string& lua_script) { if (_broker_api_version != 1 && _broker_api_version != 2) { SPDLOG_LOGGER_ERROR( - log_v2::lua(), + _logger, "broker_api_version represents the Lua broker api to use, it must be " "one of (1, 2) and not '{}'. Setting it to 1", _broker_api_version); @@ -250,7 +249,7 @@ void luabinding::_load_script(const std::string& lua_script) { } #endif - SPDLOG_LOGGER_INFO(log_v2::lua(), "Lua broker_api_version set to {}", + SPDLOG_LOGGER_INFO(_logger, "Lua broker_api_version set to {}", _broker_api_version); // Registers the broker_log object @@ -332,8 +331,11 @@ void luabinding::_init_script( */ int luabinding::write(std::shared_ptr const& data) noexcept { int retval = 0; - if (log_v2::lua()->level() == spdlog::level::trace) { - SPDLOG_LOGGER_TRACE(log_v2::lua(), "lua: luabinding::write call {}", *data); + + if (_logger->level() == spdlog::level::trace) { + SPDLOG_LOGGER_TRACE(_logger, "lua: luabinding::write call {}", *data); + } else { + SPDLOG_LOGGER_DEBUG(_logger, "lua: luabinding::write call"); } // Give data to cache. @@ -358,23 +360,21 @@ int luabinding::write(std::shared_ptr const& data) noexcept { if (lua_pcall(_L, 2, 1, 0) != 0) { const char* ret = lua_tostring(_L, -1); if (ret) - SPDLOG_LOGGER_ERROR(log_v2::lua(), - "lua: error while running function `filter()': {}", - ret); + SPDLOG_LOGGER_ERROR( + _logger, "lua: error while running function `filter()': {}", ret); else SPDLOG_LOGGER_ERROR( - log_v2::lua(), - "lua: unknown error while running function `filter()'"); + _logger, "lua: unknown error while running function `filter()'"); RETURN_AND_POP(0); } if (!lua_isboolean(_L, -1)) { - SPDLOG_LOGGER_ERROR(log_v2::lua(), "lua: `filter' must return a boolean"); + SPDLOG_LOGGER_ERROR(_logger, "lua: `filter' must return a boolean"); RETURN_AND_POP(0); } execute_write = lua_toboolean(_L, -1); - SPDLOG_LOGGER_DEBUG(log_v2::lua(), "lua: `filter' returned {}", + SPDLOG_LOGGER_DEBUG(_logger, "lua: `filter' returned {}", (execute_write ? "true" : "false")); lua_pop(_L, lua_gettop(_L)); } @@ -401,16 +401,16 @@ int luabinding::write(std::shared_ptr const& data) noexcept { if (lua_pcall(_L, 1, 1, 0) != 0) { const char* ret = lua_tostring(_L, -1); if (ret) - SPDLOG_LOGGER_ERROR(log_v2::lua(), - "lua: error running function `write' {}", ret); + SPDLOG_LOGGER_ERROR(_logger, "lua: error running function `write' {}", + ret); else - SPDLOG_LOGGER_ERROR(log_v2::lua(), + SPDLOG_LOGGER_ERROR(_logger, "lua: unknown error running function `write'"); RETURN_AND_POP(0); } if (!lua_isboolean(_L, -1)) { - SPDLOG_LOGGER_ERROR(log_v2::lua(), "lua: `write' must return a boolean"); + SPDLOG_LOGGER_ERROR(_logger, "lua: `write' must return a boolean"); RETURN_AND_POP(0); } int acknowledge = lua_toboolean(_L, -1); @@ -446,15 +446,15 @@ int32_t luabinding::flush() noexcept { if (lua_pcall(_L, 0, 1, 0) != 0) { const char* ret = lua_tostring(_L, -1); if (ret) - SPDLOG_LOGGER_ERROR(log_v2::lua(), - "lua: error running function `flush' {}", ret); + SPDLOG_LOGGER_ERROR(_logger, "lua: error running function `flush' {}", + ret); else - SPDLOG_LOGGER_ERROR(log_v2::lua(), + SPDLOG_LOGGER_ERROR(_logger, "lua: unknown error running function `flush'"); RETURN_AND_POP(0); } if (!lua_isboolean(_L, -1)) { - SPDLOG_LOGGER_ERROR(log_v2::lua(), "lua: `flush' must return a boolean"); + SPDLOG_LOGGER_ERROR(_logger, "lua: `flush' must return a boolean"); RETURN_AND_POP(0); } bool acknowledge = lua_toboolean(_L, -1); diff --git a/broker/lua/src/macro_cache.cc b/broker/lua/src/macro_cache.cc index 366d139e6ea..0c848b5d092 100644 --- a/broker/lua/src/macro_cache.cc +++ b/broker/lua/src/macro_cache.cc @@ -22,8 +22,8 @@ #include "bbdo/bam/dimension_bv_event.hh" #include "bbdo/storage/index_mapping.hh" #include "bbdo/storage/metric_mapping.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; @@ -53,7 +53,7 @@ macro_cache::~macro_cache() { try { _save_to_disk(); } catch (std::exception const& e) { - SPDLOG_LOGGER_ERROR(log_v2::lua(), + SPDLOG_LOGGER_ERROR(_cache->logger(), "lua: macro cache couldn't save data to disk: '{}'", e.what()); } @@ -636,7 +636,7 @@ void macro_cache::_process_pb_instance(std::shared_ptr const& data) { void macro_cache::_process_host(std::shared_ptr const& data) { std::shared_ptr const& h = std::static_pointer_cast(data); - SPDLOG_LOGGER_DEBUG(log_v2::lua(), "lua: processing host '{}' of id {}", + SPDLOG_LOGGER_DEBUG(_cache->logger(), "lua: processing host '{}' of id {}", h->host_name, h->host_id); if (h->enabled) _hosts[h->host_id] = data; @@ -652,7 +652,7 @@ void macro_cache::_process_host(std::shared_ptr const& data) { void macro_cache::_process_pb_host(std::shared_ptr const& data) { std::shared_ptr const& h = std::static_pointer_cast(data); - SPDLOG_LOGGER_DEBUG(log_v2::lua(), "lua: processing host '{}' of id {}", + SPDLOG_LOGGER_DEBUG(_cache->logger(), "lua: processing host '{}' of id {}", h->obj().name(), h->obj().host_id()); if (h->obj().enabled()) _hosts[h->obj().host_id()] = data; @@ -665,12 +665,12 @@ void macro_cache::_process_pb_host_status( const auto& s = std::static_pointer_cast(data); const auto& obj = s->obj(); - SPDLOG_LOGGER_DEBUG(log_v2::lua(), "lua: processing host status ({})", + SPDLOG_LOGGER_DEBUG(_cache->logger(), "lua: processing host status ({})", obj.host_id()); auto it = _hosts.find(obj.host_id()); if (it == _hosts.end()) { - log_v2::lua()->warn( + _cache->logger()->warn( "lua: Attempt to update host ({}) in lua cache, but it does not " "exist. Maybe Engine should be restarted to update the cache.", obj.host_id()); @@ -734,8 +734,8 @@ void macro_cache::_process_pb_host_status( hst.set_acknowledgement_type(obj.acknowledgement_type()); hst.set_scheduled_downtime_depth(obj.scheduled_downtime_depth()); } else { - log_v2::lua()->error("lua: The host ({}) stored in cache is corrupted", - obj.host_id()); + _cache->logger()->error("lua: The host ({}) stored in cache is corrupted", + obj.host_id()); } } /** @@ -746,7 +746,7 @@ void macro_cache::_process_pb_host_status( void macro_cache::_process_pb_adaptive_host( const std::shared_ptr& data) { const auto& h = std::static_pointer_cast(data); - SPDLOG_LOGGER_DEBUG(log_v2::lua(), "lua: processing adaptive host {}", + SPDLOG_LOGGER_DEBUG(_cache->logger(), "lua: processing adaptive host {}", h->obj().host_id()); auto& ah = h->obj(); auto it = _hosts.find(ah.host_id()); @@ -818,7 +818,7 @@ void macro_cache::_process_pb_adaptive_host( } } else SPDLOG_LOGGER_WARN( - log_v2::lua(), + _cache->logger(), "lua: cannot update cache for host {}, it does not exist in " "the cache", h->obj().host_id()); @@ -832,7 +832,7 @@ void macro_cache::_process_pb_adaptive_host( void macro_cache::_process_host_group(std::shared_ptr const& data) { std::shared_ptr const& hg = std::static_pointer_cast(data); - SPDLOG_LOGGER_DEBUG(log_v2::lua(), + SPDLOG_LOGGER_DEBUG(_cache->logger(), "lua: processing host group '{}' of id {} enabled: {}", hg->name, hg->id, hg->enabled); if (hg->enabled) @@ -849,7 +849,7 @@ void macro_cache::_process_pb_host_group( std::shared_ptr const& data) { const HostGroup& hg = std::static_pointer_cast(data)->obj(); - SPDLOG_LOGGER_DEBUG(log_v2::lua(), + SPDLOG_LOGGER_DEBUG(_cache->logger(), "lua: processing pb host group '{}' of id {}, enabled {}", hg.name(), hg.hostgroup_id(), hg.enabled()); if (hg.enabled()) @@ -867,7 +867,7 @@ void macro_cache::_process_host_group_member( std::shared_ptr const& hgm = std::static_pointer_cast(data); SPDLOG_LOGGER_DEBUG( - log_v2::lua(), + _cache->logger(), "lua: processing host group member (group_name: '{}', group_id: {}, " "host_id: {}, enabled: {})", hgm->group_name, hgm->group_id, hgm->host_id, hgm->enabled); @@ -887,7 +887,7 @@ void macro_cache::_process_pb_host_group_member( const HostGroupMember& hgm = std::static_pointer_cast(data)->obj(); SPDLOG_LOGGER_DEBUG( - log_v2::lua(), + _cache->logger(), "lua: processing pb host group member (group_name: '{}', group_id: {}, " "host_id: {}, enabled: {})", hgm.name(), hgm.hostgroup_id(), hgm.host_id(), hgm.enabled()); @@ -904,7 +904,7 @@ void macro_cache::_process_pb_host_group_member( */ void macro_cache::_process_service(std::shared_ptr const& data) { auto const& s = std::static_pointer_cast(data); - SPDLOG_LOGGER_DEBUG(log_v2::lua(), + SPDLOG_LOGGER_DEBUG(_cache->logger(), "lua: processing service ({}, {}) (description:{})", s->host_id, s->service_id, s->service_description); if (s->enabled) @@ -921,7 +921,7 @@ void macro_cache::_process_service(std::shared_ptr const& data) { void macro_cache::_process_pb_service(std::shared_ptr const& data) { auto const& s = std::static_pointer_cast(data); SPDLOG_LOGGER_DEBUG( - log_v2::lua(), "lua: processing service ({}, {}) (description:{})", + _cache->logger(), "lua: processing service ({}, {}) (description:{})", s->obj().host_id(), s->obj().service_id(), s->obj().description()); if (s->obj().enabled()) _services[{s->obj().host_id(), s->obj().service_id()}] = data; @@ -934,12 +934,13 @@ void macro_cache::_process_pb_service_status( const auto& s = std::static_pointer_cast(data); const auto& obj = s->obj(); - SPDLOG_LOGGER_DEBUG(log_v2::lua(), "lua: processing service status ({}, {})", - obj.host_id(), obj.service_id()); + SPDLOG_LOGGER_DEBUG(_cache->logger(), + "lua: processing service status ({}, {})", obj.host_id(), + obj.service_id()); auto it = _services.find({obj.host_id(), obj.service_id()}); if (it == _services.end()) { - log_v2::lua()->warn( + _cache->logger()->warn( "lua: Attempt to update service ({}, {}) in lua cache, but it does not " "exist. Maybe Engine should be restarted to update the cache.", obj.host_id(), obj.service_id()); @@ -1006,7 +1007,7 @@ void macro_cache::_process_pb_service_status( svc.set_acknowledgement_type(obj.acknowledgement_type()); svc.set_scheduled_downtime_depth(obj.scheduled_downtime_depth()); } else { - log_v2::lua()->error( + _cache->logger()->error( "lua: The service ({}, {}) stored in cache is corrupted", obj.host_id(), obj.service_id()); } @@ -1020,7 +1021,7 @@ void macro_cache::_process_pb_service_status( void macro_cache::_process_pb_adaptive_service( std::shared_ptr const& data) { const auto& s = std::static_pointer_cast(data); - SPDLOG_LOGGER_DEBUG(log_v2::lua(), + SPDLOG_LOGGER_DEBUG(_cache->logger(), "lua: processing adaptive service ({}, {})", s->obj().host_id(), s->obj().service_id()); auto& as = s->obj(); @@ -1094,7 +1095,7 @@ void macro_cache::_process_pb_adaptive_service( } } else { SPDLOG_LOGGER_WARN( - log_v2::lua(), + _cache->logger(), "lua: cannot update cache for service ({}, {}), it does not exist in " "the cache", s->obj().host_id(), s->obj().service_id()); @@ -1109,7 +1110,7 @@ void macro_cache::_process_pb_adaptive_service( void macro_cache::_process_service_group( std::shared_ptr const& data) { auto const& sg = std::static_pointer_cast(data); - SPDLOG_LOGGER_DEBUG(log_v2::lua(), + SPDLOG_LOGGER_DEBUG(_cache->logger(), "lua: processing service group '{}' of id {}", sg->name, sg->id); if (sg->enabled) @@ -1126,7 +1127,7 @@ void macro_cache::_process_pb_service_group( std::shared_ptr const& data) { const ServiceGroup& sg = std::static_pointer_cast(data)->obj(); - SPDLOG_LOGGER_DEBUG(log_v2::lua(), + SPDLOG_LOGGER_DEBUG(_cache->logger(), "lua: processing pb service group '{}' of id {}", sg.name(), sg.servicegroup_id()); if (sg.enabled()) @@ -1143,7 +1144,7 @@ void macro_cache::_process_service_group_member( std::shared_ptr const& data) { auto const& sgm = std::static_pointer_cast(data); SPDLOG_LOGGER_DEBUG( - log_v2::lua(), + _cache->logger(), "lua: processing service group member (group_name: {}, group_id: {}, " "host_id: {}, service_id: {}, enabled: {}", sgm->group_name, sgm->group_id, sgm->host_id, sgm->service_id, @@ -1165,12 +1166,12 @@ void macro_cache::_process_pb_service_group_member( std::shared_ptr const& data) { const ServiceGroupMember& sgm = std::static_pointer_cast(data)->obj(); - SPDLOG_LOGGER_DEBUG(log_v2::lua(), - "lua: processing pb service group member (group_name: " - "{}, group_id: {}, " - "host_id: {}, service_id: {} enabled: {}", - sgm.name(), sgm.servicegroup_id(), sgm.host_id(), - sgm.service_id(), sgm.enabled()); + SPDLOG_LOGGER_DEBUG( + _cache->logger(), + "lua: processing pb service group member (group_name: {}, group_id: {}, " + "host_id: {}, service_id: {} enabled: {}", + sgm.name(), sgm.servicegroup_id(), sgm.host_id(), sgm.service_id(), + sgm.enabled()); if (sgm.enabled()) _service_group_members[std::make_tuple(sgm.host_id(), sgm.service_id(), sgm.servicegroup_id())] = data; @@ -1247,7 +1248,7 @@ void macro_cache::_process_dimension_ba_event( if (data->type() == bam::pb_dimension_ba_event::static_type()) { auto const& dbae = std::static_pointer_cast(data); - SPDLOG_LOGGER_DEBUG(log_v2::lua(), + SPDLOG_LOGGER_DEBUG(_cache->logger(), "lua: pb processing dimension ba event of id {}", dbae->obj().ba_id()); _dimension_ba_events[dbae->obj().ba_id()] = dbae; @@ -1263,7 +1264,7 @@ void macro_cache::_process_dimension_ba_event( to_fill.set_sla_month_percent_warn(to_convert->sla_month_percent_warn); to_fill.set_sla_duration_crit(to_convert->sla_duration_crit); to_fill.set_sla_duration_warn(to_convert->sla_duration_warn); - SPDLOG_LOGGER_DEBUG(log_v2::lua(), + SPDLOG_LOGGER_DEBUG(_cache->logger(), "lua: pb processing dimension ba event of id {}", dbae->obj().ba_id()); _dimension_ba_events[dbae->obj().ba_id()] = dbae; @@ -1281,7 +1282,7 @@ void macro_cache::_process_dimension_ba_bv_relation_event( const auto& pb_data = std::static_pointer_cast(data); const DimensionBaBvRelationEvent& rel = pb_data->obj(); - SPDLOG_LOGGER_DEBUG(log_v2::lua(), + SPDLOG_LOGGER_DEBUG(_cache->logger(), "lua: processing pb dimension ba bv relation event " "(ba_id: {}, bv_id: {})", rel.ba_id(), rel.bv_id()); @@ -1289,10 +1290,10 @@ void macro_cache::_process_dimension_ba_bv_relation_event( } else { auto const& rel = std::static_pointer_cast(data); - SPDLOG_LOGGER_DEBUG(log_v2::lua(), - "lua: processing dimension ba bv relation event " - "(ba_id: {}, bv_id: {})", - rel->ba_id, rel->bv_id); + SPDLOG_LOGGER_DEBUG( + _cache->logger(), + "lua: processing dimension ba bv relation event (ba_id: {}, bv_id: {})", + rel->ba_id, rel->bv_id); auto pb_data(std::make_shared()); pb_data->mut_obj().set_ba_id(rel->ba_id); pb_data->mut_obj().set_bv_id(rel->bv_id); @@ -1331,7 +1332,7 @@ void macro_cache::_process_dimension_truncate_table_signal( std::shared_ptr const& data) { auto const& trunc = std::static_pointer_cast(data); - SPDLOG_LOGGER_DEBUG(log_v2::lua(), + SPDLOG_LOGGER_DEBUG(_cache->logger(), "lua: processing dimension truncate table signal"); if (trunc->update_started) { @@ -1348,7 +1349,7 @@ void macro_cache::_process_dimension_truncate_table_signal( */ void macro_cache::_process_pb_dimension_truncate_table_signal( std::shared_ptr const& data) { - SPDLOG_LOGGER_DEBUG(log_v2::lua(), + SPDLOG_LOGGER_DEBUG(_cache->logger(), "lua: processing dimension truncate table signal"); if (std::static_pointer_cast(data) @@ -1371,11 +1372,11 @@ void macro_cache::_process_custom_variable( std::shared_ptr const& data) { auto const& cv = std::static_pointer_cast(data); if (cv->name == "CRITICALITY_LEVEL") { - SPDLOG_LOGGER_DEBUG(log_v2::lua(), - "lua: processing custom variable representing a " - "criticality level for " - "host_id {} and service_id {} and level {}", - cv->host_id, cv->service_id, cv->value); + SPDLOG_LOGGER_DEBUG( + _cache->logger(), + "lua: processing custom variable representing a criticality level for " + "host_id {} and service_id {} and level {}", + cv->host_id, cv->service_id, cv->value); int32_t value = std::atoi(cv->value.c_str()); if (value) _custom_vars[{cv->host_id, cv->service_id}] = cv; @@ -1396,7 +1397,7 @@ void macro_cache::_process_pb_custom_variable( if (cv->obj().name() == "CRITICALITY_LEVEL") { int32_t value; if (absl::SimpleAtoi(cv->obj().value(), &value)) { - SPDLOG_LOGGER_DEBUG(log_v2::lua(), + SPDLOG_LOGGER_DEBUG(_cache->logger(), "lua: processing custom variable representing a " "criticality level for " "host_id {} and service_id {} and level {}", @@ -1404,7 +1405,7 @@ void macro_cache::_process_pb_custom_variable( if (value) _custom_vars[{cv->obj().host_id(), cv->obj().service_id()}] = cv; } else { - SPDLOG_LOGGER_ERROR(log_v2::lua(), + SPDLOG_LOGGER_ERROR(_cache->logger(), "lua: processing custom variable representing a " "criticality level for " "host_id {} and service_id {} incorrect value {}", diff --git a/broker/lua/src/main.cc b/broker/lua/src/main.cc index 00216e8718d..b68ef6146c7 100644 --- a/broker/lua/src/main.cc +++ b/broker/lua/src/main.cc @@ -1,20 +1,20 @@ /** -* Copyright 2017-2021 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2017-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "bbdo/bam/dimension_ba_bv_relation_event.hh" #include "bbdo/bam/dimension_ba_event.hh" @@ -24,11 +24,12 @@ #include "bbdo/storage/metric_mapping.hh" #include "bbdo/storage/status.hh" #include "com/centreon/broker/io/protocols.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/lua/factory.hh" #include "com/centreon/broker/lua/stream.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; +using log_v2 = com::centreon::common::log_v2::log_v2; // Load count. static uint32_t instances{0u}; @@ -69,11 +70,11 @@ bool broker_module_deinit() { void broker_module_init(void const* arg) { (void)arg; + auto logger = log_v2::instance().get(log_v2::LUA); // Increment instance number. if (!instances++) { // generic lua module. - log_v2::lua()->info("lua: module for Centreon Broker {}", - CENTREON_BROKER_VERSION); + logger->info("lua: module for Centreon Broker {}", CENTREON_BROKER_VERSION); io::events& e(io::events::instance()); diff --git a/broker/lua/src/stream.cc b/broker/lua/src/stream.cc index 18113f90f65..e1b2426288b 100644 --- a/broker/lua/src/stream.cc +++ b/broker/lua/src/stream.cc @@ -1,33 +1,35 @@ /** -* Copyright 2017-2021 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2017-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/lua/stream.hh" #include "com/centreon/broker/exceptions/shutdown.hh" #include "com/centreon/broker/io/events.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/lua/luabinding.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::misc; using namespace com::centreon::exceptions; using namespace com::centreon::broker::lua; +using log_v2 = com::centreon::common::log_v2::log_v2; + /** * Constructor. * @@ -38,11 +40,12 @@ stream::stream(const std::string& lua_script, const std::map& conf_params, const std::shared_ptr& cache) : io::stream("lua"), - _cache{cache}, - _luabinding(lua_script, conf_params, _cache) {} + _luabinding(lua_script, conf_params, _cache), + _logger{cache->logger()}, + _cache{cache} {} stream::~stream() noexcept { - log_v2::lua()->debug("lua: Stream destruction"); + _logger->trace("lua::stream destructor {}", static_cast(this)); } /** * Read from the connector. @@ -85,7 +88,7 @@ int32_t stream::flush() { int32_t retval = 0; if (_luabinding.has_flush()) { retval = _luabinding.flush(); - log_v2::lua()->debug("stream: flush {} events acknowledged", retval); + _logger->debug("stream: flush {} events acknowledged", retval); } return retval; } @@ -96,6 +99,6 @@ int32_t stream::flush() { * @return The number of acknowledged events. */ int32_t stream::stop() { - log_v2::lua()->debug("lua: stop stream"); + _logger->trace("lua::stream stop {}", static_cast(this)); return _luabinding.stop(); } diff --git a/broker/lua/test/lua.cc b/broker/lua/test/lua.cc index d101af1d8c8..1be48705879 100644 --- a/broker/lua/test/lua.cc +++ b/broker/lua/test/lua.cc @@ -35,27 +35,35 @@ #include "com/centreon/broker/neb/events.hh" #include "com/centreon/broker/neb/instance.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::lua; +using log_v2 = com::centreon::common::log_v2::log_v2; + #define FILE1 CENTREON_BROKER_LUA_SCRIPT_PATH "/test1.lua" #define FILE2 CENTREON_BROKER_LUA_SCRIPT_PATH "/test2.lua" #define FILE3 CENTREON_BROKER_LUA_SCRIPT_PATH "/test3.lua" #define FILE4 CENTREON_BROKER_LUA_SCRIPT_PATH "/socket.lua" class LuaTest : public ::testing::Test { + protected: + std::shared_ptr _logger; + public: void SetUp() override { + _logger = log_v2::instance().get(log_v2::LUA); + try { config::applier::init(0, "test_broker", 0); } catch (std::exception const& e) { (void)e; } std::shared_ptr pcache( - std::make_shared("/tmp/broker_test_cache")); - _cache.reset(new macro_cache(pcache)); + std::make_shared("/tmp/broker_test_cache", _logger)); + _cache = std::make_unique(pcache); } void TearDown() override { // The cache must be destroyed before the applier deinit() call. @@ -167,7 +175,7 @@ TEST_F(LuaTest, SimpleScript) { std::map conf; conf.insert({"address", "127.0.0.1"}); conf.insert({"port", 8857}); - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); char tmp[256]; getcwd(tmp, 256); std::cout << "##########################\n" << tmp << std::endl; @@ -230,7 +238,7 @@ TEST_F(LuaTest, WriteAcknowledgement) { conf.insert({"double", 3.14159265358979323846}); conf.insert({"port", 8857}); conf.insert({"name", "test-centreon"}); - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); auto bnd{std::make_unique(FILE3, conf, *_cache)}; @@ -547,7 +555,7 @@ TEST_F(LuaTest, CacheTest) { // And the cache knows about it // Then the hostname is returned from the lua method. TEST_F(LuaTest, HostCacheTest) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; std::string filename("/tmp/cache_test.lua"); @@ -591,7 +599,7 @@ TEST_F(LuaTest, HostCacheTest) { // And the cache knows about it // Then the hostname is returned from the lua method. TEST_F(LuaTest, HostCacheTestAdaptive) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; std::string filename("/tmp/cache_test.lua"); @@ -629,7 +637,7 @@ TEST_F(LuaTest, HostCacheTestAdaptive) { // And the cache knows about it // Then the hostname is returned from the lua method. TEST_F(LuaTest, HostCacheV2TestAdaptive) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; std::string filename("/tmp/cache_test.lua"); @@ -668,7 +676,7 @@ TEST_F(LuaTest, HostCacheV2TestAdaptive) { // And the cache knows about it // Then the hostname is returned from the lua method. TEST_F(LuaTest, PbHostCacheTest) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; std::string filename("/tmp/cache_test.lua"); @@ -706,7 +714,7 @@ TEST_F(LuaTest, PbHostCacheTest) { // And the cache knows about it // Then the hostname is returned from the lua method. TEST_F(LuaTest, PbHostCacheTestAdaptive) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; std::string filename("/tmp/cache_test.lua"); @@ -746,7 +754,7 @@ TEST_F(LuaTest, PbHostCacheTestAdaptive) { // And the cache knows about it // Then the hostname is returned from the lua method. TEST_F(LuaTest, PbHostCacheV2TestAdaptive) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; std::string filename("/tmp/cache_test.lua"); @@ -822,7 +830,7 @@ TEST_F(LuaTest, ServiceCacheTest) { // And the cache knows about it // Then the hostname is returned from the lua method. TEST_F(LuaTest, ServiceCacheTestAdaptive) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; std::string filename("/tmp/cache_test.lua"); @@ -860,7 +868,7 @@ TEST_F(LuaTest, ServiceCacheTestAdaptive) { // And the cache knows about it // Then the hostname is returned from the lua method. TEST_F(LuaTest, ServiceCacheTestPbAndAdaptive) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; std::string filename("/tmp/cache_test.lua"); @@ -914,7 +922,7 @@ TEST_F(LuaTest, ServiceCacheTestPbAndAdaptive) { // And the cache knows about it // Then the hostname is returned from the lua method. TEST_F(LuaTest, ServiceCacheApi2TestAdaptive) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; std::string filename("/tmp/cache_test.lua"); @@ -953,7 +961,7 @@ TEST_F(LuaTest, ServiceCacheApi2TestAdaptive) { // And the cache knows about it // Then the hostname is returned from the lua method. TEST_F(LuaTest, ServiceCacheApi2TestPbAndAdaptive) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; std::string filename("/tmp/cache_test.lua"); @@ -1192,7 +1200,7 @@ TEST_F(LuaTest, MetricMappingCacheTestV1) { } TEST_F(LuaTest, MetricMappingCacheTestV2) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/unified_sql/20-unified_sql.so"); std::map conf; std::string filename("/tmp/cache_test.lua"); @@ -1667,7 +1675,7 @@ TEST_F(LuaTest, BamCacheTestBaV1) { } TEST_F(LuaTest, BamCacheTestBaV2) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/bam/20-bam.so"); std::map conf; std::string filename("/tmp/cache_test.lua"); @@ -1766,7 +1774,7 @@ TEST_F(LuaTest, BamCacheTestBvV1) { } TEST_F(LuaTest, BamCacheTestBvV2) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/bam/20-bam.so"); std::map conf; std::string filename("/tmp/cache_test.lua"); @@ -2563,7 +2571,7 @@ TEST_F(LuaTest, CacheSeverity) { } TEST_F(LuaTest, BrokerEventIndex) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; auto svc = std::make_shared(); @@ -2605,7 +2613,7 @@ TEST_F(LuaTest, BrokerEventIndex) { } TEST_F(LuaTest, BrokerEventPairs) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; auto svc = std::make_shared(); @@ -2710,7 +2718,7 @@ TEST_F(LuaTest, PbCacheSeverity) { } TEST_F(LuaTest, PbBrokerEventIndex) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; auto svc{std::make_shared()}; @@ -2757,7 +2765,7 @@ TEST_F(LuaTest, PbBrokerEventIndex) { } TEST_F(LuaTest, PbBrokerEventPairs) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; auto svc{std::make_shared()}; @@ -2794,7 +2802,7 @@ TEST_F(LuaTest, PbBrokerEventPairs) { } TEST_F(LuaTest, BrokerEventJsonEncode) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; auto svc{std::make_shared()}; @@ -2860,7 +2868,7 @@ TEST_F(LuaTest, BrokerEventJsonEncode) { } TEST_F(LuaTest, TestHostApiV1) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; auto hst{std::make_shared()}; @@ -2887,7 +2895,7 @@ TEST_F(LuaTest, TestHostApiV1) { } TEST_F(LuaTest, TestHostApiV2) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; auto hst{std::make_shared()}; @@ -2914,7 +2922,7 @@ TEST_F(LuaTest, TestHostApiV2) { } TEST_F(LuaTest, PbTestHostApiV1) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; auto hst{std::make_shared()}; @@ -2942,7 +2950,7 @@ TEST_F(LuaTest, PbTestHostApiV1) { } TEST_F(LuaTest, PbTestHostApiV2) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; auto hst{std::make_shared()}; @@ -2970,7 +2978,7 @@ TEST_F(LuaTest, PbTestHostApiV2) { } TEST_F(LuaTest, PbTestCommentApiV1) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; auto hst{std::make_shared()}; @@ -3041,7 +3049,7 @@ TEST_F(LuaTest, PbTestCommentApiV1) { } TEST_F(LuaTest, PbTestCommentApiV2) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; auto hst{std::make_shared()}; @@ -3111,7 +3119,7 @@ TEST_F(LuaTest, PbTestCommentApiV2) { } TEST_F(LuaTest, TestSvcApiV2) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; auto svc{std::make_shared()}; @@ -3142,7 +3150,7 @@ TEST_F(LuaTest, TestSvcApiV2) { } TEST_F(LuaTest, TestSvcApiV1) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; auto svc{std::make_shared()}; @@ -3173,7 +3181,7 @@ TEST_F(LuaTest, TestSvcApiV1) { } TEST_F(LuaTest, BrokerEventCache) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; auto svc{std::make_shared()}; @@ -3201,7 +3209,7 @@ TEST_F(LuaTest, BrokerEventCache) { } TEST_F(LuaTest, PbTestSvcApiV2) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; auto svc{std::make_shared()}; @@ -3235,7 +3243,7 @@ TEST_F(LuaTest, PbTestSvcApiV2) { } TEST_F(LuaTest, PbTestSvcApiV1) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; auto svc{std::make_shared()}; @@ -3269,7 +3277,7 @@ TEST_F(LuaTest, PbTestSvcApiV1) { } TEST_F(LuaTest, PbTestCustomVariableApiV1) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; auto hst{std::make_shared()}; @@ -3332,7 +3340,7 @@ TEST_F(LuaTest, PbTestCustomVariableApiV1) { } TEST_F(LuaTest, PbTestCustomVariableApiV2) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; auto hst{std::make_shared()}; @@ -3389,7 +3397,7 @@ TEST_F(LuaTest, PbTestCustomVariableApiV2) { } TEST_F(LuaTest, PbTestCustomVariableNoIntValueNoRecordedInCache) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; auto hst{std::make_shared()}; @@ -3421,7 +3429,7 @@ TEST_F(LuaTest, PbTestCustomVariableNoIntValueNoRecordedInCache) { } TEST_F(LuaTest, PbTestCustomVariableIntValueRecordedInCache) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; auto hst{std::make_shared()}; @@ -3453,7 +3461,7 @@ TEST_F(LuaTest, PbTestCustomVariableIntValueRecordedInCache) { } TEST_F(LuaTest, PbBrokerEventCache) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; auto svc{std::make_shared()}; @@ -3529,7 +3537,7 @@ TEST_F(LuaTest, emptyMd5) { } TEST_F(LuaTest, BrokerPbServiceStatus) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; auto svc = std::make_shared(); @@ -3578,7 +3586,7 @@ TEST_F(LuaTest, BrokerPbServiceStatus) { } TEST_F(LuaTest, BrokerApi2PbServiceStatusWithIndex) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; auto svc = std::make_shared(); @@ -3628,7 +3636,7 @@ TEST_F(LuaTest, BrokerApi2PbServiceStatusWithIndex) { } TEST_F(LuaTest, BrokerApi2PbServiceStatusWithNext) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; auto svc = std::make_shared(); @@ -3684,7 +3692,7 @@ TEST_F(LuaTest, BrokerApi2PbServiceStatusWithNext) { } TEST_F(LuaTest, BrokerApi2PbServiceStatusJsonEncode) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; auto svc = std::make_shared(); @@ -3740,7 +3748,7 @@ TEST_F(LuaTest, BrokerApi2PbServiceStatusJsonEncode) { } TEST_F(LuaTest, BrokerPbServiceStatusJsonEncode) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; auto svc = std::make_shared(); @@ -3795,7 +3803,7 @@ TEST_F(LuaTest, BrokerPbServiceStatusJsonEncode) { } TEST_F(LuaTest, BrokerApi2PbServiceJsonEncode) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; auto svc = std::make_shared(); @@ -3837,7 +3845,7 @@ TEST_F(LuaTest, BrokerApi2PbServiceJsonEncode) { } TEST_F(LuaTest, BrokerPbServiceJsonEncode) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; auto svc = std::make_shared(); @@ -3878,7 +3886,7 @@ TEST_F(LuaTest, BrokerPbServiceJsonEncode) { } TEST_F(LuaTest, BrokerPbHostStatus) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; auto host = std::make_shared(); @@ -3921,7 +3929,7 @@ TEST_F(LuaTest, BrokerPbHostStatus) { } TEST_F(LuaTest, BrokerApi2PbHostStatusWithIndex) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; auto host = std::make_shared(); @@ -3965,7 +3973,7 @@ TEST_F(LuaTest, BrokerApi2PbHostStatusWithIndex) { } TEST_F(LuaTest, BrokerApi2PbHostStatusWithNext) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; auto host = std::make_shared(); @@ -4004,7 +4012,7 @@ TEST_F(LuaTest, BrokerApi2PbHostStatusWithNext) { } TEST_F(LuaTest, BrokerApi2PbHostJsonEncode) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; auto host = std::make_shared(); @@ -4039,7 +4047,7 @@ TEST_F(LuaTest, BrokerApi2PbHostJsonEncode) { } TEST_F(LuaTest, BrokerPbHostJsonEncode) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; auto host = std::make_shared(); @@ -4095,7 +4103,7 @@ TEST_F(LuaTest, BrokerBbdoVersion) { } TEST_F(LuaTest, BrokerApi2PbHostStatusJsonEncode) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; auto host = std::make_shared(); @@ -4130,7 +4138,7 @@ TEST_F(LuaTest, BrokerApi2PbHostStatusJsonEncode) { } TEST_F(LuaTest, BrokerPbHostStatusJsonEncode) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; auto host = std::make_shared(); @@ -4164,7 +4172,7 @@ TEST_F(LuaTest, BrokerPbHostStatusJsonEncode) { } TEST_F(LuaTest, BrokerPbAdaptiveHostJsonEncode) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; auto host = std::make_shared(); @@ -4197,7 +4205,7 @@ TEST_F(LuaTest, BrokerPbAdaptiveHostJsonEncode) { } TEST_F(LuaTest, BrokerApi2PbAdaptiveHostJsonEncode) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; auto host = std::make_shared(); @@ -4233,7 +4241,7 @@ TEST_F(LuaTest, BrokerApi2PbAdaptiveHostJsonEncode) { } TEST_F(LuaTest, ServiceObjectMatchBetweenBbdoVersions) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); char tmp[256]; getcwd(tmp, 256); modules.load_file("./broker/neb/10-neb.so"); @@ -4318,7 +4326,7 @@ TEST_F(LuaTest, ServiceObjectMatchBetweenBbdoVersions) { } TEST_F(LuaTest, HostObjectMatchBetweenBbdoVersions) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); char tmp[256]; getcwd(tmp, 256); modules.load_file("./broker/neb/10-neb.so"); @@ -4398,7 +4406,7 @@ TEST_F(LuaTest, HostObjectMatchBetweenBbdoVersions) { } TEST_F(LuaTest, ServiceStatusObjectMatchBetweenBbdoVersions) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); char tmp[256]; getcwd(tmp, 256); modules.load_file("./broker/neb/10-neb.so"); @@ -4477,7 +4485,7 @@ TEST_F(LuaTest, ServiceStatusObjectMatchBetweenBbdoVersions) { } TEST_F(LuaTest, HostStatusObjectMatchBetweenBbdoVersions) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); char tmp[256]; getcwd(tmp, 256); modules.load_file("./broker/neb/10-neb.so"); @@ -4556,7 +4564,7 @@ TEST_F(LuaTest, HostStatusObjectMatchBetweenBbdoVersions) { // When a pb_downtime event arrives // Then the stream is able to understand it. TEST_F(LuaTest, PbDowntime) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; std::string filename("/tmp/cache_test.lua"); @@ -4591,7 +4599,7 @@ TEST_F(LuaTest, PbDowntime) { // When a pb_downtime event arrives // Then the stream is able to understand it. TEST_F(LuaTest, PbDowntimeV2) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; std::string filename("/tmp/cache_test.lua"); @@ -4628,7 +4636,7 @@ using pb_remove_graph_message = make_type(io::storage, storage::de_remove_graph_message)>; TEST_F(LuaTest, PbRemoveGraphMessage) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/unified_sql/20-unified_sql.so"); std::map conf; @@ -4661,7 +4669,7 @@ TEST_F(LuaTest, PbRemoveGraphMessage) { } TEST_F(LuaTest, PbRemoveGraphMessageV2) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/unified_sql/20-unified_sql.so"); std::map conf; @@ -4694,7 +4702,7 @@ TEST_F(LuaTest, PbRemoveGraphMessageV2) { } TEST_F(LuaTest, BrokerApi2PbRemoveGraphMessageWithNext) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/unified_sql/20-unified_sql.so"); std::map conf; std::string filename("/tmp/test_remove_graph_with_next.lua"); @@ -4763,7 +4771,7 @@ TEST_F(LuaTest, JsonDecodeNull) { } TEST_F(LuaTest, BadLua) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::LUA)); modules.load_file("./broker/neb/10-neb.so"); std::map conf; std::string filename("/tmp/bad.lua"); diff --git a/broker/neb/CMakeLists.txt b/broker/neb/CMakeLists.txt index 5c9476c114d..a2f1a10017a 100644 --- a/broker/neb/CMakeLists.txt +++ b/broker/neb/CMakeLists.txt @@ -91,20 +91,23 @@ set(NEB_SOURCES # Static library. add_library(nebbase STATIC ${NEB_SOURCES}) -add_dependencies(nebbase - table_max_size - target_neb - target_severity - target_tag - pb_neb_lib - pb_header_lib -) +add_dependencies( + nebbase + table_max_size + target_neb + target_severity + target_tag + pb_neb_lib + pb_header_lib) -target_link_libraries(nebbase - -L${PROTOBUF_LIB_DIR} - pb_severity_lib pb_tag_lib - protobuf - pb_neb_lib pb_header_lib) +target_link_libraries( + nebbase + -L${PROTOBUF_LIB_DIR} + pb_severity_lib + pb_tag_lib + protobuf + pb_neb_lib + pb_header_lib) set(NEBBASE_CXXFLAGS "${NEBBASE_CXXFLAGS} -fPIC") set_property(TARGET nebbase PROPERTY COMPILE_FLAGS ${NEBBASE_CXXFLAGS}) @@ -122,11 +125,8 @@ add_library( ) # Flags needed to include all symbols in binary. -target_link_libraries(${NEB} - "-Wl,--whole-archive" - nebbase - "-Wl,--no-whole-archive" - spdlog::spdlog) +target_link_libraries(${NEB} "-Wl,--whole-archive" nebbase + "-Wl,--no-whole-archive" spdlog::spdlog) set_target_properties("${NEB}" PROPERTIES PREFIX "") install(TARGETS "${NEB}" LIBRARY DESTINATION "${PREFIX_MODULES}") @@ -161,7 +161,6 @@ if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID STREQUAL "Clang") target_link_libraries( "${CBMOD}" -L${PROTOBUF_LIB_DIR} - rokerlog "-Wl,--whole-archive" rokerbase multiplexing @@ -169,10 +168,8 @@ if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID STREQUAL "Clang") nlohmann_json::nlohmann_json spdlog::spdlog) else() - target_link_libraries("${CBMOD}" - -L${PROTOBUF_LIB_DIR} - "rokerbase" nlohmann_json::nlohmann_json - spdlog::spdlog) + target_link_libraries("${CBMOD}" -L${PROTOBUF_LIB_DIR} "rokerbase" + nlohmann_json::nlohmann_json spdlog::spdlog) endif() set_target_properties("${CBMOD}" PROPERTIES PREFIX "") diff --git a/broker/neb/inc/com/centreon/broker/neb/callbacks.hh b/broker/neb/inc/com/centreon/broker/neb/callbacks.hh index d9b325a7a45..0e24b1d3d10 100644 --- a/broker/neb/inc/com/centreon/broker/neb/callbacks.hh +++ b/broker/neb/inc/com/centreon/broker/neb/callbacks.hh @@ -19,7 +19,11 @@ #ifndef CCB_NEB_CALLBACKS_HH #define CCB_NEB_CALLBACKS_HH -namespace com::centreon::broker::neb { +namespace com::centreon::broker { + +extern std::shared_ptr neb_logger; + +namespace neb { extern unsigned gl_mod_flags; extern void* gl_mod_handle; @@ -68,6 +72,7 @@ int callback_pb_bench(int callback_type, void* data); void unregister_callbacks(); -} // namespace com::centreon::broker::neb +} // namespace neb +} // namespace com::centreon::broker #endif // !CCB_NEB_CALLBACKS_HH diff --git a/broker/neb/inc/com/centreon/broker/neb/internal.hh b/broker/neb/inc/com/centreon/broker/neb/internal.hh index 79e05061537..6bc17e4b31d 100644 --- a/broker/neb/inc/com/centreon/broker/neb/internal.hh +++ b/broker/neb/inc/com/centreon/broker/neb/internal.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2009-2015, 2021-2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2009-2015, 2021-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_NEB_INTERNAL_HH #define CCB_NEB_INTERNAL_HH diff --git a/broker/neb/precomp_inc/precomp.hpp b/broker/neb/precomp_inc/precomp.hpp index 4885e5ba3e0..f1090687dce 100644 --- a/broker/neb/precomp_inc/precomp.hpp +++ b/broker/neb/precomp_inc/precomp.hpp @@ -1,20 +1,20 @@ -/* -** Copyright 2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_NEB_PRECOMP_HH #define CCB_NEB_PRECOMP_HH diff --git a/broker/neb/src/broker.cc b/broker/neb/src/broker.cc index 0e1e1d218ba..0196a5e3cd0 100644 --- a/broker/neb/src/broker.cc +++ b/broker/neb/src/broker.cc @@ -29,14 +29,16 @@ namespace asio = boost::asio; #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/io/protocols.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/neb/events.hh" #include "com/centreon/broker/neb/internal.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::exceptions; +using log_v2 = com::centreon::common::log_v2::log_v2; + static uint32_t neb_instances(0); extern "C" { @@ -66,9 +68,9 @@ bool broker_module_deinit() { */ void broker_module_init(void const* arg) { (void)arg; + auto logger = log_v2::instance().get(log_v2::NEB); if (!neb_instances++) { - log_v2::core()->info("NEB: module for Centreon Broker {}", - CENTREON_BROKER_VERSION); + logger->info("NEB: module for Centreon Broker {}", CENTREON_BROKER_VERSION); io::events& e(io::events::instance()); // Register events. diff --git a/broker/neb/src/callbacks.cc b/broker/neb/src/callbacks.cc index 60e1fd431a7..ec4405be004 100644 --- a/broker/neb/src/callbacks.cc +++ b/broker/neb/src/callbacks.cc @@ -26,7 +26,6 @@ #include "com/centreon/broker/config/applier/state.hh" #include "com/centreon/broker/config/parser.hh" #include "com/centreon/broker/config/state.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/string.hh" #include "com/centreon/broker/neb/callback.hh" #include "com/centreon/broker/neb/events.hh" @@ -48,9 +47,11 @@ #include "com/centreon/engine/severity.hh" #include "com/centreon/engine/tag.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::exceptions; +using com::centreon::common::log_v2::log_v2; // List of Nagios modules. extern nebmodule* neb_module_list; @@ -161,8 +162,7 @@ char const* get_program_version(); */ int neb::callback_acknowledgement(int callback_type, void* data) { // Log message. - SPDLOG_LOGGER_INFO(log_v2::neb(), - "callbacks: generating acknowledgement event"); + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: generating acknowledgement event"); (void)callback_type; try { @@ -203,7 +203,7 @@ int neb::callback_acknowledgement(int callback_type, void* data) { gl_publisher.write(ack); } catch (std::exception const& e) { SPDLOG_LOGGER_ERROR( - log_v2::neb(), + neb_logger, "callbacks: error occurred while generating acknowledgement event: {}", e.what()); } @@ -229,7 +229,7 @@ int neb::callback_acknowledgement(int callback_type, void* data) { int neb::callback_pb_acknowledgement(int callback_type [[maybe_unused]], void* data) { // Log message. - SPDLOG_LOGGER_INFO(log_v2::neb(), + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: generating pb acknowledgement event"); // In/Out variables. @@ -248,7 +248,7 @@ int neb::callback_pb_acknowledgement(int callback_type [[maybe_unused]], misc::string::check_string_utf8(ack_data->comment_data)); ack_obj.set_entry_time(time(nullptr)); if (!ack_data->host_id) { - SPDLOG_LOGGER_ERROR(log_v2::neb(), + SPDLOG_LOGGER_ERROR(neb_logger, "callbacks: error occurred while generating " "acknowledgement event: host_id is null"); return 0; @@ -286,7 +286,7 @@ int neb::callback_pb_acknowledgement(int callback_type [[maybe_unused]], */ int neb::callback_comment(int callback_type, void* data) { // Log message. - SPDLOG_LOGGER_INFO(log_v2::neb(), "callbacks: generating comment event"); + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: generating comment event"); (void)callback_type; try { @@ -307,6 +307,12 @@ int neb::callback_comment(int callback_type, void* data) { comment->deletion_time = time(nullptr); comment->entry_time = comment_data->entry_time; comment->entry_type = comment_data->entry_type; + if (comment->entry_type == 4) + neb_logger->debug( + "callbacks: comment about acknowledgement entry_time:{} - " + "deletion_time:{} - host_id:{} - service_id:{}", + comment->entry_time, comment->deletion_time, comment->host_id, + comment->service_id); comment->expire_time = comment_data->expire_time; comment->expires = comment_data->expires; if (comment_data->service_id) { @@ -329,7 +335,7 @@ int neb::callback_comment(int callback_type, void* data) { gl_publisher.write(comment); } catch (std::exception const& e) { SPDLOG_LOGGER_ERROR( - log_v2::neb(), + neb_logger, "callbacks: error occurred while generating comment event: {}", e.what()); } @@ -352,7 +358,7 @@ int neb::callback_comment(int callback_type, void* data) { */ int neb::callback_pb_comment(int, void* data) { // Log message. - SPDLOG_LOGGER_INFO(log_v2::neb(), "callbacks: generating pb comment event"); + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: generating pb comment event"); const nebstruct_comment_data* comment_data = static_cast(data); @@ -372,22 +378,29 @@ int neb::callback_pb_comment(int, void* data) { (comment_data->comment_type == com::centreon::engine::comment::type::host) ? com::centreon::broker::Comment_Type_HOST : com::centreon::broker::Comment_Type_SERVICE); - if (NEBTYPE_COMMENT_DELETE == comment_data->type) + if (NEBTYPE_COMMENT_DELETE == comment_data->type) { comment.set_deletion_time(time(nullptr)); + neb_logger->debug("callbacks: comment with deletion time {}", + comment.deletion_time()); + } comment.set_entry_time(comment_data->entry_time); switch (comment_data->entry_type) { case com::centreon::engine::comment::e_type::user: comment.set_entry_type(com::centreon::broker::Comment_EntryType_USER); + neb_logger->debug("callbacks: comment from a user"); break; case com::centreon::engine::comment::e_type::downtime: comment.set_entry_type(com::centreon::broker::Comment_EntryType_DOWNTIME); + neb_logger->debug("callbacks: comment about downtime"); break; case com::centreon::engine::comment::e_type::flapping: comment.set_entry_type(com::centreon::broker::Comment_EntryType_FLAPPING); + neb_logger->debug("callbacks: comment about flapping"); break; case com::centreon::engine::comment::e_type::acknowledgment: comment.set_entry_type( com::centreon::broker::Comment_EntryType_ACKNOWLEDGMENT); + neb_logger->debug("callbacks: comment about acknowledgement"); break; default: break; @@ -397,7 +410,7 @@ int neb::callback_pb_comment(int, void* data) { if (comment_data->service_id) { if (!comment_data->host_id) { SPDLOG_LOGGER_ERROR( - log_v2::neb(), + neb_logger, "comment created from a service with host_id/service_id 0"); return 0; } @@ -405,7 +418,7 @@ int neb::callback_pb_comment(int, void* data) { comment.set_service_id(comment_data->service_id); } else { if (comment_data->host_id == 0) { - SPDLOG_LOGGER_ERROR(log_v2::neb(), + SPDLOG_LOGGER_ERROR(neb_logger, "comment created from a host with host_id 0"); return 0; } @@ -442,13 +455,12 @@ int neb::callback_pb_custom_variable(int, void* data) { const nebstruct_custom_variable_data* cvar( static_cast(data)); - if (log_v2::neb()->level() <= spdlog::level::debug) { + if (neb_logger->level() <= spdlog::level::debug) { SPDLOG_LOGGER_DEBUG( - log_v2::neb(), - "callbacks: generating custom variable event {} value:{}", + neb_logger, "callbacks: generating custom variable event {} value:{}", cvar->var_name, cvar->var_value); } else { - SPDLOG_LOGGER_INFO(log_v2::neb(), + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: generating custom variable event"); } @@ -476,12 +488,12 @@ int neb::callback_pb_custom_variable(int, void* data) { std::string value(misc::string::check_string_utf8(cvar->var_value)); obj.set_value(value); obj.set_default_value(value); - SPDLOG_LOGGER_INFO(log_v2::neb(), + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: new custom variable '{}' on host {}", name, host_id); } else { SPDLOG_LOGGER_INFO( - log_v2::neb(), + neb_logger, "callbacks: deleted custom variable '{}' on host {}", name, host_id); } @@ -513,13 +525,13 @@ int neb::callback_pb_custom_variable(int, void* data) { obj.set_value(value); obj.set_default_value(value); SPDLOG_LOGGER_INFO( - log_v2::neb(), + neb_logger, "callbacks: new custom variable '{}' on service ({}, {})", name, p.first, p.second); } else { SPDLOG_LOGGER_INFO( - log_v2::neb(), + neb_logger, "callbacks: deleted custom variable '{}' on service ({},{})", name, p.first, p.second); } @@ -552,8 +564,7 @@ int neb::callback_pb_custom_variable(int, void* data) { int neb::callback_custom_variable(int callback_type, void* data) { // Log message. - SPDLOG_LOGGER_INFO(log_v2::neb(), - "callbacks: generating custom variable event"); + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: generating custom variable event"); (void)callback_type; try { @@ -580,7 +591,7 @@ int neb::callback_custom_variable(int callback_type, void* data) { misc::string::check_string_utf8(cvar->var_value); // Send custom variable event. - SPDLOG_LOGGER_INFO(log_v2::neb(), + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: new custom variable '{}' on host {}", new_cvar->name, new_cvar->host_id); neb::gl_publisher.write(new_cvar); @@ -600,7 +611,7 @@ int neb::callback_custom_variable(int callback_type, void* data) { // Send custom variable event. SPDLOG_LOGGER_INFO( - log_v2::neb(), + neb_logger, "callbacks: deleted custom variable '{}' on host {}", old_cvar->name, old_cvar->host_id); neb::gl_publisher.write(old_cvar); @@ -631,7 +642,7 @@ int neb::callback_custom_variable(int callback_type, void* data) { // Send custom variable event. SPDLOG_LOGGER_INFO( - log_v2::neb(), + neb_logger, "callbacks: new custom variable '{}' on service ({}, {})", new_cvar->name, new_cvar->host_id, new_cvar->service_id); neb::gl_publisher.write(new_cvar); @@ -655,7 +666,7 @@ int neb::callback_custom_variable(int callback_type, void* data) { // Send custom variable event. SPDLOG_LOGGER_INFO( - log_v2::neb(), + neb_logger, "callbacks: deleted custom variable '{}' on service ({},{})", old_cvar->name, old_cvar->host_id, old_cvar->service_id); neb::gl_publisher.write(old_cvar); @@ -686,7 +697,7 @@ int neb::callback_custom_variable(int callback_type, void* data) { */ int neb::callback_dependency(int callback_type, void* data) { // Log message. - SPDLOG_LOGGER_INFO(log_v2::neb(), "callbacks: generating dependency event"); + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: generating dependency event"); (void)callback_type; try { @@ -707,7 +718,7 @@ int neb::callback_dependency(int callback_type, void* data) { host_id = engine::get_host_id(dep->get_hostname()); } else { SPDLOG_LOGGER_ERROR( - log_v2::neb(), + neb_logger, "callbacks: dependency callback called without valid host"); host_id = 0; } @@ -715,7 +726,7 @@ int neb::callback_dependency(int callback_type, void* data) { dep_host_id = engine::get_host_id(dep->get_dependent_hostname()); } else { SPDLOG_LOGGER_INFO( - log_v2::neb(), + neb_logger, "callbacks: dependency callback called without valid dependent " "host"); dep_host_id = 0; @@ -744,7 +755,7 @@ int neb::callback_dependency(int callback_type, void* data) { hst_dep->execution_failure_options = options; } hst_dep->inherits_parent = dep->get_inherits_parent(); - SPDLOG_LOGGER_INFO(log_v2::neb(), "callbacks: host {} depends on host {}", + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: host {} depends on host {}", dep_host_id, host_id); // Publish dependency event. @@ -765,7 +776,7 @@ int neb::callback_dependency(int callback_type, void* data) { dep->get_service_description()); } else { SPDLOG_LOGGER_ERROR( - log_v2::neb(), + neb_logger, "callbacks: dependency callback called without valid service"); ids.first = 0; ids.second = 0; @@ -777,7 +788,7 @@ int neb::callback_dependency(int callback_type, void* data) { dep->get_dependent_service_description()); } else { SPDLOG_LOGGER_ERROR( - log_v2::neb(), + neb_logger, "callbacks: dependency callback called without valid dependent " "service"); dep_ids.first = 0; @@ -812,8 +823,7 @@ int neb::callback_dependency(int callback_type, void* data) { } svc_dep->inherits_parent = dep->get_inherits_parent(); SPDLOG_LOGGER_INFO( - log_v2::neb(), - "callbacks: service ({}, {}) depends on service ({}, {})", + neb_logger, "callbacks: service ({}, {}) depends on service ({}, {})", dep_ids.first, dep_ids.second, ids.first, ids.second); // Publish dependency event. @@ -843,7 +853,7 @@ int neb::callback_dependency(int callback_type, void* data) { */ int neb::callback_pb_dependency(int, void* data) { // Log message. - SPDLOG_LOGGER_INFO(log_v2::neb(), "callbacks: generating dependency event"); + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: generating dependency event"); // Input variables. nebstruct_adaptive_dependency_data* nsadd( @@ -863,7 +873,7 @@ int neb::callback_pb_dependency(int, void* data) { host_id = engine::get_host_id(dep->get_hostname()); } else { SPDLOG_LOGGER_ERROR( - log_v2::neb(), + neb_logger, "callbacks: dependency callback called without valid host"); host_id = 0; } @@ -871,7 +881,7 @@ int neb::callback_pb_dependency(int, void* data) { dep_host_id = engine::get_host_id(dep->get_dependent_hostname()); } else { SPDLOG_LOGGER_INFO( - log_v2::neb(), + neb_logger, "callbacks: dependency callback called without valid dependent " "host"); dep_host_id = 0; @@ -901,7 +911,7 @@ int neb::callback_pb_dependency(int, void* data) { hst_dep.set_execution_failure_options(options); } hst_dep.set_inherits_parent(dep->get_inherits_parent()); - SPDLOG_LOGGER_INFO(log_v2::neb(), "callbacks: host {} depends on host {}", + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: host {} depends on host {}", dep_host_id, host_id); // Publish dependency event. @@ -922,7 +932,7 @@ int neb::callback_pb_dependency(int, void* data) { dep->get_service_description()); } else { SPDLOG_LOGGER_ERROR( - log_v2::neb(), + neb_logger, "callbacks: dependency callback called without valid service"); ids.first = 0; ids.second = 0; @@ -934,7 +944,7 @@ int neb::callback_pb_dependency(int, void* data) { dep->get_dependent_service_description()); } else { SPDLOG_LOGGER_ERROR( - log_v2::neb(), + neb_logger, "callbacks: dependency callback called without valid dependent " "service"); dep_ids.first = 0; @@ -970,8 +980,7 @@ int neb::callback_pb_dependency(int, void* data) { } svc_dep.set_inherits_parent(dep->get_inherits_parent()); SPDLOG_LOGGER_INFO( - log_v2::neb(), - "callbacks: service ({}, {}) depends on service ({}, {})", + neb_logger, "callbacks: service ({}, {}) depends on service ({}, {})", dep_ids.first, dep_ids.second, ids.first, ids.second); // Publish dependency event. @@ -994,7 +1003,7 @@ int neb::callback_pb_dependency(int, void* data) { */ int neb::callback_downtime(int callback_type, void* data) { // Log message. - SPDLOG_LOGGER_INFO(log_v2::neb(), "callbacks: generating downtime event"); + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: generating downtime event"); (void)callback_type; const nebstruct_downtime_data* downtime_data{ static_cast(data)}; @@ -1062,7 +1071,7 @@ int neb::callback_downtime(int callback_type, void* data) { gl_publisher.write(downtime); } catch (std::exception const& e) { SPDLOG_LOGGER_ERROR( - log_v2::neb(), + neb_logger, "callbacks: error occurred while generating downtime event: {}", e.what()); } @@ -1085,7 +1094,7 @@ int neb::callback_downtime(int callback_type, void* data) { */ int neb::callback_pb_downtime(int callback_type, void* data) { // Log message. - log_v2::neb()->info("callbacks: generating pb downtime event"); + neb_logger->info("callbacks: generating pb downtime event"); (void)callback_type; const nebstruct_downtime_data* downtime_data = @@ -1140,7 +1149,7 @@ int neb::callback_pb_downtime(int callback_type, void* data) { params.deletion_time = downtime_data->timestamp.tv_sec; break; default: - log_v2::neb()->error( + neb_logger->error( "callbacks: error occurred while generating downtime event: " "Downtime {} with not managed type.", downtime_data->downtime_id); @@ -1174,7 +1183,7 @@ int neb::callback_pb_downtime(int callback_type, void* data) { */ int neb::callback_external_command(int callback_type, void* data) { // Log message. - SPDLOG_LOGGER_DEBUG(log_v2::neb(), "callbacks: external command data"); + SPDLOG_LOGGER_DEBUG(neb_logger, "callbacks: external command data"); (void)callback_type; nebstruct_external_command_data* necd( @@ -1183,7 +1192,7 @@ int neb::callback_external_command(int callback_type, void* data) { try { if (necd->command_type == CMD_CHANGE_CUSTOM_HOST_VAR) { SPDLOG_LOGGER_INFO( - log_v2::neb(), + neb_logger, "callbacks: generating host custom variable update event"); // Split argument string. @@ -1192,8 +1201,7 @@ int neb::callback_external_command(int callback_type, void* data) { misc::string::check_string_utf8(necd->command_args), ';')}; if (l.size() != 3) SPDLOG_LOGGER_ERROR( - log_v2::neb(), - "callbacks: invalid host custom variable command"); + neb_logger, "callbacks: invalid host custom variable command"); else { std::list::iterator it(l.begin()); std::string host{std::move(*it)}; @@ -1221,7 +1229,7 @@ int neb::callback_external_command(int callback_type, void* data) { } } else if (necd->command_type == CMD_CHANGE_CUSTOM_SVC_VAR) { SPDLOG_LOGGER_INFO( - log_v2::neb(), + neb_logger, "callbacks: generating service custom variable update event"); // Split argument string. @@ -1230,7 +1238,7 @@ int neb::callback_external_command(int callback_type, void* data) { misc::string::check_string_utf8(necd->command_args), ';')}; if (l.size() != 4) SPDLOG_LOGGER_ERROR( - log_v2::neb(), + neb_logger, "callbacks: invalid service custom variable command"); else { std::list::iterator it{l.begin()}; @@ -1284,7 +1292,7 @@ int neb::callback_external_command(int callback_type, void* data) { */ int neb::callback_pb_external_command(int, void* data) { // Log message. - SPDLOG_LOGGER_DEBUG(log_v2::neb(), "callbacks: external command data"); + SPDLOG_LOGGER_DEBUG(neb_logger, "callbacks: external command data"); nebstruct_external_command_data* necd( static_cast(data)); @@ -1295,15 +1303,14 @@ int neb::callback_pb_external_command(int, void* data) { auto split_iter = args.begin(); if (necd->command_type == CMD_CHANGE_CUSTOM_HOST_VAR) { SPDLOG_LOGGER_INFO( - log_v2::neb(), + neb_logger, "callbacks: generating host custom variable update event"); // Split argument string. if (necd->command_args) { if (args_size != 3) SPDLOG_LOGGER_ERROR( - log_v2::neb(), - "callbacks: invalid host custom variable command {}", + neb_logger, "callbacks: invalid host custom variable command {}", necd->command_args); else { std::string host(*(split_iter++)); @@ -1324,21 +1331,21 @@ int neb::callback_pb_external_command(int, void* data) { // Send event. gl_publisher.write(cvs); } else { - SPDLOG_LOGGER_ERROR(log_v2::neb(), "callbacks: unknown host {} ", + SPDLOG_LOGGER_ERROR(neb_logger, "callbacks: unknown host {} ", host); } } } } else if (necd->command_type == CMD_CHANGE_CUSTOM_SVC_VAR) { SPDLOG_LOGGER_INFO( - log_v2::neb(), + neb_logger, "callbacks: generating service custom variable update event"); // Split argument string. if (necd->command_args) { if (args_size != 4) SPDLOG_LOGGER_ERROR( - log_v2::neb(), + neb_logger, "callbacks: invalid service custom variable command {}", necd->command_args); else { @@ -1363,7 +1370,7 @@ int neb::callback_pb_external_command(int, void* data) { // Send event. gl_publisher.write(cvs); } else { - SPDLOG_LOGGER_ERROR(log_v2::neb(), + SPDLOG_LOGGER_ERROR(neb_logger, "callbacks: unknown host {} service {}", host, service); } @@ -1388,7 +1395,7 @@ int neb::callback_pb_external_command(int, void* data) { */ int neb::callback_group(int callback_type, void* data) { // Log message. - SPDLOG_LOGGER_INFO(log_v2::neb(), "callbacks: generating group event"); + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: generating group event"); (void)callback_type; try { @@ -1415,12 +1422,12 @@ int neb::callback_group(int callback_type, void* data) { if (new_hg->id) { if (new_hg->enabled) SPDLOG_LOGGER_INFO( - log_v2::neb(), + neb_logger, "callbacks: new host group {} ('{}') on instance {}", new_hg->id, new_hg->name, new_hg->poller_id); else SPDLOG_LOGGER_INFO( - log_v2::neb(), + neb_logger, "callbacks: disable host group {} ('{}') on instance {}", new_hg->id, new_hg->name, new_hg->poller_id); neb::gl_publisher.write(new_hg); @@ -1446,12 +1453,12 @@ int neb::callback_group(int callback_type, void* data) { if (new_sg->id) { if (new_sg->enabled) SPDLOG_LOGGER_INFO( - log_v2::neb(), + neb_logger, "callbacks:: new service group {} ('{}) on instance {}", new_sg->id, new_sg->name, new_sg->poller_id); else SPDLOG_LOGGER_INFO( - log_v2::neb(), + neb_logger, "callbacks:: disable service group {} ('{}) on instance {}", new_sg->id, new_sg->name, new_sg->poller_id); neb::gl_publisher.write(new_sg); @@ -1485,8 +1492,7 @@ int neb::callback_pb_group(int callback_type, void* data) { nebstruct_group_data const* group_data( static_cast(data)); - SPDLOG_LOGGER_INFO(log_v2::neb(), - "callbacks: generating pb group event type:{}", + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: generating pb group event type:{}", group_data->type); // Host group. @@ -1509,14 +1515,14 @@ int neb::callback_pb_group(int callback_type, void* data) { // Send host group event. if (host_group->get_id()) { if (new_hg->obj().enabled()) - SPDLOG_LOGGER_INFO(log_v2::neb(), + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: new pb host group {} ('{}' {} " "members) on instance {}", host_group->get_id(), new_hg->obj().name(), host_group->members.size(), new_hg->obj().poller_id()); else - SPDLOG_LOGGER_INFO(log_v2::neb(), + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: disable pb host group {} ('{}' {} " "members) on instance {}", host_group->get_id(), new_hg->obj().name(), @@ -1548,13 +1554,13 @@ int neb::callback_pb_group(int callback_type, void* data) { if (service_group->get_id()) { if (new_sg->obj().enabled()) SPDLOG_LOGGER_INFO( - log_v2::neb(), + neb_logger, "callbacks:: new pb service group {} ('{}) on instance {}", service_group->get_id(), new_sg->obj().name(), new_sg->obj().poller_id()); else SPDLOG_LOGGER_INFO( - log_v2::neb(), + neb_logger, "callbacks:: disable pb service group {} ('{}) on instance {}", service_group->get_id(), new_sg->obj().name(), new_sg->obj().poller_id()); @@ -1581,7 +1587,7 @@ int neb::callback_pb_group(int callback_type, void* data) { */ int neb::callback_group_member(int callback_type, void* data) { // Log message. - SPDLOG_LOGGER_INFO(log_v2::neb(), "callbacks: generating group member event"); + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: generating group member event"); (void)callback_type; try { @@ -1606,7 +1612,7 @@ int neb::callback_group_member(int callback_type, void* data) { if (host_id != 0 && hgm->group_id != 0) { hgm->host_id = host_id; if (member_data->type == NEBTYPE_HOSTGROUPMEMBER_DELETE) { - SPDLOG_LOGGER_INFO(log_v2::neb(), + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: host {} is not a member of group " "{} on instance {} " "anymore", @@ -1614,7 +1620,7 @@ int neb::callback_group_member(int callback_type, void* data) { hgm->enabled = false; } else { SPDLOG_LOGGER_INFO( - log_v2::neb(), + neb_logger, "callbacks: host {} is a member of group {} on instance {}", hgm->host_id, hgm->group_id, hgm->poller_id); hgm->enabled = true; @@ -1648,14 +1654,14 @@ int neb::callback_group_member(int callback_type, void* data) { if (sgm->host_id && sgm->service_id && sgm->group_id) { if (member_data->type == NEBTYPE_SERVICEGROUPMEMBER_DELETE) { SPDLOG_LOGGER_INFO( - log_v2::neb(), + neb_logger, "callbacks: service ({},{}) is not a member of group {} on " "instance {} anymore", sgm->host_id, sgm->service_id, sgm->group_id, sgm->poller_id); sgm->enabled = false; } else { SPDLOG_LOGGER_INFO( - log_v2::neb(), + neb_logger, "callbacks: service ({}, {}) is a member of group {} on " "instance {}", sgm->host_id, sgm->service_id, sgm->group_id, sgm->poller_id); @@ -1690,8 +1696,7 @@ int neb::callback_group_member(int callback_type, void* data) { */ int neb::callback_pb_group_member(int callback_type, void* data) { // Log message. - SPDLOG_LOGGER_INFO(log_v2::neb(), - "callbacks: generating pb group member event"); + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: generating pb group member event"); (void)callback_type; // Input variable. @@ -1716,7 +1721,7 @@ int neb::callback_pb_group_member(int callback_type, void* data) { if (host_id != 0 && hgm.hostgroup_id() != 0) { hgm.set_host_id(host_id); if (member_data->type == NEBTYPE_HOSTGROUPMEMBER_DELETE) { - SPDLOG_LOGGER_INFO(log_v2::neb(), + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: host {} is not a member of group " "{} on instance {} " "anymore", @@ -1725,7 +1730,7 @@ int neb::callback_pb_group_member(int callback_type, void* data) { hgm.set_enabled(false); } else { SPDLOG_LOGGER_INFO( - log_v2::neb(), + neb_logger, "callbacks: host {} is a member of group {} on instance {}", hgm.host_id(), hgm.hostgroup_id(), hgm.poller_id()); hgm.set_enabled(true); @@ -1760,7 +1765,7 @@ int neb::callback_pb_group_member(int callback_type, void* data) { if (sgm.host_id() && sgm.service_id() && sgm.servicegroup_id()) { if (member_data->type == NEBTYPE_SERVICEGROUPMEMBER_DELETE) { SPDLOG_LOGGER_INFO( - log_v2::neb(), + neb_logger, "callbacks: service ({},{}) is not a member of group {} on " "instance {} anymore", sgm.host_id(), sgm.service_id(), sgm.servicegroup_id(), @@ -1768,7 +1773,7 @@ int neb::callback_pb_group_member(int callback_type, void* data) { sgm.set_enabled(false); } else { SPDLOG_LOGGER_INFO( - log_v2::neb(), + neb_logger, "callbacks: service ({}, {}) is a member of group {} on " "instance {}", sgm.host_id(), sgm.service_id(), sgm.servicegroup_id(), @@ -1799,7 +1804,7 @@ int neb::callback_pb_group_member(int callback_type, void* data) { */ int neb::callback_host(int callback_type, void* data) { // Log message. - SPDLOG_LOGGER_INFO(log_v2::neb(), "callbacks: generating host event"); + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: generating host event"); (void)callback_type; try { @@ -1935,14 +1940,14 @@ int neb::callback_host(int callback_type, void* data) { // Send host event. SPDLOG_LOGGER_INFO( - log_v2::neb(), "callbacks: new host {} ('{}') on instance {}", + neb_logger, "callbacks: new host {} ('{}') on instance {}", my_host->host_id, my_host->host_name, my_host->poller_id); neb::gl_publisher.write(my_host); /* No need to send this service custom variables changes, custom * variables are managed in a different loop. */ } else - SPDLOG_LOGGER_ERROR(log_v2::neb(), + SPDLOG_LOGGER_ERROR(neb_logger, "callbacks: host '{}' has no ID (yet) defined", (!h->name().empty() ? h->name() : "(unknown)")); } @@ -1966,7 +1971,7 @@ int neb::callback_host(int callback_type, void* data) { */ int neb::callback_pb_host(int callback_type, void* data) { // Log message. - SPDLOG_LOGGER_INFO(log_v2::neb(), + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: generating pb host event protobuf"); (void)callback_type; @@ -2010,7 +2015,7 @@ int neb::callback_pb_host(int callback_type, void* data) { else if (dh->modified_attribute & MODATTR_NOTIFICATION_TIMEPERIOD) hst.set_notification_period(eh->notification_period()); else { - SPDLOG_LOGGER_ERROR(log_v2::neb(), + SPDLOG_LOGGER_ERROR(neb_logger, "callbacks: adaptive host not implemented."); assert(1 == 0); } @@ -2020,13 +2025,13 @@ int neb::callback_pb_host(int callback_type, void* data) { hst.set_host_id(host_id); // Send host event. - SPDLOG_LOGGER_INFO(log_v2::neb(), + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: new host {} ('{}') on instance {}", hst.host_id(), eh->name(), config::applier::state::instance().poller_id()); neb::gl_publisher.write(h); } else - SPDLOG_LOGGER_ERROR(log_v2::neb(), + SPDLOG_LOGGER_ERROR(neb_logger, "callbacks: host '{}' has no ID (yet) defined", (!eh->name().empty() ? eh->name() : "(unknown)")); } else { @@ -2166,7 +2171,7 @@ int neb::callback_pb_host(int callback_type, void* data) { host.set_host_id(host_id); // Send host event. - SPDLOG_LOGGER_INFO(log_v2::neb(), + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: new host {} ('{}') on instance {}", host.host_id(), host.name(), host.instance_id()); neb::gl_publisher.write(h); @@ -2174,7 +2179,7 @@ int neb::callback_pb_host(int callback_type, void* data) { /* No need to send this service custom variables changes, custom * variables are managed in a different loop. */ } else - SPDLOG_LOGGER_ERROR(log_v2::neb(), + SPDLOG_LOGGER_ERROR(neb_logger, "callbacks: host '{}' has no ID (yet) defined", (!eh->name().empty() ? eh->name() : "(unknown)")); } @@ -2207,7 +2212,7 @@ int neb::callback_host_check(int callback_type, void* data) { return 0; // Log message. - SPDLOG_LOGGER_INFO(log_v2::neb(), "callbacks: generating host check event"); + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: generating host check event"); try { auto host_check{std::make_shared()}; @@ -2231,7 +2236,7 @@ int neb::callback_host_check(int callback_type, void* data) { } } catch (std::exception const& e) { SPDLOG_LOGGER_ERROR( - log_v2::neb(), + neb_logger, "callbacks: error occurred while generating host check event: {}", e.what()); } @@ -2267,13 +2272,13 @@ int neb::callback_pb_host_check(int callback_type, void* data) { return 0; // Log message. - if (log_v2::neb()->level() <= spdlog::level::debug) { + if (neb_logger->level() <= spdlog::level::debug) { SPDLOG_LOGGER_DEBUG( - log_v2::neb(), + neb_logger, "callbacks: generating host check event for {} command_line={}", hcdata->host_name, hcdata->command_line); } else { - SPDLOG_LOGGER_INFO(log_v2::neb(), "callbacks: generating host check event"); + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: generating host check event"); } std::shared_ptr host_check{ @@ -2314,7 +2319,7 @@ int neb::callback_pb_host_check(int callback_type, void* data) { */ int neb::callback_host_status(int callback_type, void* data) { // Log message. - SPDLOG_LOGGER_INFO(log_v2::neb(), "callbacks: generating host status event"); + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: generating host status event"); (void)callback_type; try { @@ -2416,9 +2421,11 @@ int neb::callback_host_status(int callback_type, void* data) { } gl_acknowledgements.erase(it); } + neb_logger->debug("Still {} running acknowledgements", + gl_acknowledgements.size()); } catch (std::exception const& e) { SPDLOG_LOGGER_ERROR( - log_v2::neb(), + neb_logger, "callbacks: error occurred while generating host status event: {}", e.what()); } @@ -2444,7 +2451,7 @@ int neb::callback_host_status(int callback_type, void* data) { int neb::callback_pb_host_status(int callback_type, void* data) noexcept { // Log message. SPDLOG_LOGGER_INFO( - log_v2::neb(), + neb_logger, "callbacks: generating pb host status check result event protobuf"); (void)callback_type; @@ -2456,7 +2463,7 @@ int neb::callback_pb_host_status(int callback_type, void* data) noexcept { hscr.set_host_id(eh->host_id()); if (hscr.host_id() == 0) - SPDLOG_LOGGER_ERROR(log_v2::neb(), "could not find ID of host '{}'", + SPDLOG_LOGGER_ERROR(neb_logger, "could not find ID of host '{}'", eh->name()); if (eh->problem_has_been_acknowledged()) @@ -2507,6 +2514,7 @@ int neb::callback_pb_host_status(int callback_type, void* data) noexcept { if (it != gl_acknowledgements.end() && hscr.acknowledgement_type() == AckType::NONE) { if (it->second->type() == make_type(io::neb, de_pb_acknowledgement)) { + neb_logger->debug("acknowledgement found on host {}", hscr.host_id()); neb::pb_acknowledgement* a = static_cast(it->second.get()); if (!(!hscr.state() // !(OK or (normal ack and NOK)) @@ -2526,6 +2534,8 @@ int neb::callback_pb_host_status(int callback_type, void* data) noexcept { } gl_acknowledgements.erase(it); } + neb_logger->debug("Still {} running acknowledgements", + gl_acknowledgements.size()); return 0; } @@ -2542,7 +2552,7 @@ int neb::callback_pb_host_status(int callback_type, void* data) noexcept { */ int neb::callback_log(int callback_type, void* data) { // Log message. - SPDLOG_LOGGER_INFO(log_v2::neb(), "callbacks: generating log event"); + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: generating log event"); (void)callback_type; try { @@ -2581,7 +2591,7 @@ int neb::callback_log(int callback_type, void* data) { */ int neb::callback_pb_log(int callback_type [[maybe_unused]], void* data) { // Log message. - SPDLOG_LOGGER_INFO(log_v2::neb(), "callbacks: generating pb log event"); + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: generating pb log event"); try { // In/Out variables. @@ -2620,7 +2630,7 @@ int neb::callback_pb_log(int callback_type [[maybe_unused]], void* data) { */ int neb::callback_process(int, void* data) { // Log message. - SPDLOG_LOGGER_DEBUG(log_v2::neb(), "callbacks: process event callback"); + SPDLOG_LOGGER_DEBUG(neb_logger, "callbacks: process event callback"); // Input variables. nebstruct_process_data const* process_data; @@ -2629,12 +2639,11 @@ int neb::callback_process(int, void* data) { // Check process event type. process_data = static_cast(data); if (NEBTYPE_PROCESS_EVENTLOOPSTART == process_data->type) { - SPDLOG_LOGGER_INFO(log_v2::neb(), - "callbacks: generating process start event"); + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: generating process start event"); // Register callbacks. SPDLOG_LOGGER_DEBUG( - log_v2::neb(), "callbacks: registering callbacks for old BBDO version"); + neb_logger, "callbacks: registering callbacks for old BBDO version"); for (uint32_t i(0); i < sizeof(gl_callbacks) / sizeof(*gl_callbacks); ++i) gl_registered_callbacks.emplace_back(std::make_unique( gl_callbacks[i].macro, gl_mod_handle, gl_callbacks[i].callback)); @@ -2643,8 +2652,7 @@ int neb::callback_process(int, void* data) { if (gl_mod_flags & NEBMODULE_ENGINE) { // Register engine callbacks. SPDLOG_LOGGER_DEBUG( - log_v2::neb(), - "callbacks: registering callbacks for old BBDO version"); + neb_logger, "callbacks: registering callbacks for old BBDO version"); for (uint32_t i = 0; i < sizeof(gl_engine_callbacks) / sizeof(*gl_engine_callbacks); ++i) gl_registered_callbacks.emplace_back(std::make_unique( @@ -2662,13 +2670,14 @@ int neb::callback_process(int, void* data) { instance->program_start = time(nullptr); instance->version = get_program_version(); start_time = instance->program_start; + SPDLOG_LOGGER_DEBUG(neb_logger, "callbacks: instance '{}' running {}", + instance->name, instance->is_running); // Send initial event and then configuration. gl_publisher.write(instance); send_initial_configuration(); } else if (NEBTYPE_PROCESS_EVENTLOOPEND == process_data->type) { - SPDLOG_LOGGER_INFO(log_v2::neb(), - "callbacks: generating process end event"); + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: generating process end event"); // Output variable. auto instance{std::make_shared()}; @@ -2681,6 +2690,8 @@ int neb::callback_process(int, void* data) { instance->program_end = time(nullptr); instance->program_start = start_time; instance->version = get_program_version(); + SPDLOG_LOGGER_DEBUG(neb_logger, "callbacks: instance '{}' running {}", + instance->name, instance->is_running); // Send event. gl_publisher.write(instance); @@ -2701,7 +2712,7 @@ int neb::callback_process(int, void* data) { */ int neb::callback_pb_process(int callback_type, void* data) { // Log message. - SPDLOG_LOGGER_DEBUG(log_v2::neb(), "callbacks: process event callback"); + SPDLOG_LOGGER_DEBUG(neb_logger, "callbacks: process event callback"); (void)callback_type; // Input variables. @@ -2717,12 +2728,11 @@ int neb::callback_pb_process(int callback_type, void* data) { // Check process event type. process_data = static_cast(data); if (NEBTYPE_PROCESS_EVENTLOOPSTART == process_data->type) { - SPDLOG_LOGGER_INFO(log_v2::neb(), - "callbacks: generating process start event"); + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: generating process start event"); // Register callbacks. SPDLOG_LOGGER_DEBUG( - log_v2::neb(), "callbacks: registering callbacks for new BBDO version"); + neb_logger, "callbacks: registering callbacks for new BBDO version"); for (uint32_t i = 0; i < sizeof(gl_pb_callbacks) / sizeof(*gl_pb_callbacks); ++i) gl_registered_callbacks.emplace_back( @@ -2733,8 +2743,7 @@ int neb::callback_pb_process(int callback_type, void* data) { if (gl_mod_flags & NEBMODULE_ENGINE) { // Register engine callbacks. SPDLOG_LOGGER_DEBUG( - log_v2::neb(), - "callbacks: registering callbacks for new BBDO version"); + neb_logger, "callbacks: registering callbacks for new BBDO version"); for (uint32_t i = 0; i < sizeof(gl_pb_engine_callbacks) / sizeof(*gl_pb_engine_callbacks); ++i) @@ -2754,8 +2763,7 @@ int neb::callback_pb_process(int callback_type, void* data) { gl_publisher.write(inst_obj); send_initial_pb_configuration(); } else if (NEBTYPE_PROCESS_EVENTLOOPEND == process_data->type) { - SPDLOG_LOGGER_INFO(log_v2::neb(), - "callbacks: generating process end event"); + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: generating process end event"); // Fill output var. inst.set_instance_id(config::applier::state::instance().poller_id()); inst.set_running(false); @@ -2766,6 +2774,8 @@ int neb::callback_pb_process(int callback_type, void* data) { // Send event. gl_publisher.write(inst_obj); } + SPDLOG_LOGGER_DEBUG(neb_logger, "callbacks: instance '{}' running {}", + inst.name(), inst.running()); return 0; } @@ -2784,8 +2794,7 @@ int neb::callback_pb_process(int callback_type, void* data) { */ int neb::callback_program_status(int callback_type, void* data) { // Log message. - SPDLOG_LOGGER_INFO(log_v2::neb(), - "callbacks: generating instance status event"); + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: generating instance status event"); (void)callback_type; try { @@ -2844,7 +2853,7 @@ int neb::callback_program_status(int callback_type, void* data) { */ int neb::callback_pb_program_status(int, void* data) { // Log message. - SPDLOG_LOGGER_INFO(log_v2::neb(), + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: generating pb instance status event"); // In/Out variables. @@ -2856,7 +2865,7 @@ int neb::callback_pb_program_status(int, void* data) { const nebstruct_program_status_data& program_status_data = *static_cast(data); - SPDLOG_LOGGER_INFO(log_v2::neb(), + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: generating pb instance status event " "global_service_event_handler={}", program_status_data.global_host_event_handler); @@ -2904,7 +2913,7 @@ int neb::callback_pb_program_status(int, void* data) { */ int neb::callback_relation(int callback_type, void* data) { // Log message. - SPDLOG_LOGGER_INFO(log_v2::neb(), "callbacks: generating relation event"); + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: generating relation event"); (void)callback_type; try { @@ -2933,7 +2942,7 @@ int neb::callback_relation(int callback_type, void* data) { // Send event. SPDLOG_LOGGER_INFO( - log_v2::neb(), "callbacks: host {} is parent of host {}", + neb_logger, "callbacks: host {} is parent of host {}", new_host_parent->parent_id, new_host_parent->host_id); neb::gl_publisher.write(new_host_parent); } @@ -2961,7 +2970,7 @@ int neb::callback_relation(int callback_type, void* data) { */ int neb::callback_pb_relation(int callback_type [[maybe_unused]], void* data) { // Log message. - SPDLOG_LOGGER_INFO(log_v2::neb(), "callbacks: generating pb relation event"); + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: generating pb relation event"); try { // Input variable. @@ -2976,10 +2985,8 @@ int neb::callback_pb_relation(int callback_type [[maybe_unused]], void* data) { // Find host IDs. int host_id; int parent_id; - { - host_id = engine::get_host_id(relation->dep_hst->name()); - parent_id = engine::get_host_id(relation->hst->name()); - } + host_id = engine::get_host_id(relation->dep_hst->name()); + parent_id = engine::get_host_id(relation->hst->name()); if (host_id && parent_id) { // Generate parent event. auto new_host_parent{std::make_shared()}; @@ -2989,7 +2996,7 @@ int neb::callback_pb_relation(int callback_type [[maybe_unused]], void* data) { new_host_parent->mut_obj().set_parent_id(parent_id); // Send event. - SPDLOG_LOGGER_INFO(log_v2::neb(), + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: pb host {} is parent of host {}", parent_id, host_id); neb::gl_publisher.write(new_host_parent); @@ -3019,7 +3026,7 @@ int neb::callback_pb_relation(int callback_type [[maybe_unused]], void* data) { */ int neb::callback_service(int callback_type, void* data) { // Log message. - SPDLOG_LOGGER_INFO(log_v2::neb(), "callbacks: generating service event"); + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: generating service event"); (void)callback_type; try { @@ -3160,7 +3167,7 @@ int neb::callback_service(int callback_type, void* data) { my_service->service_id = p.second; if (my_service->host_id && my_service->service_id) { // Send service event. - SPDLOG_LOGGER_INFO(log_v2::neb(), + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: new service {} ('{}') on host {}", my_service->service_id, my_service->service_description, my_service->host_id); @@ -3170,7 +3177,7 @@ int neb::callback_service(int callback_type, void* data) { * variables are managed in a different loop. */ } else SPDLOG_LOGGER_ERROR( - log_v2::neb(), + neb_logger, "callbacks: service has no host ID or no service ID (yet) (host " "'{}', service '{}')", (!s->get_hostname().empty() ? my_service->host_name : "(unknown)"), @@ -3198,14 +3205,14 @@ int neb::callback_service(int callback_type, void* data) { * @return 0 on success. */ int neb::callback_pb_service(int callback_type [[maybe_unused]], void* data) { - SPDLOG_LOGGER_INFO(log_v2::neb(), + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: generating pb service event protobuf"); nebstruct_adaptive_service_data* ds = static_cast(data); const engine::service* es{static_cast(ds->object_ptr)}; - SPDLOG_LOGGER_TRACE(log_v2::neb(), "modified_attribute = {}", + SPDLOG_LOGGER_TRACE(neb_logger, "modified_attribute = {}", ds->modified_attribute); if (ds->type == NEBTYPE_ADAPTIVESERVICE_UPDATE && ds->modified_attribute != MODATTR_ALL) { @@ -3243,7 +3250,7 @@ int neb::callback_pb_service(int callback_type [[maybe_unused]], void* data) { else if (ds->modified_attribute & MODATTR_NOTIFICATION_TIMEPERIOD) srv.set_notification_period(es->notification_period()); else { - SPDLOG_LOGGER_ERROR(log_v2::neb(), + SPDLOG_LOGGER_ERROR(neb_logger, "callbacks: adaptive service not implemented."); assert(1 == 0); } @@ -3253,7 +3260,7 @@ int neb::callback_pb_service(int callback_type [[maybe_unused]], void* data) { srv.set_host_id(p.first); srv.set_service_id(p.second); // Send service event. - SPDLOG_LOGGER_INFO(log_v2::neb(), + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: new service {} ('{}') on host {}", srv.service_id(), es->description(), srv.host_id()); neb::gl_publisher.write(s); @@ -3262,7 +3269,7 @@ int neb::callback_pb_service(int callback_type [[maybe_unused]], void* data) { * variables are managed in a different loop. */ } else SPDLOG_LOGGER_ERROR( - log_v2::neb(), + neb_logger, "callbacks: service has no host ID or no service ID (yet) (host " "'{}', service '{}')", !es->get_hostname().empty() ? es->get_hostname() : "(unknown)", @@ -3332,7 +3339,7 @@ int neb::callback_pb_service(int callback_type [[maybe_unused]], void* data) { c != srv.description().end(); ++c) { if (!isdigit(*c)) { SPDLOG_LOGGER_ERROR( - log_v2::neb(), + neb_logger, "callbacks: service ('{}', '{}') looks like a meta-service " "but its name is malformed", name, srv.description()); @@ -3349,7 +3356,7 @@ int neb::callback_pb_service(int callback_type [[maybe_unused]], void* data) { c != srv.description().end(); ++c) { if (!isdigit(*c)) { SPDLOG_LOGGER_ERROR( - log_v2::neb(), + neb_logger, "callbacks: service ('{}', '{}') looks like a " "business-activity but its name is malformed", name, srv.description()); @@ -3453,12 +3460,12 @@ int neb::callback_pb_service(int callback_type [[maybe_unused]], void* data) { srv.set_host_id(p.first); srv.set_service_id(p.second); if (srv.host_id() && srv.service_id()) - SPDLOG_LOGGER_DEBUG(log_v2::neb(), + SPDLOG_LOGGER_DEBUG(neb_logger, "callbacks: service ({}, {}) has a severity id {}", srv.host_id(), srv.service_id(), srv.severity_id()); if (srv.host_id() && srv.service_id()) { // Send service event. - SPDLOG_LOGGER_INFO(log_v2::neb(), + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: new service {} ('{}') on host {}", srv.service_id(), srv.description(), srv.host_id()); neb::gl_publisher.write(s); @@ -3467,7 +3474,7 @@ int neb::callback_pb_service(int callback_type [[maybe_unused]], void* data) { * variables are managed in a different loop. */ } else SPDLOG_LOGGER_ERROR( - log_v2::neb(), + neb_logger, "callbacks: service has no host ID or no service ID (yet) (host " "'{}', service '{}')", (!es->get_hostname().empty() ? srv.host_name() : "(unknown)"), @@ -3500,8 +3507,7 @@ int neb::callback_service_check(int callback_type, void* data) { return 0; // Log message. - SPDLOG_LOGGER_INFO(log_v2::neb(), - "callbacks: generating service check event"); + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: generating service check event"); (void)callback_type; try { @@ -3527,7 +3533,7 @@ int neb::callback_service_check(int callback_type, void* data) { } } catch (std::exception const& e) { SPDLOG_LOGGER_ERROR( - log_v2::neb(), + neb_logger, "callbacks: error occurred while generating service check event: {}", e.what()); } @@ -3561,15 +3567,14 @@ int neb::callback_pb_service_check(int, void* data) { return 0; // Log message. - if (log_v2::neb()->level() <= spdlog::level::debug) { - SPDLOG_LOGGER_DEBUG(log_v2::neb(), + if (neb_logger->level() <= spdlog::level::debug) { + SPDLOG_LOGGER_DEBUG(neb_logger, "callbacks: generating service check event host {} " "service {} command_line={}", scdata->host_id, scdata->service_id, scdata->command_line); } else { - SPDLOG_LOGGER_INFO(log_v2::neb(), - "callbacks: generating service check event"); + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: generating service check event"); } // In/Out variables. @@ -3607,7 +3612,7 @@ int neb::callback_pb_service_check(int, void* data) { */ int32_t neb::callback_severity(int callback_type [[maybe_unused]], void* data) noexcept { - SPDLOG_LOGGER_INFO(log_v2::neb(), + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: generating protobuf severity event"); nebstruct_adaptive_severity_data* ds = @@ -3618,19 +3623,19 @@ int32_t neb::callback_severity(int callback_type [[maybe_unused]], Severity& sv = s.get()->mut_obj(); switch (ds->type) { case NEBTYPE_SEVERITY_ADD: - SPDLOG_LOGGER_INFO(log_v2::neb(), "callbacks: new severity"); + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: new severity"); sv.set_action(Severity_Action_ADD); break; case NEBTYPE_SEVERITY_DELETE: - SPDLOG_LOGGER_INFO(log_v2::neb(), "callbacks: removed severity"); + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: removed severity"); sv.set_action(Severity_Action_DELETE); break; case NEBTYPE_SEVERITY_UPDATE: - SPDLOG_LOGGER_INFO(log_v2::neb(), "callbacks: modified severity"); + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: modified severity"); sv.set_action(Severity_Action_MODIFY); break; default: - SPDLOG_LOGGER_ERROR(log_v2::neb(), + SPDLOG_LOGGER_ERROR(neb_logger, "callbacks: protobuf severity event action must be " "among ADD, MODIFY " "or DELETE"); @@ -3658,7 +3663,7 @@ int32_t neb::callback_severity(int callback_type [[maybe_unused]], */ int32_t neb::callback_tag(int callback_type [[maybe_unused]], void* data) noexcept { - SPDLOG_LOGGER_INFO(log_v2::neb(), "callbacks: generating protobuf tag event"); + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: generating protobuf tag event"); nebstruct_adaptive_tag_data* ds = static_cast(data); @@ -3668,20 +3673,20 @@ int32_t neb::callback_tag(int callback_type [[maybe_unused]], Tag& tg = t.get()->mut_obj(); switch (ds->type) { case NEBTYPE_TAG_ADD: - SPDLOG_LOGGER_INFO(log_v2::neb(), "callbacks: new tag"); + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: new tag"); tg.set_action(Tag_Action_ADD); break; case NEBTYPE_TAG_DELETE: - SPDLOG_LOGGER_INFO(log_v2::neb(), "callbacks: removed tag"); + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: removed tag"); tg.set_action(Tag_Action_DELETE); break; case NEBTYPE_TAG_UPDATE: - SPDLOG_LOGGER_INFO(log_v2::neb(), "callbacks: modified tag"); + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: modified tag"); tg.set_action(Tag_Action_MODIFY); break; default: SPDLOG_LOGGER_ERROR( - log_v2::neb(), + neb_logger, "callbacks: protobuf tag event action must be among ADD, MODIFY " "or DELETE"); return 1; @@ -3703,7 +3708,7 @@ int32_t neb::callback_tag(int callback_type [[maybe_unused]], break; default: SPDLOG_LOGGER_ERROR( - log_v2::neb(), + neb_logger, "callbacks: protobuf tag event type must be among HOSTCATEGORY, " "SERVICECATEGORY, HOSTGROUP pr SERVICEGROUP"); return 1; @@ -3718,15 +3723,14 @@ int32_t neb::callback_tag(int callback_type [[maybe_unused]], int32_t neb::callback_pb_service_status(int callback_type [[maybe_unused]], void* data) noexcept { SPDLOG_LOGGER_INFO( - log_v2::neb(), - "callbacks: generating pb service status check result event"); + neb_logger, "callbacks: generating pb service status check result event"); const engine::service* es{static_cast( static_cast(data)->object_ptr)}; - log_v2::neb()->info("callbacks: pb_service_status ({},{}) status {}, type {}", - es->host_id(), es->service_id(), - static_cast(es->get_current_state()), - static_cast(es->get_check_type())); + neb_logger->info("callbacks: pb_service_status ({},{}) status {}, type {}", + es->host_id(), es->service_id(), + static_cast(es->get_current_state()), + static_cast(es->get_check_type())); auto s{std::make_shared()}; ServiceStatus& sscr = s.get()->mut_obj(); @@ -3734,8 +3738,7 @@ int32_t neb::callback_pb_service_status(int callback_type [[maybe_unused]], sscr.set_host_id(es->host_id()); sscr.set_service_id(es->service_id()); if (es->host_id() == 0 || es->service_id() == 0) - SPDLOG_LOGGER_ERROR(log_v2::neb(), - "could not find ID of service ('{}', '{}')", + SPDLOG_LOGGER_ERROR(neb_logger, "could not find ID of service ('{}', '{}')", es->get_hostname(), es->description()); if (es->problem_has_been_acknowledged()) @@ -3774,11 +3777,11 @@ int32_t neb::callback_pb_service_status(int callback_type [[maybe_unused]], sscr.set_percent_state_change(es->get_percent_state_change()); if (!es->get_perf_data().empty()) { sscr.set_perfdata(misc::string::check_string_utf8(es->get_perf_data())); - SPDLOG_LOGGER_TRACE(log_v2::neb(), + SPDLOG_LOGGER_TRACE(neb_logger, "callbacks: service ({}, {}) has perfdata <<{}>>", es->host_id(), es->service_id(), es->get_perf_data()); } else { - SPDLOG_LOGGER_TRACE(log_v2::neb(), + SPDLOG_LOGGER_TRACE(neb_logger, "callbacks: service ({}, {}) has no perfdata", es->host_id(), es->service_id()); } @@ -3796,7 +3799,7 @@ int32_t neb::callback_pb_service_status(int callback_type [[maybe_unused]], c != es->description().end(); ++c) { if (!isdigit(*c)) { SPDLOG_LOGGER_ERROR( - log_v2::neb(), + neb_logger, "callbacks: service ('{}', '{}') looks like a meta-service " "but its name is malformed", es->get_hostname(), es->description()); @@ -3813,7 +3816,7 @@ int32_t neb::callback_pb_service_status(int callback_type [[maybe_unused]], for (auto c = es->description().begin() + 3; c != es->description().end(); ++c) { if (!isdigit(*c)) { - SPDLOG_LOGGER_ERROR(log_v2::neb(), + SPDLOG_LOGGER_ERROR(neb_logger, "callbacks: service ('{}', '{}') looks like a " "business-activity but its name is malformed", es->get_hostname(), es->description()); @@ -3828,11 +3831,15 @@ int32_t neb::callback_pb_service_status(int callback_type [[maybe_unused]], // Send event(s). gl_publisher.write(s); + neb_logger->debug("Looking for acknowledgement on service ({}:{})", + sscr.host_id(), sscr.service_id()); // Acknowledgement event. auto it = gl_acknowledgements.find( std::make_pair(sscr.host_id(), sscr.service_id())); if (it != gl_acknowledgements.end() && sscr.acknowledgement_type() == AckType::NONE) { + neb_logger->info("acknowledgement found on service ({}:{})", sscr.host_id(), + sscr.service_id()); if (it->second->type() == make_type(io::neb, de_pb_acknowledgement)) { neb::pb_acknowledgement* a = static_cast(it->second.get()); @@ -3853,6 +3860,8 @@ int32_t neb::callback_pb_service_status(int callback_type [[maybe_unused]], } gl_acknowledgements.erase(it); } + neb_logger->debug("Still {} running acknowledgements", + gl_acknowledgements.size()); return 0; } @@ -3871,8 +3880,7 @@ int32_t neb::callback_pb_service_status(int callback_type [[maybe_unused]], */ int neb::callback_service_status(int callback_type, void* data) { // Log message. - SPDLOG_LOGGER_INFO(log_v2::neb(), - "callbacks: generating service status event"); + SPDLOG_LOGGER_INFO(neb_logger, "callbacks: generating service status event"); (void)callback_type; try { @@ -3966,6 +3974,8 @@ int neb::callback_service_status(int callback_type, void* data) { auto it = gl_acknowledgements.find( std::make_pair(service_status->host_id, service_status->service_id)); if (it != gl_acknowledgements.end() && !service_status->acknowledged) { + neb_logger->debug("acknowledgement found on service ({}:{})", + service_status->host_id, service_status->service_id); if (it->second->type() == make_type(io::neb, de_pb_acknowledgement)) { neb::pb_acknowledgement* a = static_cast(it->second.get()); @@ -3988,9 +3998,11 @@ int neb::callback_service_status(int callback_type, void* data) { } gl_acknowledgements.erase(it); } + neb_logger->debug("Still {} running acknowledgements", + gl_acknowledgements.size()); } catch (std::exception const& e) { SPDLOG_LOGGER_ERROR( - log_v2::neb(), + neb_logger, "callbacks: error occurred while generating service status event: {}", e.what()); } @@ -4009,7 +4021,7 @@ int neb::callback_service_status(int callback_type, void* data) { */ int neb::callback_pb_bench(int, void* data) { // Log message. - SPDLOG_LOGGER_DEBUG(log_v2::neb(), "callbacks: generating pb_bench event"); + SPDLOG_LOGGER_DEBUG(neb_logger, "callbacks: generating pb_bench event"); const nebstruct_bench_data* bench_data = static_cast(data); diff --git a/broker/neb/src/initial.cc b/broker/neb/src/initial.cc index b43b11fda9a..71829c4e99d 100644 --- a/broker/neb/src/initial.cc +++ b/broker/neb/src/initial.cc @@ -18,7 +18,6 @@ #include "com/centreon/broker/neb/initial.hh" #include "com/centreon/broker/config/applier/state.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/neb/callbacks.hh" #include "com/centreon/broker/neb/events.hh" #include "com/centreon/broker/neb/internal.hh" @@ -58,7 +57,7 @@ typedef int (*neb_sender)(int, void*); static void send_custom_variables_list( neb_sender sender = neb::callback_custom_variable) { // Start log message. - log_v2::neb()->info("init: beginning custom variables dump"); + neb_logger->info("init: beginning custom variables dump"); // Iterate through all hosts. for (host_map::iterator it{com::centreon::engine::host::hosts.begin()}, @@ -114,7 +113,7 @@ static void send_custom_variables_list( } // End log message. - log_v2::neb()->info("init: end of custom variables dump"); + neb_logger->info("init: end of custom variables dump"); } static void send_pb_custom_variables_list() { @@ -126,7 +125,7 @@ static void send_pb_custom_variables_list() { */ static void send_downtimes_list(neb_sender sender = neb::callback_downtime) { // Start log message. - log_v2::neb()->info("init: beginning downtimes dump"); + neb_logger->info("init: beginning downtimes dump"); std::multimap< time_t, @@ -164,7 +163,7 @@ static void send_downtimes_list(neb_sender sender = neb::callback_downtime) { } // End log message. - log_v2::neb()->info("init: end of downtimes dump"); + neb_logger->info("init: end of downtimes dump"); } /** @@ -180,7 +179,7 @@ static void send_pb_downtimes_list() { static void send_host_dependencies_list( neb_sender callbackfct = neb::callback_dependency) { // Start log message. - log_v2::neb()->info("init: beginning host dependencies dump"); + neb_logger->info("init: beginning host dependencies dump"); try { // Loop through all dependencies. @@ -199,15 +198,15 @@ static void send_host_dependencies_list( callbackfct(NEBCALLBACK_ADAPTIVE_DEPENDENCY_DATA, &nsadd); } } catch (std::exception const& e) { - log_v2::neb()->info( - "init: error occurred while dumping host dependencies: {}", e.what()); + neb_logger->info("init: error occurred while dumping host dependencies: {}", + e.what()); } catch (...) { - log_v2::neb()->error( + neb_logger->error( "init: unknown error occurred while dumping host dependencies"); } // End log message. - log_v2::neb()->info("init: end of host dependencies dump"); + neb_logger->info("init: end of host dependencies dump"); return; } @@ -223,7 +222,7 @@ static void send_host_group_list( neb_sender group_sender = neb::callback_group, neb_sender group_member_sender = neb::callback_group_member) { // Start log message. - log_v2::neb()->info("init: beginning host group dump"); + neb_logger->info("init: beginning host group dump"); // Loop through all host groups. for (hostgroup_map::const_iterator @@ -256,7 +255,7 @@ static void send_host_group_list( } // End log message. - log_v2::neb()->info("init: end of host group dump"); + neb_logger->info("init: end of host group dump"); } static void send_pb_host_group_list() { @@ -268,7 +267,7 @@ static void send_pb_host_group_list() { */ static void send_severity_list() { /* Start log message. */ - log_v2::neb()->info("init: beginning severity dump"); + neb_logger->info("init: beginning severity dump"); for (auto it = com::centreon::engine::severity::severities.begin(), end = com::centreon::engine::severity::severities.end(); @@ -282,7 +281,7 @@ static void send_severity_list() { */ static void send_tag_list() { /* Start log message. */ - log_v2::neb()->info("init: beginning tag dump"); + neb_logger->info("init: beginning tag dump"); for (auto it = com::centreon::engine::tag::tags.begin(), end = com::centreon::engine::tag::tags.end(); @@ -296,7 +295,7 @@ static void send_tag_list() { */ static void send_host_list(neb_sender sender = neb::callback_host) { // Start log message. - log_v2::neb()->info("init: beginning host dump"); + neb_logger->info("init: beginning host dump"); // Loop through all hosts. for (host_map::iterator it{com::centreon::engine::host::hosts.begin()}, @@ -314,7 +313,7 @@ static void send_host_list(neb_sender sender = neb::callback_host) { } // End log message. - log_v2::neb()->info("init: end of host dump"); + neb_logger->info("init: end of host dump"); } /** @@ -329,7 +328,7 @@ static void send_pb_host_list() { */ static void send_host_parents_list(neb_sender sender = neb::callback_relation) { // Start log message. - log_v2::neb()->info("init: beginning host parents dump"); + neb_logger->info("init: beginning host parents dump"); try { // Loop through all hosts. @@ -352,15 +351,15 @@ static void send_host_parents_list(neb_sender sender = neb::callback_relation) { } } } catch (std::exception const& e) { - log_v2::neb()->error("init: error occurred while dumping host parents: {}", - e.what()); + neb_logger->error("init: error occurred while dumping host parents: {}", + e.what()); } catch (...) { - log_v2::neb()->error( + neb_logger->error( "init: unknown error occurred while dumping host parents"); } // End log message. - log_v2::neb()->info("init: end of host parents dump"); + neb_logger->info("init: end of host parents dump"); } /** @@ -377,7 +376,7 @@ static void send_pb_host_parents_list() { static void send_service_dependencies_list( neb_sender sender_fct = neb::callback_dependency) { // Start log message. - log_v2::neb()->info("init: beginning service dependencies dump"); + neb_logger->info("init: beginning service dependencies dump"); try { // Loop through all dependencies. @@ -397,16 +396,16 @@ static void send_service_dependencies_list( sender_fct(NEBCALLBACK_ADAPTIVE_DEPENDENCY_DATA, &nsadd); } } catch (std::exception const& e) { - log_v2::neb()->error( + neb_logger->error( "init: error occurred while dumping service dependencies: {}", e.what()); } catch (...) { - log_v2::neb()->error( + neb_logger->error( "init: unknown error occurred while dumping service dependencies"); } // End log message. - log_v2::neb()->info("init: end of service dependencies dump"); + neb_logger->info("init: end of service dependencies dump"); } static void send_pb_service_dependencies_list() { @@ -420,7 +419,7 @@ static void send_service_group_list( neb_sender group_sender = neb::callback_group, neb_sender group_member_sender = neb::callback_group_member) { // Start log message. - log_v2::neb()->info("init: beginning service group dump"); + neb_logger->info("init: beginning service group dump"); // Loop through all service groups. for (servicegroup_map::const_iterator @@ -453,7 +452,7 @@ static void send_service_group_list( } // End log message. - log_v2::neb()->info("init: end of service groups dump"); + neb_logger->info("init: end of service groups dump"); } static void send_pb_service_group_list() { @@ -466,7 +465,7 @@ static void send_pb_service_group_list() { */ static void send_service_list(neb_sender sender = neb::callback_service) { // Start log message. - log_v2::neb()->info("init: beginning service dump"); + neb_logger->info("init: beginning service dump"); // Loop through all services. for (service_map::const_iterator @@ -485,7 +484,7 @@ static void send_service_list(neb_sender sender = neb::callback_service) { } // End log message. - log_v2::neb()->info("init: end of services dump"); + neb_logger->info("init: end of services dump"); } /** @@ -495,13 +494,14 @@ static void send_pb_service_list() { send_service_list(neb::callback_pb_service); } - /** * Send the instance configuration loaded event. */ static void send_instance_configuration() { - log_v2::neb()->info( - "init: sending initial instance configuration loading event"); + neb_logger->info( + "init: sending initial instance configuration loading event, poller id: " + "{}", + config::applier::state::instance().poller_id()); std::shared_ptr ic( new neb::instance_configuration); ic->loaded = true; @@ -513,7 +513,7 @@ static void send_instance_configuration() { * Send the instance configuration loaded event. */ static void send_pb_instance_configuration() { - log_v2::neb()->info( + neb_logger->info( "init: sending initial instance configuration loading event"); auto ic = std::make_shared(); ic->mut_obj().set_loaded(true); @@ -531,7 +531,7 @@ static void send_pb_instance_configuration() { * Send initial configuration to the global publisher. */ void neb::send_initial_configuration() { - SPDLOG_LOGGER_INFO(log_v2::neb(), "init: send poller conf"); + SPDLOG_LOGGER_INFO(neb_logger, "init: send poller conf"); send_severity_list(); send_tag_list(); send_host_list(); @@ -556,7 +556,7 @@ void neb::send_initial_configuration() { * Send initial configuration to the global publisher. */ void neb::send_initial_pb_configuration() { - SPDLOG_LOGGER_INFO(log_v2::neb(), "init: send poller pb conf"); + SPDLOG_LOGGER_INFO(neb_logger, "init: send poller pb conf"); send_severity_list(); send_tag_list(); send_pb_host_list(); diff --git a/broker/neb/src/neb.cc b/broker/neb/src/neb.cc index 021abdc9d5f..8dde234fa4a 100644 --- a/broker/neb/src/neb.cc +++ b/broker/neb/src/neb.cc @@ -22,18 +22,24 @@ #include "com/centreon/broker/config/applier/init.hh" #include "com/centreon/broker/config/applier/state.hh" #include "com/centreon/broker/config/parser.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/neb/callbacks.hh" #include "com/centreon/broker/neb/instance_configuration.hh" #include "com/centreon/engine/nebcallbacks.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::exceptions; +using com::centreon::common::log_v2::log_v2; // Specify the event broker API version. NEB_API_VERSION(CURRENT_NEB_API_VERSION) +namespace com::centreon::broker { +std::shared_ptr neb_logger = + log_v2::instance().get(log_v2::NEB); +} // namespace com::centreon::broker + extern std::shared_ptr g_io_context; extern "C" { @@ -57,9 +63,6 @@ int nebmodule_deinit(int flags, int reason) { // Unregister callbacks. neb::unregister_callbacks(); - // Unload singletons. - log_v2::instance() - ->stop_flush_timer(); // beware at the order of these two calls com::centreon::broker::config::applier::deinit(); } // Avoid exception propagation in C code. @@ -85,6 +88,8 @@ int nebmodule_deinit(int flags, int reason) { * @return 0 on success, any other value on failure. */ int nebmodule_init(int flags, char const* args, void* handle) { + neb_logger = log_v2::instance().get(log_v2::NEB); + try { // Save module handle and flags for future use. neb::gl_mod_flags = flags; @@ -114,7 +119,6 @@ int nebmodule_init(int flags, char const* args, void* handle) { setlocale(LC_NUMERIC, "C"); try { - log_v2::load(g_io_context); // Set configuration file. if (args) { char const* config_file("config_file="); @@ -131,11 +135,14 @@ int nebmodule_init(int flags, char const* args, void* handle) { p.parse(neb::gl_configuration_file)}; // Initialization. + /* This is a little hack to avoid to replace the log file set by + * centengine */ + s.mut_log_conf().allow_only_atomic_changes(true); com::centreon::broker::config::applier::init(s); try { - log_v2::instance()->apply(s); + log_v2::instance().apply(s.log_conf()); } catch (const std::exception& e) { - log_v2::core()->error("main: {}", e.what()); + log_v2::instance().get(log_v2::CORE)->error("main: {}", e.what()); } com::centreon::broker::config::applier::state::instance().apply(s); @@ -160,20 +167,25 @@ int nebmodule_init(int flags, char const* args, void* handle) { NEBCALLBACK_LOG_DATA, neb::gl_mod_handle, &neb::callback_log)); } } catch (std::exception const& e) { - log_v2::core()->error("main: {}", e.what()); + log_v2::instance().get(log_v2::CORE)->error("main: {}", e.what()); return -1; } catch (...) { - log_v2::core()->error("main: configuration file parsing failed"); + log_v2::instance() + .get(log_v2::CORE) + ->error("main: configuration file parsing failed"); return -1; } } catch (std::exception const& e) { - log_v2::core()->error("main: cbmod loading failed: {}", e.what()); + log_v2::instance() + .get(log_v2::CORE) + ->error("main: cbmod loading failed: {}", e.what()); nebmodule_deinit(0, 0); return -1; } catch (...) { - log_v2::core()->error( - "main: cbmod loading failed due to an unknown exception"); + log_v2::instance() + .get(log_v2::CORE) + ->error("main: cbmod loading failed due to an unknown exception"); nebmodule_deinit(0, 0); return -1; } diff --git a/broker/neb/src/set_log_data.cc b/broker/neb/src/set_log_data.cc index 7e20a64ff93..34ebf9a15da 100644 --- a/broker/neb/src/set_log_data.cc +++ b/broker/neb/src/set_log_data.cc @@ -1,32 +1,33 @@ /** -* Copyright 2009-2011,2015 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2009-2011,2015-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/neb/set_log_data.hh" #include -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/neb/internal.hh" #include "com/centreon/broker/neb/log_entry.hh" #include "com/centreon/engine/host.hh" #include "com/centreon/engine/service.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::exceptions; +using com::centreon::common::log_v2::log_v2; /** * Extract the first element of a log string. @@ -229,19 +230,19 @@ void neb::set_log_data(neb::log_entry& le, char const* log_data) { le.service_id = engine::get_service_id(le.host_name, le.service_description); } -#define test_fail(name) \ - if (ait == args.end()) { \ - log_v2::neb()->error("Missing " name " in log message '{}'", output); \ - return false; \ +#define test_fail(name) \ + if (ait == args.end()) { \ + logger->error("Missing " name " in log message '{}'", output); \ + return false; \ } -#define test_fail_and_not_empty(name) \ - if (ait == args.end()) { \ - log_v2::neb()->error("Missing " name " in log message '{}'", output); \ - return false; \ - } \ - if (ait->empty()) { \ - return false; \ +#define test_fail_and_not_empty(name) \ + if (ait == args.end()) { \ + logger->error("Missing " name " in log message '{}'", output); \ + return false; \ + } \ + if (ait->empty()) { \ + return false; \ } /** @@ -287,6 +288,7 @@ bool neb::set_pb_log_data(neb::pb_log_entry& le, const std::string& output) { lasts = absl::StripLeadingAsciiWhitespace(lasts); auto args = absl::StrSplit(lasts, ';'); auto ait = args.begin(); + auto logger = log_v2::instance().get(log_v2::NEB); if (typ == "SERVICE ALERT") { le_obj.set_msg_type(LogEntry_MsgType_SERVICE_ALERT); @@ -309,7 +311,7 @@ bool neb::set_pb_log_data(neb::pb_log_entry& le, const std::string& output) { test_fail("retry value"); int retry; if (!absl::SimpleAtoi(*ait, &retry)) { - log_v2::neb()->error( + logger->error( "Retry value in log message should be an integer and not '{}'", fmt::string_view(ait->data(), ait->size())); return false; @@ -336,7 +338,7 @@ bool neb::set_pb_log_data(neb::pb_log_entry& le, const std::string& output) { test_fail("retry value"); int retry; if (!absl::SimpleAtoi(*ait, &retry)) { - log_v2::neb()->error( + logger->error( "Retry value in log message should be an integer and not '{}'", fmt::string_view(ait->data(), ait->size())); return false; @@ -410,7 +412,7 @@ bool neb::set_pb_log_data(neb::pb_log_entry& le, const std::string& output) { test_fail("retry value"); int retry; if (!absl::SimpleAtoi(*ait, &retry)) { - log_v2::neb()->error( + logger->error( "Retry value in log message should be an integer and not '{}'", fmt::string_view(ait->data(), ait->size())); return false; @@ -442,7 +444,7 @@ bool neb::set_pb_log_data(neb::pb_log_entry& le, const std::string& output) { test_fail("retry value"); int retry; if (!absl::SimpleAtoi(*ait, &retry)) { - log_v2::neb()->error( + logger->error( "Retry value in log message should be an integer and not '{}'", fmt::string_view(ait->data(), ait->size())); return false; @@ -517,7 +519,7 @@ bool neb::set_pb_log_data(neb::pb_log_entry& le, const std::string& output) { test_fail("retry value"); int retry; if (!absl::SimpleAtoi(*ait, &retry)) { - log_v2::neb()->error( + logger->error( "Retry value in log message should be an integer and not '{}'", fmt::string_view(ait->data(), ait->size())); return false; @@ -549,7 +551,7 @@ bool neb::set_pb_log_data(neb::pb_log_entry& le, const std::string& output) { test_fail("retry value"); int retry; if (!absl::SimpleAtoi(*ait, &retry)) { - log_v2::neb()->error( + logger->error( "Retry value in log message should be an integer and not '{}'", fmt::string_view(ait->data(), ait->size())); return false; @@ -577,7 +579,7 @@ bool neb::set_pb_log_data(neb::pb_log_entry& le, const std::string& output) { test_fail("retry value"); int retry; if (!absl::SimpleAtoi(*ait, &retry)) { - log_v2::neb()->error( + logger->error( "Retry value in log message should be an integer and not '{}'", fmt::string_view(ait->data(), ait->size())); return false; @@ -609,7 +611,7 @@ bool neb::set_pb_log_data(neb::pb_log_entry& le, const std::string& output) { test_fail("retry value"); int retry; if (!absl::SimpleAtoi(*ait, &retry)) { - log_v2::neb()->error( + logger->error( "Retry value in log message should be an integer and not '{}'", fmt::string_view(ait->data(), ait->size())); return false; diff --git a/broker/rrd/inc/com/centreon/broker/rrd/backend.hh b/broker/rrd/inc/com/centreon/broker/rrd/backend.hh index 1845c6b5f62..748e3f19f19 100644 --- a/broker/rrd/inc/com/centreon/broker/rrd/backend.hh +++ b/broker/rrd/inc/com/centreon/broker/rrd/backend.hh @@ -1,27 +1,30 @@ -/* -** Copyright 2011-2013, 2021 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2011-2013, 2021-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_RRD_BACKEND_HH #define CCB_RRD_BACKEND_HH +#include "common/log_v2/log_v2.hh" namespace com::centreon::broker { +using log_v2 = com::centreon::common::log_v2::log_v2; + namespace rrd { /** * @class backend backend.hh "com/centreon/broker/rrd/backend.hh" @@ -34,8 +37,11 @@ namespace rrd { * @see rrd::cached */ class backend { + protected: + std::shared_ptr _logger; + public: - backend() = default; + backend() : _logger{log_v2::instance().get(log_v2::RRD)} {} backend(backend const& b) = delete; virtual ~backend() noexcept = default; backend& operator=(backend const& b) = delete; @@ -56,6 +62,6 @@ class backend { }; } // namespace rrd -} +} // namespace com::centreon::broker #endif // !CCB_RRD_BACKEND_HH diff --git a/broker/rrd/inc/com/centreon/broker/rrd/cached.hh b/broker/rrd/inc/com/centreon/broker/rrd/cached.hh index 0078c68cc9a..25a98b7b5a6 100644 --- a/broker/rrd/inc/com/centreon/broker/rrd/cached.hh +++ b/broker/rrd/inc/com/centreon/broker/rrd/cached.hh @@ -1,33 +1,34 @@ -/* -** Copyright 2020 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2020-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_RRD_CACHED_HH #define CCB_RRD_CACHED_HH #include -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/rrd/exceptions/open.hh" #include "com/centreon/broker/rrd/exceptions/update.hh" #include "com/centreon/broker/rrd/lib.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon; using namespace com::centreon::exceptions; +using log_v2 = com::centreon::common::log_v2::log_v2; namespace com::centreon::broker { @@ -110,18 +111,18 @@ class cached : public backend { */ void remove(std::string const& filename) { // Build rrdcached command. - log_v2::rrd()->trace("RRD: FORGET the {} file", filename); + _logger->trace("RRD: FORGET the {} file", filename); std::string cmd(fmt::format("FORGET {}\n", filename)); try { _send_to_cached(cmd); } catch (msg_fmt const& e) { - log_v2::rrd()->error(e.what()); + _logger->error(e.what()); } if (::remove(filename.c_str())) - log_v2::rrd()->error("RRD: could not remove file '{}': {}", filename, - strerror(errno)); + _logger->error("RRD: could not remove file '{}': {}", filename, + strerror(errno)); } /** @@ -273,39 +274,39 @@ class cached : public backend { std::string cmd(fmt::format("UPDATE {} {}:{}\n", _filename, t, value)); // Send command. - log_v2::rrd()->debug("RRD: updating file '{}' ({})", _filename, cmd); + _logger->debug("RRD: updating file '{}' ({})", _filename, cmd); try { _send_to_cached(cmd); } catch (msg_fmt const& e) { if (!strstr(e.what(), "illegal attempt to update using time")) throw exceptions::update(e.what()); else - log_v2::rrd()->error("RRD: ignored update error in file '{}': {}", - _filename, e.what() + 5); + _logger->error("RRD: ignored update error in file '{}': {}", _filename, + e.what() + 5); } } void update(const std::deque& pts) { - log_v2::rrd()->debug("RRD: updating file '{}' with {} values", _filename, - pts.size()); + _logger->debug("RRD: updating file '{}' with {} values", _filename, + pts.size()); std::string cmd{ fmt::format("UPDATE {} {}\n", _filename, fmt::join(pts, " "))}; try { _send_to_cached(cmd); - log_v2::rrd()->trace("RRD: flushing file '{}'", _filename); + _logger->trace("RRD: flushing file '{}'", _filename); _send_to_cached(fmt::format("FLUSH {}\n", _filename)); } catch (msg_fmt const& e) { if (!strstr(e.what(), "illegal attempt to update using time")) throw exceptions::update(e.what()); else - log_v2::rrd()->error("RRD: ignored update error in file '{}': {}", - _filename, e.what() + 5); + _logger->error("RRD: ignored update error in file '{}': {}", _filename, + e.what() + 5); } } }; } // namespace rrd -} +} // namespace com::centreon::broker #endif /* !CCB_RRD_CACHED_HH */ diff --git a/broker/rrd/inc/com/centreon/broker/rrd/connector.hh b/broker/rrd/inc/com/centreon/broker/rrd/connector.hh index 867a9619d2c..12b968995ee 100644 --- a/broker/rrd/inc/com/centreon/broker/rrd/connector.hh +++ b/broker/rrd/inc/com/centreon/broker/rrd/connector.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2011-2013, 2020-2021 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2011-2013, 2020-2021 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_RRD_CONNECTOR_HH #define CCB_RRD_CONNECTOR_HH @@ -31,6 +31,17 @@ namespace rrd { * Generate an RRD stream that will write files. */ class connector : public io::endpoint { + std::string _real_path_of(std::string const& path); + + uint32_t _cache_size; + std::string _cached_local; + uint16_t _cached_port; + bool _ignore_update_errors; + std::string _metrics_path; + std::string _status_path; + bool _write_metrics; + bool _write_status; + public: connector(); connector(const connector&) = delete; @@ -45,21 +56,9 @@ class connector : public io::endpoint { void set_status_path(std::string const& status_path); void set_write_metrics(bool write_metrics) noexcept; void set_write_status(bool write_status) noexcept; - - private: - std::string _real_path_of(std::string const& path); - - uint32_t _cache_size; - std::string _cached_local; - uint16_t _cached_port; - bool _ignore_update_errors; - std::string _metrics_path; - std::string _status_path; - bool _write_metrics; - bool _write_status; }; } // namespace rrd -} +} // namespace com::centreon::broker #endif // !CCB_RRD_CONNECTOR_HH diff --git a/broker/rrd/inc/com/centreon/broker/rrd/creator.hh b/broker/rrd/inc/com/centreon/broker/rrd/creator.hh index 0d28c8a34c7..ab2305a50dd 100644 --- a/broker/rrd/inc/com/centreon/broker/rrd/creator.hh +++ b/broker/rrd/inc/com/centreon/broker/rrd/creator.hh @@ -1,27 +1,26 @@ -/* -** Copyright 2013 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2013 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_RRD_CREATOR_HH #define CCB_RRD_CREATOR_HH #include - namespace com::centreon::broker { namespace rrd { @@ -32,20 +31,6 @@ namespace rrd { * Create RRD objects. */ class creator { - public: - creator(std::string const& tmpl_path, uint32_t cache_size); - creator(creator const&) = delete; - ~creator(); - creator& operator=(creator const&) = delete; - void clear(); - void create(std::string const& filename, - uint32_t length, - time_t from, - uint32_t step, - short value_type, - bool without_cache = false); - - private: struct tmpl_info { bool operator<(tmpl_info const& right) const { if (length != right.length) @@ -94,9 +79,22 @@ class creator { uint32_t _cache_size; std::map _fds; std::string _tmpl_path; + + public: + creator(std::string const& tmpl_path, uint32_t cache_size); + creator(creator const&) = delete; + ~creator(); + creator& operator=(creator const&) = delete; + void clear(); + void create(std::string const& filename, + uint32_t length, + time_t from, + uint32_t step, + short value_type, + bool without_cache = false); }; } // namespace rrd -} +} // namespace com::centreon::broker #endif // !CCB_RRD_CREATOR_HH diff --git a/broker/rrd/inc/com/centreon/broker/rrd/factory.hh b/broker/rrd/inc/com/centreon/broker/rrd/factory.hh index 321551c4c95..8fcc5afe351 100644 --- a/broker/rrd/inc/com/centreon/broker/rrd/factory.hh +++ b/broker/rrd/inc/com/centreon/broker/rrd/factory.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2011-2013 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2011-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_RRD_FACTORY_HH #define CCB_RRD_FACTORY_HH @@ -45,6 +45,6 @@ class factory : public io::factory { }; } // namespace rrd -} +} // namespace com::centreon::broker #endif // !CCB_RRD_FACTORY_HH diff --git a/broker/rrd/inc/com/centreon/broker/rrd/internal.hh b/broker/rrd/inc/com/centreon/broker/rrd/internal.hh index a5832c09d1e..0cdca9e78b3 100644 --- a/broker/rrd/inc/com/centreon/broker/rrd/internal.hh +++ b/broker/rrd/inc/com/centreon/broker/rrd/internal.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2021 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2021 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_RRD_INTERNAL_HH #define CCB_RRD_INTERNAL_HH @@ -45,6 +45,6 @@ using pb_metric = using pb_status = io::protobuf; } // namespace storage -} +} // namespace com::centreon::broker #endif /* !CCB_RRD_INTERNAL_HH */ diff --git a/broker/rrd/inc/com/centreon/broker/rrd/lib.hh b/broker/rrd/inc/com/centreon/broker/rrd/lib.hh index 1591b71751d..99cbcb96db6 100644 --- a/broker/rrd/inc/com/centreon/broker/rrd/lib.hh +++ b/broker/rrd/inc/com/centreon/broker/rrd/lib.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2011-2013 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2011-2013 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_RRD_LIB_HH #define CCB_RRD_LIB_HH @@ -59,6 +59,6 @@ class lib : public backend { }; } // namespace rrd -} +} // namespace com::centreon::broker #endif // !CCB_RRD_LIB_HH diff --git a/broker/rrd/inc/com/centreon/broker/rrd/output.hh b/broker/rrd/inc/com/centreon/broker/rrd/output.hh index 929b68df5d9..2e4b30d49be 100644 --- a/broker/rrd/inc/com/centreon/broker/rrd/output.hh +++ b/broker/rrd/inc/com/centreon/broker/rrd/output.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2011-2013 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2011-2013 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_RRD_OUTPUT_HH #define CCB_RRD_OUTPUT_HH @@ -52,6 +52,9 @@ class output : public io::stream { const bool _write_status; T _backend; + /* Loggers */ + std::shared_ptr _logger; + void _rebuild_data(const RebuildMessage& rm); public: @@ -86,6 +89,6 @@ class output : public io::stream { } // namespace rrd -} +} // namespace com::centreon::broker #endif // !CCB_RRD_OUTPUT_HH diff --git a/broker/rrd/src/connector.cc b/broker/rrd/src/connector.cc index b11b9e3e181..278204f2364 100644 --- a/broker/rrd/src/connector.cc +++ b/broker/rrd/src/connector.cc @@ -1,48 +1,51 @@ /** -* Copyright 2011-2014 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2014 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/rrd/connector.hh" #include "bbdo/storage/metric.hh" #include "bbdo/storage/remove_graph.hh" #include "bbdo/storage/status.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/rrd/internal.hh" #include "com/centreon/broker/rrd/output.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::rrd; +using log_v2 = com::centreon::common::log_v2::log_v2; + +static constexpr multiplexing::muxer_filter _rrd_stream_filter = + multiplexing::muxer_filter( + {storage::metric::static_type(), storage::pb_metric::static_type(), + storage::status::static_type(), storage::pb_status::static_type(), + storage::pb_rebuild_message::static_type(), + storage::remove_graph::static_type(), + storage::pb_remove_graph_message::static_type(), + make_type(io::extcmd, extcmd::de_pb_bench)}); -static constexpr multiplexing::muxer_filter _rrd_stream_filter = { - storage::metric::static_type(), - storage::pb_metric::static_type(), - storage::status::static_type(), - storage::pb_status::static_type(), - storage::pb_rebuild_message::static_type(), - storage::remove_graph::static_type(), - storage::pb_remove_graph_message::static_type(), - make_type(io::extcmd, extcmd::de_pb_bench)}; +static constexpr multiplexing::muxer_filter _rrd_forbidden_filter = + multiplexing::muxer_filter(_rrd_stream_filter).reverse(); /** * Default constructor. */ connector::connector() - : io::endpoint(false, _rrd_stream_filter), + : io::endpoint(false, _rrd_stream_filter, _rrd_forbidden_filter), _cache_size(16), _cached_port(0), _ignore_update_errors(true), @@ -161,10 +164,11 @@ std::string connector::_real_path_of(std::string const& path) { // Variables. std::string retval; char* real_path{realpath(path.c_str(), nullptr)}; + auto logger = log_v2::instance().get(log_v2::RRD); // Resolution success. if (real_path) { - log_v2::rrd()->info("RRD: path '{}' resolved as '{}'", path, real_path); + logger->info("RRD: path '{}' resolved as '{}'", path, real_path); try { retval = real_path; } catch (...) { @@ -176,8 +180,8 @@ std::string connector::_real_path_of(std::string const& path) { // Resolution failure. else { char const* msg{strerror(errno)}; - log_v2::rrd()->error( - "RRD: could not resolve path '{}', using it as such: {}", path, msg); + logger->error("RRD: could not resolve path '{}', using it as such: {}", + path, msg); retval = path; } diff --git a/broker/rrd/src/creator.cc b/broker/rrd/src/creator.cc index 231336df3e4..d15259eb08f 100644 --- a/broker/rrd/src/creator.cc +++ b/broker/rrd/src/creator.cc @@ -1,20 +1,20 @@ /** -* Copyright 2013-2017 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2013-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include #include @@ -30,13 +30,14 @@ #include #include "bbdo/storage/metric.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/perfdata.hh" #include "com/centreon/broker/rrd/creator.hh" #include "com/centreon/broker/rrd/exceptions/open.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::rrd; +using com::centreon::common::log_v2::log_v2; /** * Constructor. @@ -47,7 +48,7 @@ using namespace com::centreon::broker::rrd; creator::creator(std::string const& tmpl_path, uint32_t cache_size) : _cache_size(cache_size), _tmpl_path(tmpl_path) { SPDLOG_LOGGER_DEBUG( - log_v2::rrd(), + log_v2::instance().get(log_v2::RRD), "RRD: file creator will maintain at most {} templates in '{}'", _cache_size, _tmpl_path); } @@ -107,8 +108,8 @@ void creator::create(std::string const& filename, if (it != _fds.end() && it->first.is_length_step_type_equal(info) && it->first.from <= from) { _duplicate(filename, it->second); - SPDLOG_LOGGER_DEBUG(log_v2::rrd(), "reuse {} for {}", it->second.path, - filename); + SPDLOG_LOGGER_DEBUG(log_v2::instance().get(log_v2::RRD), + "reuse {} for {}", it->second.path, filename); } // Not in the cache, but we have enough space in the cache. // Create new entry. @@ -266,9 +267,10 @@ void creator::_open(std::string const& filename, // Debug message. argv[argc] = nullptr; + auto logger = log_v2::instance().get(log_v2::RRD); SPDLOG_LOGGER_DEBUG( - log_v2::rrd(), "RRD: create file '{}' ({}, {}, {}, step 1, from {})", - filename, argv[0], argv[1], (argv[2] ? argv[2] : "(null)"), from); + logger, "RRD: create file '{}' ({}, {}, {}, step 1, from {})", filename, + argv[0], argv[1], (argv[2] ? argv[2] : "(null)"), from); // Create RRD file. rrd_clear_error(); @@ -284,7 +286,7 @@ void creator::_open(std::string const& filename, std::filesystem::perms::group_read | std::filesystem::perms::group_write, std::filesystem::perm_options::add, err); if (err) { - SPDLOG_LOGGER_ERROR(log_v2::rrd(), + SPDLOG_LOGGER_ERROR(logger, "RRD: fail to add access rights (660) to {}: {}", filename, err.message()); } diff --git a/broker/rrd/src/factory.cc b/broker/rrd/src/factory.cc index 004c40ec85a..2242c5218c7 100644 --- a/broker/rrd/src/factory.cc +++ b/broker/rrd/src/factory.cc @@ -1,31 +1,32 @@ /** -* Copyright 2011-2022 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2022 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/rrd/factory.hh" #include "com/centreon/broker/config/parser.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/rrd/connector.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::rrd; +using com::centreon::common::log_v2::log_v2; /** * Search for a property value. @@ -80,6 +81,8 @@ io::endpoint* factory::new_endpoint( std::shared_ptr cache) const { (void)cache; + auto logger = log_v2::instance().get(log_v2::RRD); + // Local socket path. std::string path{find_param(cfg, "path", false)}; @@ -106,10 +109,12 @@ io::endpoint* factory::new_endpoint( cfg.params.find("write_metrics")); if (it != cfg.params.end()) { if (!absl::SimpleAtob(it->second, &write_metrics)) { - log_v2::rrd()->error( - "factory: cannot parse the 'write_metrics' boolean: the content is " - "'{}'", - it->second); + log_v2::instance() + .get(log_v2::CORE) + ->error( + "factory: cannot parse the 'write_metrics' boolean: the " + "content is '{}'", + it->second); write_metrics = true; } } else @@ -123,10 +128,12 @@ io::endpoint* factory::new_endpoint( cfg.params.find("write_status")}; if (it != cfg.params.end()) { if (!absl::SimpleAtob(it->second, &write_status)) { - log_v2::rrd()->error( - "factory: cannot parse the 'write_status' boolean: the content is " - "'{}'", - it->second); + log_v2::instance() + .get(log_v2::CORE) + ->error( + "factory: cannot parse the 'write_status' boolean: the content " + "is '{}'", + it->second); write_status = true; } } else @@ -147,7 +154,7 @@ io::endpoint* factory::new_endpoint( cfg.params.find("ignore_update_errors")}; if (it != cfg.params.end()) { if (!absl::SimpleAtob(it->second, &ignore_update_errors)) { - log_v2::rrd()->error( + logger->error( "factory: cannot parse the 'ignore_update_errors' boolean: the " "content is '{}'", it->second); diff --git a/broker/rrd/src/lib.cc b/broker/rrd/src/lib.cc index 431637e2d98..c1979849d57 100644 --- a/broker/rrd/src/lib.cc +++ b/broker/rrd/src/lib.cc @@ -1,20 +1,20 @@ /** -* Copyright 2011-2013,2015,2017 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2013,2015,2017 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/rrd/lib.hh" @@ -26,7 +26,6 @@ #include #include "bbdo/storage/metric.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/rrd/exceptions/open.hh" #include "com/centreon/broker/rrd/exceptions/update.hh" @@ -119,9 +118,9 @@ void lib::open(std::string const& filename, void lib::remove(std::string const& filename) { if (::remove(filename.c_str())) { char const* msg(strerror(errno)); - log_v2::rrd()->error("RRD: could not remove file '{}': {}", filename, msg); + _logger->error("RRD: could not remove file '{}': {}", filename, msg); } else - SPDLOG_LOGGER_INFO(log_v2::rrd(), "remove file {}", filename); + SPDLOG_LOGGER_INFO(_logger, "remove file {}", filename); } /** @@ -133,9 +132,8 @@ void lib::remove(std::string const& filename) { void lib::update(time_t t, std::string const& value) { // Build argument string. if (value == "") { - log_v2::rrd()->error( - "RRD: ignored update non-float value '{}' in file '{}'", value, - _filename); + _logger->error("RRD: ignored update non-float value '{}' in file '{}'", + value, _filename); return; } @@ -147,7 +145,7 @@ void lib::update(time_t t, std::string const& value) { argv[1] = nullptr; // Debug message. - log_v2::perfdata()->debug("RRD: updating file '{}' ({})", _filename, argv[0]); + _logger->debug("RRD: updating file '{}' ({})", _filename, argv[0]); // Update RRD file. rrd_clear_error(); @@ -155,12 +153,12 @@ void lib::update(time_t t, std::string const& value) { argv)) { char const* msg(rrd_get_error()); if (!strstr(msg, "illegal attempt to update using time")) - log_v2::rrd()->error("RRD: failed to update value in file '{}': {}", - _filename, msg); + _logger->error("RRD: failed to update value in file '{}': {}", _filename, + msg); else - log_v2::rrd()->error("RRD: ignored update error in file '{}': {}", - _filename, msg); + _logger->error("RRD: ignored update error in file '{}': {}", _filename, + msg); } } @@ -169,7 +167,7 @@ void lib::update(const std::deque& pts) { argv[pts.size()] = nullptr; auto it = pts.begin(); for (uint32_t i = 0; i < pts.size(); i++) { - log_v2::rrd()->trace("insertion of {} in rrd file", *it); + _logger->trace("insertion of {} in rrd file", *it); argv[i] = it->data(); ++it; } @@ -178,11 +176,11 @@ void lib::update(const std::deque& pts) { argv)) { char const* msg(rrd_get_error()); if (!strstr(msg, "illegal attempt to update using time")) - log_v2::rrd()->error("RRD: failed to update value in file '{}': {}", - _filename, msg); + _logger->error("RRD: failed to update value in file '{}': {}", _filename, + msg); else - log_v2::rrd()->error("RRD: ignored update error in file '{}': {}", - _filename, msg); + _logger->error("RRD: ignored update error in file '{}': {}", _filename, + msg); } } diff --git a/broker/rrd/src/main.cc b/broker/rrd/src/main.cc index 7d50e03675e..c5405868cc4 100644 --- a/broker/rrd/src/main.cc +++ b/broker/rrd/src/main.cc @@ -1,20 +1,20 @@ /** -* Copyright 2011-2013, 2020-2021 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2013, 2020-2021 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include @@ -25,11 +25,12 @@ #include "bbdo/storage/status.hh" #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/io/protocols.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/rrd/factory.hh" #include "com/centreon/broker/rrd/internal.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; +using log_v2 = com::centreon::common::log_v2::log_v2; // Load count. static uint32_t instances(0); @@ -68,17 +69,17 @@ bool broker_module_deinit() { */ void broker_module_init(void const* arg) { (void)arg; + auto logger = log_v2::instance().get(log_v2::RRD); // Increment instance number. if (!instances++) { // RRD module. - log_v2::rrd()->info("RRD: module for Centreon Broker {}", - CENTREON_BROKER_VERSION); + logger->info("RRD: module for Centreon Broker {}", CENTREON_BROKER_VERSION); // Print RRDtool version. char const* rrdversion(rrd_strversion()); - log_v2::rrd()->info("RRD: using rrdtool {}", - (rrdversion ? rrdversion : "(unknown)")); + logger->info("RRD: using rrdtool {}", + (rrdversion ? rrdversion : "(unknown)")); io::events& e(io::events::instance()); diff --git a/broker/rrd/src/output.cc b/broker/rrd/src/output.cc index a9b4840c7d4..17175958d2b 100644 --- a/broker/rrd/src/output.cc +++ b/broker/rrd/src/output.cc @@ -21,6 +21,7 @@ #include #include + #include #include #include @@ -30,10 +31,10 @@ #include "bbdo/storage/status.hh" #include "com/centreon/broker/exceptions/shutdown.hh" #include "com/centreon/broker/io/events.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/perfdata.hh" #include "com/centreon/broker/rrd/exceptions/open.hh" #include "com/centreon/broker/rrd/exceptions/update.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::rrd; @@ -85,8 +86,8 @@ output::output(std::string const& metrics_path, _status_path(status_path), _write_metrics(write_metrics), _write_status(write_status), - _backend(!metrics_path.empty() ? metrics_path : status_path, cache_size) { -} + _backend(!metrics_path.empty() ? metrics_path : status_path, cache_size), + _logger{log_v2::instance().get(log_v2::RRD)} {} /** * Local socket constructor. @@ -116,7 +117,8 @@ output>::output( _status_path(status_path), _write_metrics(write_metrics), _write_status(write_status), - _backend(metrics_path, cache_size) { + _backend(metrics_path, cache_size), + _logger{log_v2::instance().get(log_v2::RRD)} { _backend.connect_local(local); } @@ -186,7 +188,7 @@ void output::update() { */ template int output::write(std::shared_ptr const& d) { - SPDLOG_LOGGER_TRACE(log_v2::rrd(), "RRD: output::write."); + SPDLOG_LOGGER_TRACE(_logger, "RRD: output::write."); // Check that data exists. if (!validate(d, "RRD")) return 1; @@ -198,8 +200,7 @@ int output::write(std::shared_ptr const& d) { std::shared_ptr e( std::static_pointer_cast(d)); auto& m = e->obj(); - SPDLOG_LOGGER_DEBUG(log_v2::rrd(), - "RRD: new pb data for metric {} (time {})", + SPDLOG_LOGGER_DEBUG(_logger, "RRD: new pb data for metric {} (time {})", m.metric_id(), m.time()); // Metric path. @@ -220,37 +221,35 @@ int output::write(std::shared_ptr const& d) { } std::string v; switch (m.value_type()) { - case misc::perfdata::gauge: + case Metric_ValueType_GAUGE: v = fmt::format("{:f}", m.value()); - SPDLOG_LOGGER_TRACE(log_v2::rrd(), + SPDLOG_LOGGER_TRACE(_logger, "RRD: update metric {} of type GAUGE with {}", m.metric_id(), v); break; - case misc::perfdata::counter: + case Metric_ValueType_COUNTER: v = fmt::format("{}", static_cast(m.value())); SPDLOG_LOGGER_TRACE( - log_v2::rrd(), - "RRD: update metric {} of type COUNTER with {}", + _logger, "RRD: update metric {} of type COUNTER with {}", m.metric_id(), v); break; - case misc::perfdata::derive: + case Metric_ValueType_DERIVE: v = fmt::format("{}", static_cast(m.value())); SPDLOG_LOGGER_TRACE( - log_v2::rrd(), "RRD: update metric {} of type DERIVE with {}", + _logger, "RRD: update metric {} of type DERIVE with {}", m.metric_id(), v); break; - case misc::perfdata::absolute: + case Metric_ValueType_ABSOLUTE: v = fmt::format("{}", static_cast(m.value())); SPDLOG_LOGGER_TRACE( - log_v2::rrd(), - "RRD: update metric {} of type ABSOLUTE with {}", + _logger, "RRD: update metric {} of type ABSOLUTE with {}", m.metric_id(), v); break; default: v = fmt::format("{:f}", m.value()); - SPDLOG_LOGGER_TRACE( - log_v2::rrd(), "RRD: update metric {} of type {} with {}", - m.metric_id(), static_cast(m.value_type()), v); + SPDLOG_LOGGER_TRACE(_logger, + "RRD: update metric {} of type {} with {}", + m.metric_id(), m.value_type(), v); break; } _backend.update(m.time(), v); @@ -264,9 +263,8 @@ int output::write(std::shared_ptr const& d) { // Debug message. std::shared_ptr e( std::static_pointer_cast(d)); - SPDLOG_LOGGER_DEBUG(log_v2::rrd(), - "RRD: new data for metric {} (time {}) {}", - e->metric_id, static_cast(e->time), + SPDLOG_LOGGER_DEBUG(_logger, "RRD: new data for metric {} (time {}) {}", + e->metric_id, e->time, e->is_for_rebuild ? "for rebuild" : ""); // Metric path. @@ -289,33 +287,31 @@ int output::write(std::shared_ptr const& d) { switch (e->value_type) { case misc::perfdata::gauge: v = fmt::format("{:f}", e->value); - SPDLOG_LOGGER_TRACE(log_v2::rrd(), + SPDLOG_LOGGER_TRACE(_logger, "RRD: update metric {} of type GAUGE with {}", e->metric_id, v); break; case misc::perfdata::counter: v = fmt::format("{}", static_cast(e->value)); SPDLOG_LOGGER_TRACE( - log_v2::rrd(), - "RRD: update metric {} of type COUNTER with {}", e->metric_id, - v); + _logger, "RRD: update metric {} of type COUNTER with {}", + e->metric_id, v); break; case misc::perfdata::derive: v = fmt::format("{}", static_cast(e->value)); SPDLOG_LOGGER_TRACE( - log_v2::rrd(), "RRD: update metric {} of type DERIVE with {}", + _logger, "RRD: update metric {} of type DERIVE with {}", e->metric_id, v); break; case misc::perfdata::absolute: v = fmt::format("{}", static_cast(e->value)); SPDLOG_LOGGER_TRACE( - log_v2::rrd(), - "RRD: update metric {} of type ABSOLUTE with {}", + _logger, "RRD: update metric {} of type ABSOLUTE with {}", e->metric_id, v); break; default: v = fmt::format("{:f}", e->value); - SPDLOG_LOGGER_TRACE(log_v2::rrd(), + SPDLOG_LOGGER_TRACE(_logger, "RRD: update metric {} of type {} with {}", e->metric_id, e->value_type, v); break; @@ -332,7 +328,7 @@ int output::write(std::shared_ptr const& d) { std::shared_ptr e( std::static_pointer_cast(d)); const auto& s = e->obj(); - SPDLOG_LOGGER_DEBUG(log_v2::rrd(), + SPDLOG_LOGGER_DEBUG(_logger, "RRD: new pb status data for index {} (state {})", s.index_id(), s.state()); @@ -372,7 +368,7 @@ int output::write(std::shared_ptr const& d) { std::shared_ptr e( std::static_pointer_cast(d)); SPDLOG_LOGGER_DEBUG( - log_v2::rrd(), "RRD: new status data for index {} (state {}) {}", + _logger, "RRD: new status data for index {} (state {}) {}", e->index_id, e->state, e->is_for_rebuild ? "for rebuild" : ""); // Status path. @@ -406,19 +402,17 @@ int output::write(std::shared_ptr const& d) { } break; case storage::pb_rebuild_message::static_type(): { - SPDLOG_LOGGER_DEBUG(log_v2::rrd(), "RRD: RebuildMessage received"); + SPDLOG_LOGGER_DEBUG(_logger, "RRD: RebuildMessage received"); std::shared_ptr e{ std::static_pointer_cast(d)}; switch (e->obj().state()) { case RebuildMessage_State_START: if (e->obj().metric_to_index_id().empty()) { - SPDLOG_LOGGER_ERROR(log_v2::rrd(), - "RRD: rebuild empty metric list"); + SPDLOG_LOGGER_ERROR(_logger, "RRD: rebuild empty metric list"); return 1; } SPDLOG_LOGGER_INFO( - log_v2::rrd(), - "RRD: Starting to rebuild metrics ({}) status ({})", + _logger, "RRD: Starting to rebuild metrics ({}) status ({})", fmt::join(keys_of_map(e->obj().metric_to_index_id()), ","), fmt::join(values_of_map(e->obj().metric_to_index_id()), ",")); // Rebuild is starting. @@ -442,22 +436,19 @@ int output::write(std::shared_ptr const& d) { break; case RebuildMessage_State_DATA: if (_metrics_rebuild.empty()) { - SPDLOG_LOGGER_ERROR(log_v2::rrd(), - "RRD: rebuild empty metric list"); + SPDLOG_LOGGER_ERROR(_logger, "RRD: rebuild empty metric list"); return 1; } - SPDLOG_LOGGER_DEBUG(log_v2::rrd(), "RRD: Data to rebuild metrics"); + SPDLOG_LOGGER_DEBUG(_logger, "RRD: Data to rebuild metrics"); _rebuild_data(e->obj()); break; case RebuildMessage_State_END: if (e->obj().metric_to_index_id().empty()) { - SPDLOG_LOGGER_ERROR(log_v2::rrd(), - "RRD: rebuild empty metric list"); + SPDLOG_LOGGER_ERROR(_logger, "RRD: rebuild empty metric list"); return 1; } SPDLOG_LOGGER_INFO( - log_v2::rrd(), - "RRD: Finishing to rebuild metrics ({}) status ({})", + _logger, "RRD: Finishing to rebuild metrics ({}) status ({})", fmt::join(keys_of_map(e->obj().metric_to_index_id()), ","), fmt::join(values_of_map(e->obj().metric_to_index_id()), ",")); // Rebuild is ending. @@ -487,35 +478,35 @@ int output::write(std::shared_ptr const& d) { } break; default: - log_v2::rrd()->error( + _logger->error( "RRD: Bad 'state' value in rebuild message: it can only contain " "START, DATA or END"); break; } } break; case storage::pb_remove_graph_message::static_type(): { - SPDLOG_LOGGER_DEBUG(log_v2::rrd(), "RRD: RemoveGraphsMessage received"); + SPDLOG_LOGGER_DEBUG(_logger, "RRD: RemoveGraphsMessage received"); std::shared_ptr e{ std::static_pointer_cast(d)}; for (auto& m : e->obj().metric_ids()) { std::string path{fmt::format("{}{}.rrd", _metrics_path, m)}; /* File removed */ - SPDLOG_LOGGER_INFO(log_v2::rrd(), "RRD: removing {} file", path); + SPDLOG_LOGGER_INFO(_logger, "RRD: removing {} file", path); _backend.remove(path); } for (auto& i : e->obj().index_ids()) { std::string path{fmt::format("{}{}.rrd", _status_path, i)}; /* File removed */ - SPDLOG_LOGGER_INFO(log_v2::rrd(), "RRD: removing {} file", path); + SPDLOG_LOGGER_INFO(_logger, "RRD: removing {} file", path); _backend.remove(path); } } break; case storage::remove_graph::static_type(): { - SPDLOG_LOGGER_INFO(log_v2::rrd(), "storage::remove_graph"); + SPDLOG_LOGGER_INFO(_logger, "storage::remove_graph"); // Debug message. std::shared_ptr e( std::static_pointer_cast(d)); - SPDLOG_LOGGER_DEBUG(log_v2::rrd(), "RRD: remove graph request for {} {}", + SPDLOG_LOGGER_DEBUG(_logger, "RRD: remove graph request for {} {}", e->is_index ? "index" : "metric", e->id); // Generate path. @@ -532,8 +523,7 @@ int output::write(std::shared_ptr const& d) { _backend.remove(path); } break; default: - log_v2::rrd()->warn("RRD: unknown BBDO message received of type {}", - d->type()); + _logger->warn("RRD: unknown BBDO message received of type {}", d->type()); } return 1; @@ -588,7 +578,7 @@ void output::_rebuild_data(const RebuildMessage& rm) { for (auto& p : rm.timeserie()) { std::deque query; - SPDLOG_LOGGER_DEBUG(log_v2::rrd(), "RRD: Rebuilding metric {}", p.first); + SPDLOG_LOGGER_DEBUG(_logger, "RRD: Rebuilding metric {}", p.first); std::string path{fmt::format("{}{}.rrd", _metrics_path, p.first)}; auto index_id_search = _metrics_to_index_rebuild.find(p.first); uint64_t index_id = 0; @@ -623,8 +613,7 @@ void output::_rebuild_data(const RebuildMessage& rm) { } break; default: - SPDLOG_LOGGER_DEBUG(log_v2::rrd(), - "data_source_type = {} is not managed", + SPDLOG_LOGGER_DEBUG(_logger, "data_source_type = {} is not managed", data_source_type); } @@ -638,7 +627,7 @@ void output::_rebuild_data(const RebuildMessage& rm) { start_time = p.second.pts()[0].ctime() - interval; else start_time = std::time(nullptr) - interval; - SPDLOG_LOGGER_TRACE(log_v2::rrd(), "'{}' start date set to {}", path, + SPDLOG_LOGGER_TRACE(_logger, "'{}' start date set to {}", path, start_time); try { /* Here, the file is opened only if it exists. */ @@ -648,16 +637,16 @@ void output::_rebuild_data(const RebuildMessage& rm) { _backend.open(path, p.second.rrd_retention(), start_time, interval, p.second.data_source_type(), true); } - SPDLOG_LOGGER_TRACE(log_v2::rrd(), "{} points added to file '{}'", - query.size(), path); + SPDLOG_LOGGER_TRACE(_logger, "{} points added to file '{}'", query.size(), + path); _backend.update(query); } else - SPDLOG_LOGGER_TRACE(log_v2::rrd(), "Nothing to rebuild in '{}'", path); + SPDLOG_LOGGER_TRACE(_logger, "Nothing to rebuild in '{}'", path); } for (const auto& by_index_status_values : status_values) { - SPDLOG_LOGGER_DEBUG(log_v2::rrd(), "RRD: Rebuilding status {}", + SPDLOG_LOGGER_DEBUG(_logger, "RRD: Rebuilding status {}", by_index_status_values.first); std::string status_path{ fmt::format("{}{}.rrd", _status_path, by_index_status_values.first)}; @@ -668,21 +657,21 @@ void output::_rebuild_data(const RebuildMessage& rm) { try { /* Here, the file is opened only if it exists. */ _backend.open(status_path); - SPDLOG_LOGGER_TRACE(log_v2::rrd(), "open '{}' start date set to {}", + SPDLOG_LOGGER_TRACE(_logger, "open '{}' start date set to {}", status_path, start_time); } catch (const exceptions::open& b) { /* Here, the file is created. */ _backend.open(status_path, by_index_status_values.second.rrd_retention, start_time, by_index_status_values.second.check_interval, 0, true); - SPDLOG_LOGGER_TRACE(log_v2::rrd(), + SPDLOG_LOGGER_TRACE(_logger, "create '{}' start date set to {} retention set to " "{}, check interval set to {}", status_path, start_time, by_index_status_values.second.rrd_retention, by_index_status_values.second.check_interval); } - SPDLOG_LOGGER_TRACE(log_v2::rrd(), "{} points added to file '{}'", + SPDLOG_LOGGER_TRACE(_logger, "{} points added to file '{}'", by_index_status_values.second.time_to_value.size(), status_path); diff --git a/broker/simu/inc/com/centreon/broker/simu/connector.hh b/broker/simu/inc/com/centreon/broker/simu/connector.hh index 8309733124d..05526226b9a 100644 --- a/broker/simu/inc/com/centreon/broker/simu/connector.hh +++ b/broker/simu/inc/com/centreon/broker/simu/connector.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2017-2018 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2017-2018 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_SIMU_CONNECTOR_HH #define CCB_SIMU_CONNECTOR_HH @@ -45,6 +45,6 @@ class connector : public io::endpoint { }; } // namespace simu -} +} // namespace com::centreon::broker #endif // !CCB_SIMU_CONNECTOR_HH diff --git a/broker/simu/inc/com/centreon/broker/simu/factory.hh b/broker/simu/inc/com/centreon/broker/simu/factory.hh index c58775756f6..6d4176e53b7 100644 --- a/broker/simu/inc/com/centreon/broker/simu/factory.hh +++ b/broker/simu/inc/com/centreon/broker/simu/factory.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2017-2018 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2017-2018 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_SIMU_FACTORY_HH #define CCB_SIMU_FACTORY_HH @@ -45,6 +45,6 @@ class factory : public io::factory { }; } // namespace simu -} +} // namespace com::centreon::broker #endif // !CCB_SIMU_FACTORY_HH diff --git a/broker/simu/inc/com/centreon/broker/simu/luabinding.hh b/broker/simu/inc/com/centreon/broker/simu/luabinding.hh index 4bc310e6449..02aa886f37a 100644 --- a/broker/simu/inc/com/centreon/broker/simu/luabinding.hh +++ b/broker/simu/inc/com/centreon/broker/simu/luabinding.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2018 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2018-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_SIMU_SIMUBINDING_HH #define CCB_SIMU_SIMUBINDING_HH @@ -28,9 +28,8 @@ extern "C" { #include "lualib.h" } -namespace com::centreon::broker { +namespace com::centreon::broker::simu { -namespace simu { /** * @class luabinding luabinding.hh "com/centreon/broker/simu/luabinding.hh" * @brief Class managing exchange with the the lua interpreter. @@ -38,9 +37,12 @@ namespace simu { * Expose an api to simplify exchanges with the Lua interpreter. */ class luabinding { + std::shared_ptr _logger; + public: luabinding(std::string const& lua_script, - std::map const& conf_params); + std::map const& conf_params, + const std::shared_ptr& logger); ~luabinding(); bool read(std::shared_ptr& d); @@ -68,8 +70,6 @@ class luabinding { // Count on events int _total; }; -} // namespace simu - -} +} // namespace com::centreon::broker::simu #endif // !CCB_SIMU_SIMU_HH diff --git a/broker/simu/inc/com/centreon/broker/simu/stream.hh b/broker/simu/inc/com/centreon/broker/simu/stream.hh index 0512da45874..c921c8f55b3 100644 --- a/broker/simu/inc/com/centreon/broker/simu/stream.hh +++ b/broker/simu/inc/com/centreon/broker/simu/stream.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2018 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2018-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_SIMU_STREAM_HH #define CCB_SIMU_STREAM_HH @@ -22,9 +22,7 @@ #include "com/centreon/broker/io/stream.hh" #include "com/centreon/broker/misc/variant.hh" -namespace com::centreon::broker { - -namespace simu { +namespace com::centreon::broker::simu { // Forward declaration. class luabinding; @@ -36,21 +34,23 @@ class luabinding; * Stream events into lua database. */ class stream : public io::stream { + std::shared_ptr _logger; + // Access to the Lua interpreter luabinding* _luabinding; public: stream(std::string const& lua_script, - std::map const& conf_params); + std::map const& conf_params, + const std::shared_ptr& logger); ~stream(); bool read(std::shared_ptr& d, time_t deadline) override; - stream& operator=(stream const& other) = delete; - stream(stream const& other) = delete; + stream& operator=(stream const&) = delete; + stream(stream const&) = delete; int32_t write(std::shared_ptr const& d) override; int32_t stop() override { return 0; } }; -} // namespace simu -} +} // namespace com::centreon::broker::simu #endif // !CCB_SIMU_STREAM_HH diff --git a/broker/simu/src/connector.cc b/broker/simu/src/connector.cc index d524810e33a..22ee66ba51e 100644 --- a/broker/simu/src/connector.cc +++ b/broker/simu/src/connector.cc @@ -1,31 +1,39 @@ /** -* Copyright 2011-2012,2015 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2012,2015 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/simu/connector.hh" +#include "com/centreon/broker/multiplexing/muxer_filter.hh" #include "com/centreon/broker/simu/stream.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::simu; +using com::centreon::common::log_v2::log_v2; /** * Default constructor. */ -connector::connector() : io::endpoint(false, {}) {} +connector::connector() + : io::endpoint( + false, + multiplexing::muxer_filter(multiplexing::muxer_filter::zero_init()), + multiplexing::muxer_filter(multiplexing::muxer_filter::zero_init()) + .add_category(io::local)) {} /** * Copy constructor. @@ -62,5 +70,6 @@ void connector::connect_to( * @return a lua connection object. */ std::shared_ptr connector::open() { - return std::shared_ptr(new stream(_lua_script, _conf_params)); + return std::make_shared(_lua_script, _conf_params, + log_v2::instance().get(log_v2::LUA)); } diff --git a/broker/simu/src/luabinding.cc b/broker/simu/src/luabinding.cc index 3fe248d30f4..0b29503dedc 100644 --- a/broker/simu/src/luabinding.cc +++ b/broker/simu/src/luabinding.cc @@ -1,33 +1,34 @@ /** -* Copyright 2018 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2018 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/simu/luabinding.hh" #include #include "com/centreon/broker/io/events.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/lua/broker_log.hh" #include "com/centreon/broker/lua/broker_utils.hh" #include "com/centreon/broker/mapping/entry.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::simu; +using com::centreon::common::log_v2::log_v2; /** * Constructor. @@ -36,14 +37,15 @@ using namespace com::centreon::broker::simu; * @param[in] conf_params A hash table with user parameters */ luabinding::luabinding(std::string const& lua_script, - std::map const& conf_params) - : _lua_script(lua_script), _total(0) { + std::map const& conf_params, + const std::shared_ptr& logger) + : _lua_script(lua_script), _total(0), _logger(logger) { size_t pos(lua_script.find_last_of('/')); std::string path(lua_script.substr(0, pos)); _L = _load_interpreter(); _update_lua_path(path); - log_v2::lua()->debug("simu: initializing the Lua state machine"); + _logger->debug("simu: initializing the Lua state machine"); _load_script(); _init_script(conf_params); @@ -177,7 +179,7 @@ void luabinding::_init_script( */ bool luabinding::read(std::shared_ptr& data) { bool retval(false); - log_v2::lua()->trace("simu: luabinding::read call"); + _logger->trace("simu: luabinding::read call"); // Total to acknowledge incremented ++_total; @@ -309,7 +311,7 @@ bool luabinding::_parse_event(std::shared_ptr& d) { " whereas it has been registered", map["_type"].as_int()); } else { - log_v2::lua()->info( + _logger->info( "simu: cannot unserialize event of ID {}: event was not registered and " "will therefore be ignored", map["_type"].as_uint()); diff --git a/broker/simu/src/main.cc b/broker/simu/src/main.cc index d2ae98ee8de..25f451805c2 100644 --- a/broker/simu/src/main.cc +++ b/broker/simu/src/main.cc @@ -1,20 +1,20 @@ /** -* Copyright 2011-2013 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2013 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "bbdo/storage/index_mapping.hh" #include "bbdo/storage/metric.hh" @@ -22,11 +22,12 @@ #include "bbdo/storage/status.hh" #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/io/protocols.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/simu/factory.hh" #include "com/centreon/broker/simu/stream.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; +using log_v2 = com::centreon::common::log_v2::log_v2; // Load count. static uint32_t instances{0u}; @@ -68,11 +69,12 @@ bool broker_module_deinit() { void broker_module_init(void const* arg) { (void)arg; + auto logger = log_v2::instance().get(log_v2::LUA); // Increment instance number. if (!instances++) { // generic simu module. - log_v2::core()->info("simu: module for Centreon Broker {}", - CENTREON_BROKER_VERSION); + logger->info("simu: module for Centreon Broker {}", + CENTREON_BROKER_VERSION); io::events& e(io::events::instance()); diff --git a/broker/simu/src/stream.cc b/broker/simu/src/stream.cc index 5cbd156629e..b3e841d301c 100644 --- a/broker/simu/src/stream.cc +++ b/broker/simu/src/stream.cc @@ -1,20 +1,20 @@ /** -* Copyright 2017 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2017 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/simu/stream.hh" #include "com/centreon/broker/exceptions/shutdown.hh" @@ -32,9 +32,10 @@ using namespace com::centreon::broker::simu; * @param[in] port port */ stream::stream(std::string const& lua_script, - std::map const& conf_params) - : io::stream("simu") { - _luabinding = new luabinding(lua_script, conf_params); + std::map const& conf_params, + const std::shared_ptr& logger) + : io::stream("simu"), _logger(logger) { + _luabinding = new luabinding(lua_script, conf_params, _logger); } /** diff --git a/broker/simu/test/simu.cc b/broker/simu/test/simu.cc index 79fe0e17539..59ad7f8ccfa 100644 --- a/broker/simu/test/simu.cc +++ b/broker/simu/test/simu.cc @@ -24,15 +24,21 @@ #include "com/centreon/broker/neb/events.hh" #include "com/centreon/broker/simu/luabinding.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::misc; using namespace com::centreon::broker::simu; +using com::centreon::common::log_v2::log_v2; class SimuGenericTest : public ::testing::Test { + protected: + std::shared_ptr _logger; + public: void SetUp() override { + _logger = log_v2::instance().get(log_v2::LUA); try { config::applier::init(0, "test_broker", 0); } catch (std::exception const& e) { @@ -66,8 +72,9 @@ class SimuGenericTest : public ::testing::Test { // Then an exception is thrown TEST_F(SimuGenericTest, MissingScript) { std::map conf; - ASSERT_THROW(new luabinding("/tmp/this_script_does_not_exist.lua", conf), - msg_fmt); + ASSERT_THROW( + new luabinding("/tmp/this_script_does_not_exist.lua", conf, _logger), + msg_fmt); } // When a lua script with error such as number divided by nil is loaded @@ -78,7 +85,7 @@ TEST_F(SimuGenericTest, FaultyScript) { CreateScript(filename, "local a = { 1, 2, 3 }\n" "local b = 18 / a[4]"); - ASSERT_THROW(new luabinding(filename, conf), msg_fmt); + ASSERT_THROW(new luabinding(filename, conf, _logger), msg_fmt); RemoveFile(filename); } @@ -88,7 +95,7 @@ TEST_F(SimuGenericTest, WithoutInit) { std::map conf; std::string filename("/tmp/without_init.lua"); CreateScript(filename, "local a = { 1, 2, 3 }\n"); - ASSERT_THROW(new luabinding(filename, conf), msg_fmt); + ASSERT_THROW(new luabinding(filename, conf, _logger), msg_fmt); RemoveFile(filename); } @@ -101,7 +108,7 @@ TEST_F(SimuGenericTest, IncompleteScript) { "end\n" "local a = { 1, 2, 3 }\n"); std::map conf; - ASSERT_THROW(new luabinding(filename, conf), msg_fmt); + ASSERT_THROW(new luabinding(filename, conf, _logger), msg_fmt); RemoveFile(filename); } @@ -116,7 +123,7 @@ TEST_F(SimuGenericTest, ReadReturnValue1) { "return 2\n" "end\n"); std::map conf; - std::unique_ptr lb(new luabinding(filename, conf)); + std::unique_ptr lb(new luabinding(filename, conf, _logger)); std::shared_ptr d; ASSERT_THROW(lb->read(d), msg_fmt); RemoveFile(filename); @@ -133,7 +140,7 @@ TEST_F(SimuGenericTest, ReadReturnValue2) { "return nil\n" "end\n"); std::map conf; - std::unique_ptr lb(new luabinding(filename, conf)); + std::unique_ptr lb(new luabinding(filename, conf, _logger)); std::shared_ptr d; ASSERT_FALSE(lb->read(d)); RemoveFile(filename); @@ -152,7 +159,7 @@ TEST_F(SimuGenericTest, ReadReturnValue3) { "return { a='toto' }\n" "end\n"); std::map conf; - std::unique_ptr lb(new luabinding(filename, conf)); + std::unique_ptr lb(new luabinding(filename, conf, _logger)); std::shared_ptr d; ASSERT_FALSE(lb->read(d)); RemoveFile(filename); @@ -178,9 +185,10 @@ TEST_F(SimuGenericTest, ReadReturnValue4) { "}\n" "end\n"); std::map conf; - config::applier::modules modules; + config::applier::modules modules(_logger); modules.load_file("./broker/neb/10-neb.so"); - std::unique_ptr lb = std::make_unique(filename, conf); + std::unique_ptr lb = + std::make_unique(filename, conf, _logger); std::shared_ptr d; ASSERT_TRUE(lb->read(d)); RemoveFile(filename); @@ -214,9 +222,9 @@ TEST_F(SimuGenericTest, ReadReturnCustomVariable) { " default_value=\"centengine\"}\n" "end\n"); std::map conf; - config::applier::modules modules; + config::applier::modules modules(_logger); modules.load_file("./broker/neb/10-neb.so"); - std::unique_ptr lb(new luabinding(filename, conf)); + std::unique_ptr lb(new luabinding(filename, conf, _logger)); std::shared_ptr d; ASSERT_TRUE(lb->read(d)); RemoveFile(filename); diff --git a/broker/sql/inc/com/centreon/broker/sql/cleanup.hh b/broker/sql/inc/com/centreon/broker/sql/cleanup.hh index 57e3c44d517..9d9406983c1 100644 --- a/broker/sql/inc/com/centreon/broker/sql/cleanup.hh +++ b/broker/sql/inc/com/centreon/broker/sql/cleanup.hh @@ -1,25 +1,24 @@ -/* -** Copyright 2014 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2014 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_SQL_CLEANUP_HH #define CCB_SQL_CLEANUP_HH - namespace com::centreon::broker { namespace sql { @@ -67,6 +66,6 @@ class cleanup { }; } // namespace sql -} +} // namespace com::centreon::broker #endif // !CCB_SQL_CLEANUP_HH diff --git a/broker/sql/inc/com/centreon/broker/sql/connector.hh b/broker/sql/inc/com/centreon/broker/sql/connector.hh index e610fd098da..1ef84f9ed16 100644 --- a/broker/sql/inc/com/centreon/broker/sql/connector.hh +++ b/broker/sql/inc/com/centreon/broker/sql/connector.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2011-2012,2015-2021 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2011-2012,2015-2021 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_SQL_CONNECTOR_HH #define CCB_SQL_CONNECTOR_HH @@ -54,6 +54,6 @@ class connector : public io::endpoint { }; } // namespace sql -} +} // namespace com::centreon::broker #endif // !CCB_SQL_CONNECTOR_HH diff --git a/broker/sql/inc/com/centreon/broker/sql/factory.hh b/broker/sql/inc/com/centreon/broker/sql/factory.hh index 7377423fd60..dbeb248411d 100644 --- a/broker/sql/inc/com/centreon/broker/sql/factory.hh +++ b/broker/sql/inc/com/centreon/broker/sql/factory.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2011-2013 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2011-2013 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_SQL_FACTORY_HH #define CCB_SQL_FACTORY_HH @@ -45,6 +45,6 @@ class factory : public io::factory { }; } // namespace sql -} +} // namespace com::centreon::broker #endif // !CCB_SQL_FACTORY_HH diff --git a/broker/sql/inc/com/centreon/broker/sql/stream.hh b/broker/sql/inc/com/centreon/broker/sql/stream.hh index 71330fef971..db6c1fcb5dd 100644 --- a/broker/sql/inc/com/centreon/broker/sql/stream.hh +++ b/broker/sql/inc/com/centreon/broker/sql/stream.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2011-2016 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2011-2016 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_SQL_STREAM_HH #define CCB_SQL_STREAM_HH @@ -51,6 +51,8 @@ class stream : public io::stream { bool _stopped; void _process_log_issue(std::shared_ptr const& e); + std::shared_ptr _logger_sql; + std::shared_ptr _logger_storage; public: stream(database_config const& dbcfg, @@ -70,6 +72,6 @@ class stream : public io::stream { }; } // namespace sql -} +} // namespace com::centreon::broker #endif // !CCB_SQL_STREAM_HH diff --git a/broker/sql/src/connector.cc b/broker/sql/src/connector.cc index 62941d336b2..ac1c19c4209 100644 --- a/broker/sql/src/connector.cc +++ b/broker/sql/src/connector.cc @@ -1,39 +1,37 @@ /** -* Copyright 2011-2012,2015-2021 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2012,2015-2021 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/sql/connector.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/sql/stream.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::sql; -/************************************** - * * - * Public Methods * - * * - **************************************/ - /** * Default constructor. */ -connector::connector() : io::endpoint(false, {}) {} +connector::connector() + : io::endpoint( + false, + multiplexing::muxer_filter(multiplexing::muxer_filter::zero_init()), + multiplexing::muxer_filter(multiplexing::muxer_filter::zero_init())) { +} /** * Set connection parameters. diff --git a/broker/sql/src/factory.cc b/broker/sql/src/factory.cc index 87b6cc45925..de930a65a37 100644 --- a/broker/sql/src/factory.cc +++ b/broker/sql/src/factory.cc @@ -1,31 +1,32 @@ /** -* Copyright 2011-2013,2015 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2013,2015, 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/sql/factory.hh" #include #include "com/centreon/broker/config/parser.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/sql/connector.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::sql; +using com::centreon::common::log_v2::log_v2; /** * Check if an endpoint match a configuration. @@ -66,9 +67,11 @@ io::endpoint* factory::new_endpoint( cfg.params.find("cleanup_check_interval")}; if (it != cfg.params.end() && !absl::SimpleAtoi(it->second, &cleanup_check_interval)) { - log_v2::sql()->error( - "sql: the 'cleanup_check_interval' value must be a positive integer. " - "Otherwise, 0 is used for its value."); + log_v2::instance() + .get(log_v2::CORE) + ->error( + "sql: the 'cleanup_check_interval' value must be a positive " + "integer. Otherwise, 0 is used for its value."); cleanup_check_interval = 0u; } } @@ -79,9 +82,11 @@ io::endpoint* factory::new_endpoint( cfg.params.find("enable_command_cache")); if (it != cfg.params.end() && !absl::SimpleAtob(it->second, &enable_cmd_cache)) { - log_v2::sql()->error( - "sql: the 'enable_command_cache' value must be a boolean. Otherwise " - "'false' is used for its value."); + log_v2::instance() + .get(log_v2::CORE) + ->error( + "sql: the 'enable_command_cache' value must be a boolean. " + "Otherwise 'false' is used for its value."); enable_cmd_cache = false; } } @@ -100,9 +105,11 @@ io::endpoint* factory::new_endpoint( cfg.params.find("instance_timeout")); if (it != cfg.params.end() && !absl::SimpleAtoi(it->second, &instance_timeout)) { - log_v2::sql()->error( - "sql: the 'instance_timeout' value must be a positive integer. " - "Otherwise, 300 is used for its value."); + log_v2::instance() + .get(log_v2::CORE) + ->error( + "sql: the 'instance_timeout' value must be a positive integer. " + "Otherwise, 300 is used for its value."); instance_timeout = 300; } } @@ -114,10 +121,12 @@ io::endpoint* factory::new_endpoint( cfg.params.find("with_state_events")); if (it != cfg.params.end()) { if (!absl::SimpleAtob(it->second, &wse)) { - log_v2::rrd()->error( - "factory: cannot parse the 'with_state_events' boolean: the " - "content is '{}'", - it->second); + log_v2::instance() + .get(log_v2::CORE) + ->error( + "factory: cannot parse the 'with_state_events' boolean: the " + "content is '{}'", + it->second); wse = false; } } diff --git a/broker/sql/src/main.cc b/broker/sql/src/main.cc index 3b26fb44752..7885bb8532f 100644 --- a/broker/sql/src/main.cc +++ b/broker/sql/src/main.cc @@ -1,27 +1,28 @@ /** -* Copyright 2011-2013 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2013 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/io/protocols.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/sql/factory.hh" #include "com/centreon/broker/sql/stream.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; +using log_v2 = com::centreon::common::log_v2::log_v2; // Load count. static uint32_t instances(0); @@ -62,11 +63,11 @@ bool broker_module_deinit() { void broker_module_init(void const* arg) { (void)arg; + auto logger = log_v2::instance().get(log_v2::SQL); // Increment instance number. if (!instances++) { // SQL module. - log_v2::sql()->info("SQL: module for Centreon Broker {}", - CENTREON_BROKER_VERSION); + logger->info("SQL: module for Centreon Broker {}", CENTREON_BROKER_VERSION); // Register SQL layer. io::protocols::instance().reg("SQL", std::make_shared(), 1, diff --git a/broker/sql/src/stream.cc b/broker/sql/src/stream.cc index 196a1d33258..ef761a0309d 100644 --- a/broker/sql/src/stream.cc +++ b/broker/sql/src/stream.cc @@ -20,7 +20,6 @@ #include "com/centreon/broker/exceptions/shutdown.hh" #include "com/centreon/broker/io/events.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/neb/downtime.hh" #include "com/centreon/broker/neb/events.hh" #include "com/centreon/broker/neb/internal.hh" @@ -30,12 +29,14 @@ #include "com/centreon/engine/host.hh" #include "com/centreon/engine/service.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::misc; using namespace com::centreon::broker::sql; using namespace com::centreon::broker::database; +using log_v2 = com::centreon::common::log_v2::log_v2; /** * Process log issue event. @@ -69,17 +70,19 @@ stream::stream(database_config const& dbcfg, // dbcfg.get_name(), // cleanup_check_interval), _pending_events{0}, - _stopped(false) { + _stopped(false), + _logger_sql{log_v2::instance().get(log_v2::SQL)}, + _logger_storage{log_v2::instance().get(log_v2::PERFDATA)} { // FIXME DBR (void)cleanup_check_interval; // // Get oudated instances. // // // Run cleanup thread. // _cleanup_thread.start(); - log_v2::sql()->debug("sql stream instanciation"); + _logger_sql->debug("sql stream instanciation"); if (!storage::conflict_manager::init_sql(dbcfg, loop_timeout, instance_timeout)) { - log_v2::sql()->error("sql stream instanciation failed"); + _logger_sql->error("sql stream instanciation failed"); throw msg_fmt( "SQL: Unable to initialize the sql connection to the database"); } @@ -91,7 +94,9 @@ int32_t stream::stop() { int32_t retval = storage::conflict_manager::instance().unload( storage::conflict_manager::sql); _stopped = true; - log_v2::core()->info("sql stream stopped with {} ackowledged events", retval); + log_v2::instance() + .get(log_v2::CORE) + ->info("sql stream stopped with {} ackowledged events", retval); return retval; } @@ -113,8 +118,8 @@ int stream::flush() { _pending_events -= retval; // Event acknowledgement. - log_v2::sql()->trace("SQL: {} / {} events acknowledged", retval, - _pending_events); + _logger_sql->trace("SQL: {} / {} events acknowledged", retval, + _pending_events); return retval; } @@ -156,8 +161,8 @@ int32_t stream::write(std::shared_ptr const& data) { storage::conflict_manager::sql, data); _pending_events -= ack; // Event acknowledgement. - log_v2::perfdata()->debug("storage: {} / {} events acknowledged", ack, - _pending_events); + _logger_storage->debug("storage: {} / {} events acknowledged", ack, + _pending_events); return ack; } diff --git a/broker/stats/inc/com/centreon/broker/stats/builder.hh b/broker/stats/inc/com/centreon/broker/stats/builder.hh index 6b5dfc7a54b..008ef0539f5 100644 --- a/broker/stats/inc/com/centreon/broker/stats/builder.hh +++ b/broker/stats/inc/com/centreon/broker/stats/builder.hh @@ -1,4 +1,4 @@ -/* +/** * Copyright 2011 - 2019 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -50,6 +50,6 @@ class builder { }; } // namespace stats -} +} // namespace com::centreon::broker #endif // !CCB_STATS_BUILDER_HH diff --git a/broker/stats/inc/com/centreon/broker/stats/parser.hh b/broker/stats/inc/com/centreon/broker/stats/parser.hh index 671c4629c3f..229a90217c7 100644 --- a/broker/stats/inc/com/centreon/broker/stats/parser.hh +++ b/broker/stats/inc/com/centreon/broker/stats/parser.hh @@ -1,4 +1,4 @@ -/* +/** * Copyright 2011 - 2019 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -20,7 +20,6 @@ #ifndef CCB_STATS_PARSER_HH #define CCB_STATS_PARSER_HH - namespace com::centreon::broker { namespace stats { @@ -45,6 +44,6 @@ class parser { }; } // namespace stats -} +} // namespace com::centreon::broker #endif // !CCB_STATS_PARSER_HH diff --git a/broker/stats/src/main.cc b/broker/stats/src/main.cc index d15055b0a81..58048da4383 100644 --- a/broker/stats/src/main.cc +++ b/broker/stats/src/main.cc @@ -18,11 +18,12 @@ */ #include "com/centreon/broker/config/state.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/stats/parser.hh" #include "com/centreon/broker/stats/worker_pool.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; +using log_v2 = com::centreon::common::log_v2::log_v2; // Load count. static uint32_t instances(0); @@ -51,11 +52,12 @@ bool broker_module_deinit() { * @param[in] arg Configuration argument. */ void broker_module_init(void const* arg) { + auto logger = log_v2::instance().get(log_v2::STATS); // Increment instance number. if (!instances++) { // Stats module. - log_v2::sql()->info("stats: module for Centreon Broker {}", - CENTREON_BROKER_VERSION); + logger->info("stats: module for Centreon Broker {}", + CENTREON_BROKER_VERSION); // Check that stats are enabled. config::state const& base_cfg(*static_cast(arg)); @@ -79,14 +81,14 @@ void broker_module_init(void const* arg) { } loaded = true; } catch (std::exception const& e) { - log_v2::stats()->info("stats: engine loading failure: {}", e.what()); + logger->info("stats: engine loading failure: {}", e.what()); } catch (...) { - log_v2::stats()->info("stats: engine loading failure"); + logger->info("stats: engine loading failure"); } } if (!loaded) { wpool.cleanup(); - log_v2::stats()->info( + logger->info( "stats: invalid stats " "configuration, stats engine is NOT loaded"); } diff --git a/broker/stats/src/worker.cc b/broker/stats/src/worker.cc index f9fded36267..ee5a483bfcc 100644 --- a/broker/stats/src/worker.cc +++ b/broker/stats/src/worker.cc @@ -27,12 +27,13 @@ #include #include "com/centreon/broker/config/applier/endpoint.hh" #include "com/centreon/broker/config/applier/modules.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/stats/builder.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker::stats; +using com::centreon::common::log_v2::log_v2; /** * Default constructor. @@ -151,12 +152,12 @@ void worker::_run() { } } } catch (std::exception const& e) { - log_v2::stats()->error( - "stats: FIFO thread will exit due to the following error: {}", - e.what()); + auto logger = log_v2::instance().get(log_v2::STATS); + logger->error("stats: FIFO thread will exit due to the following error: {}", + e.what()); } catch (...) { - log_v2::stats()->error( - "stats: FIFO thread will exit due to an unknown error"); + auto logger = log_v2::instance().get(log_v2::STATS); + logger->error("stats: FIFO thread will exit due to an unknown error"); } ::unlink(_fifo.c_str()); } diff --git a/broker/stats/src/worker_pool.cc b/broker/stats/src/worker_pool.cc index ce7a7fb1574..69539afd66f 100644 --- a/broker/stats/src/worker_pool.cc +++ b/broker/stats/src/worker_pool.cc @@ -18,14 +18,18 @@ */ #include "com/centreon/broker/stats/worker_pool.hh" + #include + #include -#include "com/centreon/broker/log_v2.hh" + #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::stats; +using log_v2 = com::centreon::common::log_v2::log_v2; worker_pool::worker_pool() {} @@ -36,7 +40,9 @@ void worker_pool::add_worker(std::string const& fifo) { // Stat failed, probably because of inexistant file. if (stat(fifo_path.c_str(), &s) != 0) { char const* msg(strerror(errno)); - log_v2::stats()->info("stats: cannot stat() '{}': {}", fifo_path, msg); + log_v2::instance() + .get(log_v2::STATS) + ->info("stats: cannot stat() '{}': {}", fifo_path, msg); // Create FIFO. if (mkfifo(fifo_path.c_str(), diff --git a/broker/stats/test/stats.cc b/broker/stats/test/stats.cc index 3d033e0ee76..3bf822aa645 100644 --- a/broker/stats/test/stats.cc +++ b/broker/stats/test/stats.cc @@ -33,6 +33,7 @@ #include "com/centreon/broker/misc/misc.hh" #include "com/centreon/broker/misc/string.hh" #include "com/centreon/broker/multiplexing/engine.hh" +#include "com/centreon/broker/multiplexing/muxer_filter.hh" #include "com/centreon/broker/sql/mysql_manager.hh" #include "com/centreon/broker/stats/builder.hh" #include "com/centreon/broker/stats/center.hh" @@ -132,7 +133,11 @@ class st : public io::stream { class endp : public io::endpoint { public: - endp() : io::endpoint{false, {}} {} + endp() + : io::endpoint{false, + {}, + multiplexing::muxer_filter( + multiplexing::muxer_filter::zero_init())} {} std::shared_ptr open() override { static int count = 0; if (++count < 2) diff --git a/broker/stats_exporter/inc/com/centreon/broker/stats_exporter/exporter.hh b/broker/stats_exporter/inc/com/centreon/broker/stats_exporter/exporter.hh index 4f591a3723c..a4e3f499541 100644 --- a/broker/stats_exporter/inc/com/centreon/broker/stats_exporter/exporter.hh +++ b/broker/stats_exporter/inc/com/centreon/broker/stats_exporter/exporter.hh @@ -51,6 +51,7 @@ namespace stats_exporter { * instrument_i64s. */ class exporter { + std::shared_ptr _center; /** * @brief Class to work on ObservableGauge with double values. */ @@ -78,7 +79,7 @@ class exporter { void* state) { std::function query = *reinterpret_cast*>(state); - std::lock_guard lck(stats::center::instance()); + std::lock_guard lck(*stats::center::instance_ptr()); auto observer_long = opentelemetry::nostd::get query = *reinterpret_cast*>(state); - std::lock_guard lck(stats::center::instance()); + std::lock_guard lck(*stats::center::instance_ptr()); auto observer_long = opentelemetry::nostd::getinfo( - "stats_exporter: export configured with an interval of {}s and a timeout " - "of {}s", - interval, timeout); + log_v2::instance() + .get(log_v2::CONFIG) + ->info( + "stats_exporter: export configured with an interval of {}s and a " + "timeout of {}s", + interval, timeout); metric_sdk::PeriodicExportingMetricReaderOptions options; options.export_interval_millis = std::chrono::milliseconds(static_cast(1000. * interval)); @@ -76,8 +80,8 @@ void exporter::init_metrics( */ _thread_pool_size = std::make_unique( provider, "thread_pool_size", "Number of threads in the thread pool", - []() -> int64_t { - const auto& s = stats::center::instance().stats().pool_stats(); + [center = _center]() -> int64_t { + const auto& s = center->stats().pool_stats(); return s.size(); }); @@ -85,8 +89,8 @@ void exporter::init_metrics( provider, "thread_pool_latency", "Latency of the thread pool in seconds, the time to wait before a thread " "is available", - []() -> double { - const auto& s = stats::center::instance().stats().pool_stats(); + [center = _center]() -> double { + const auto& s = center->stats().pool_stats(); return s.latency(); }); @@ -98,8 +102,8 @@ void exporter::init_metrics( provider, fmt::format("{}_muxer_total_events", m.name), fmt::format("Total number of events stacked in the muxer '{}'", m.name), - [name = m.name]() -> int64_t { - const auto& s = stats::center::instance().stats(); + [name = m.name, center = _center]() -> int64_t { + const auto& s = center->stats(); return s.processing().muxers().at(name).total_events(); }); @@ -108,8 +112,8 @@ void exporter::init_metrics( fmt::format( "Number of unacknowlkedged events stacked in the muxer '{}'", m.name), - [name = m.name]() -> int64_t { - const auto& s = stats::center::instance().stats(); + [name = m.name, center = _center]() -> int64_t { + const auto& s = center->stats(); return s.processing().muxers().at(name).unacknowledged_events(); }); @@ -117,8 +121,8 @@ void exporter::init_metrics( provider, fmt::format("{}_muxer_queue_file_write_path", m.name), fmt::format("Index of the current written queue file for muxer '{}'", m.name), - [name = m.name]() -> int64_t { - const auto& s = stats::center::instance().stats(); + [name = m.name, center = _center]() -> int64_t { + const auto& s = center->stats(); const auto& q = s.processing().muxers().at(name).queue_file(); return q.file_write_path(); }); @@ -127,8 +131,8 @@ void exporter::init_metrics( provider, fmt::format("{}_muxer_queue_file_read_path", m.name), fmt::format("Index of the current written queue file for muxer '{}'", m.name), - [name = m.name]() -> int64_t { - const auto& s = stats::center::instance().stats(); + [name = m.name, center = _center]() -> int64_t { + const auto& s = center->stats(); const auto& q = s.processing().muxers().at(name).queue_file(); return q.file_read_path(); }); @@ -139,8 +143,8 @@ void exporter::init_metrics( fmt::format("percentage progression of the retention reading of the " "muxer '{}'", m.name), - [name = m.name]() -> double { - const auto& s = stats::center::instance().stats(); + [name = m.name, center = _center]() -> double { + const auto& s = center->stats(); const auto& q = s.processing().muxers().at(name).queue_file(); return q.file_percent_processed(); }); @@ -165,11 +169,12 @@ exporter::~exporter() noexcept { void exporter::_check_connections( std::shared_ptr provider, const boost::system::error_code& ec) { - if (ec) - log_v2::sql()->error( + if (ec) { + auto logger = log_v2::instance().get(log_v2::SQL); + logger->error( "stats_exporter: Sql connections checker has been interrupted: {}", ec.message()); - else { + } else { size_t count = mysql_manager::instance().connections_count(); while (_conn.size() < count) { _conn.push_back({}); @@ -178,8 +183,8 @@ void exporter::_check_connections( ci.waiting_tasks = std::make_unique( provider, fmt::format("sql_connection_{}_waiting_tasks", id), fmt::format("Number of waiting tasks on the connection {}", id), - [id]() -> int64_t { - const auto& s = stats::center::instance().stats(); + [id, center = _center]() -> int64_t { + const auto& s = center->stats(); if (id < s.sql_manager().connections().size()) return s.sql_manager().connections().at(id).waiting_tasks(); else @@ -191,8 +196,8 @@ void exporter::_check_connections( fmt::format( "Average duration in seconds of one loop on the connection {}", id), - [id]() -> double { - const auto& s = stats::center::instance().stats(); + [id, center = _center]() -> double { + const auto& s = center->stats(); if (id < s.sql_manager().connections().size()) return s.sql_manager() .connections() @@ -206,8 +211,8 @@ void exporter::_check_connections( provider, fmt::format("sql_connection_{}_average_tasks_count", id), fmt::format("Average number of waiting tasks on the connection {}", id), - [id]() -> double { - const auto& s = stats::center::instance().stats(); + [id, center = _center]() -> double { + const auto& s = center->stats(); if (id < s.sql_manager().connections().size()) return s.sql_manager().connections().at(id).average_tasks_count(); else @@ -219,8 +224,8 @@ void exporter::_check_connections( fmt::format("Average activity in percent on the connection {} (work " "duration / total duration)", id), - [id]() -> double { - const auto& s = stats::center::instance().stats(); + [id, center = _center]() -> double { + const auto& s = center->stats(); if (id < s.sql_manager().connections().size()) return s.sql_manager().connections().at(id).activity_percent(); else @@ -232,8 +237,8 @@ void exporter::_check_connections( fmt::format("Average activity in percent on the connection {} (work " "duration / total duration)", id), - [id]() -> double { - const auto& s = stats::center::instance().stats(); + [id, center = _center]() -> double { + const auto& s = center->stats(); if (id < s.sql_manager().connections().size()) return s.sql_manager() .connections() @@ -249,8 +254,8 @@ void exporter::_check_connections( fmt::format("Average activity in percent on the connection {} (work " "duration / total duration)", id), - [id]() -> double { - const auto& s = stats::center::instance().stats(); + [id, center = _center]() -> double { + const auto& s = center->stats(); if (id < s.sql_manager().connections().size()) return s.sql_manager() .connections() diff --git a/broker/stats_exporter/src/main.cc b/broker/stats_exporter/src/main.cc index f5c9f8c2090..d7427e0b97c 100644 --- a/broker/stats_exporter/src/main.cc +++ b/broker/stats_exporter/src/main.cc @@ -22,9 +22,10 @@ #include #include #include +#include "common/log_v2/log_v2.hh" #include "com/centreon/broker/config/state.hh" -#include "com/centreon/broker/log_v2.hh" + #include "com/centreon/broker/stats_exporter/exporter_grpc.hh" #include "com/centreon/broker/stats_exporter/exporter_http.hh" @@ -32,6 +33,7 @@ namespace metric_sdk = opentelemetry::sdk::metrics; namespace metrics_api = opentelemetry::metrics; using namespace com::centreon::broker; +using com::centreon::common::log_v2::log_v2; // Load count. static uint32_t instances = 0; @@ -60,23 +62,24 @@ const char* const* broker_module_parents() { * @param[in] arg Configuration argument. */ void broker_module_init(const void* arg) { + auto logger = log_v2::instance().get(log_v2::STATS); // Increment instance number. if (!instances++) { const config::state* s = static_cast(arg); const auto& conf = s->get_stats_exporter(); const auto& exporters = conf.exporters; // Stats module. - log_v2::config()->info("stats_exporter: module for Centreon Broker {}", - CENTREON_BROKER_VERSION); + logger->info("stats_exporter: module for Centreon Broker {}", + CENTREON_BROKER_VERSION); for (const auto& e : exporters) { switch (e.protocol) { case config::state::stats_exporter::HTTP: - log_v2::config()->info("stats_exporter: with exporter 'HTTP'"); + logger->info("stats_exporter: with exporter 'HTTP'"); expt = std::make_unique(e.url, *s); break; case config::state::stats_exporter::GRPC: - log_v2::config()->info("stats_exporter: with exporter 'GRPC'"); + logger->info("stats_exporter: with exporter 'GRPC'"); expt = std::make_unique(e.url, *s); break; } diff --git a/broker/storage/inc/com/centreon/broker/storage/conflict_manager.hh b/broker/storage/inc/com/centreon/broker/storage/conflict_manager.hh index 1c06d7e2eb8..2a71612cc93 100644 --- a/broker/storage/inc/com/centreon/broker/storage/conflict_manager.hh +++ b/broker/storage/inc/com/centreon/broker/storage/conflict_manager.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2019-2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2019-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_SQL_CONFLICT_MANAGER_HH #define CCB_SQL_CONFLICT_MANAGER_HH @@ -179,6 +179,7 @@ class conflict_manager { std::thread _thread; /* Stats */ + std::shared_ptr _center; ConflictManagerStats* _stats; std::mutex _stat_m; int32_t _events_handled = 0; @@ -236,6 +237,8 @@ class conflict_manager { timestamp _oldest_timestamp; std::unordered_map _stored_timestamps; + std::shared_ptr _logger_sql; + std::shared_ptr _logger_storage; database::mysql_stmt _acknowledgement_insupdate; database::mysql_stmt _comment_insupdate; @@ -370,7 +373,7 @@ class conflict_manager { uint32_t interval_length, const database_config& dbcfg); static conflict_manager& instance(); - int32_t unload(stream_type type); + static int32_t unload(stream_type type); nlohmann::json get_statistics(); int32_t send_event(stream_type c, std::shared_ptr const& e); @@ -380,8 +383,9 @@ class conflict_manager { std::string const& metric_name, short metric_type); void remove_graphs(const std::shared_ptr& d); + void process_stop(const std::shared_ptr& d); }; } // namespace storage -} +} // namespace com::centreon::broker #endif /* !CCB_SQL_CONFLICT_MANAGER_HH */ diff --git a/broker/storage/inc/com/centreon/broker/storage/connector.hh b/broker/storage/inc/com/centreon/broker/storage/connector.hh index 18c581bb0d8..f23944f64ef 100644 --- a/broker/storage/inc/com/centreon/broker/storage/connector.hh +++ b/broker/storage/inc/com/centreon/broker/storage/connector.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2011-2013,2017 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2011-2013,2017 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_STORAGE_CONNECTOR_HH #define CCB_STORAGE_CONNECTOR_HH @@ -51,6 +51,6 @@ class connector : public io::endpoint { }; } // namespace storage -} +} // namespace com::centreon::broker #endif // !CCB_STORAGE_CONNECTOR_HH diff --git a/broker/storage/inc/com/centreon/broker/storage/factory.hh b/broker/storage/inc/com/centreon/broker/storage/factory.hh index 30bd9da1387..2dd9f4161b3 100644 --- a/broker/storage/inc/com/centreon/broker/storage/factory.hh +++ b/broker/storage/inc/com/centreon/broker/storage/factory.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2011-2013 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2011-2013 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_STORAGE_FACTORY_HH #define CCB_STORAGE_FACTORY_HH @@ -44,6 +44,6 @@ class factory : public io::factory { }; } // namespace storage -} +} // namespace com::centreon::broker #endif // !CCB_STORAGE_FACTORY_HH diff --git a/broker/storage/inc/com/centreon/broker/storage/internal.hh b/broker/storage/inc/com/centreon/broker/storage/internal.hh index 32752b3c8d1..32042880ee0 100644 --- a/broker/storage/inc/com/centreon/broker/storage/internal.hh +++ b/broker/storage/inc/com/centreon/broker/storage/internal.hh @@ -1,24 +1,25 @@ -/* -** Copyright 2021 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2021 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_STORAGE_INTERNAL_HH #define CCB_STORAGE_INTERNAL_HH +#include "bbdo/bbdo.pb.h" #include "bbdo/events.hh" #include "bbdo/rebuild_message.pb.h" #include "bbdo/remove_graph_message.pb.h" @@ -37,6 +38,10 @@ using pb_remove_graphs = io::protobuf; } // namespace bbdo +namespace local { +using pb_stop = io::protobuf; +} // namespace local + namespace storage { /** * Here is the declaration of the message sent by unified_sql to rrd to rebuild @@ -48,6 +53,6 @@ using pb_remove_graph_message = io::protobuf; } // namespace storage -} +} // namespace com::centreon::broker #endif // !CCB_STORAGE_INTERNAL_HH diff --git a/broker/storage/inc/com/centreon/broker/storage/rebuilder.hh b/broker/storage/inc/com/centreon/broker/storage/rebuilder.hh index 5a54d160fe9..8ad3ba690ac 100644 --- a/broker/storage/inc/com/centreon/broker/storage/rebuilder.hh +++ b/broker/storage/inc/com/centreon/broker/storage/rebuilder.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2012-2015,2017-2021 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2012-2015,2017-2021 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_STORAGE_REBUILDER_HH #define CCB_STORAGE_REBUILDER_HH @@ -49,6 +49,7 @@ class rebuilder { std::shared_ptr _connection; uint32_t _interval_length; uint32_t _rrd_len; + std::shared_ptr _logger; // Local types. struct metric_info { diff --git a/broker/storage/inc/com/centreon/broker/storage/stored_timestamp.hh b/broker/storage/inc/com/centreon/broker/storage/stored_timestamp.hh index 4c9791b487b..83070ab9720 100644 --- a/broker/storage/inc/com/centreon/broker/storage/stored_timestamp.hh +++ b/broker/storage/inc/com/centreon/broker/storage/stored_timestamp.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2014 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2014 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_SQL_STORED_TIMESTAMP_HH #define CCB_SQL_STORED_TIMESTAMP_HH @@ -59,6 +59,6 @@ class stored_timestamp { }; } // namespace storage -} +} // namespace com::centreon::broker #endif //! CCB_SQL_STORED_TIMESTAMP_HH diff --git a/broker/storage/inc/com/centreon/broker/storage/stream.hh b/broker/storage/inc/com/centreon/broker/storage/stream.hh index 73eff70f171..f005ddb79ba 100644 --- a/broker/storage/inc/com/centreon/broker/storage/stream.hh +++ b/broker/storage/inc/com/centreon/broker/storage/stream.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2011-2021 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2011-2021 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_STORAGE_STREAM_HH #define CCB_STORAGE_STREAM_HH @@ -36,6 +36,10 @@ namespace storage { * metrics table of a centstorage DB. */ class stream : public io::stream { + int32_t _pending_events; + bool _stopped; + std::shared_ptr _logger_sql; + std::shared_ptr _logger_storage; struct index_info { std::string host_name; uint32_t index_id; @@ -66,10 +70,9 @@ class stream : public io::stream { double value; }; - int32_t _pending_events; std::string _status; mutable std::mutex _statusm; - bool _stopped; + std::shared_ptr _logger; void _update_status(std::string const& status); @@ -89,6 +92,6 @@ class stream : public io::stream { }; } // namespace storage -} +} // namespace com::centreon::broker #endif // !CCB_STORAGE_STREAM_HH diff --git a/broker/storage/src/conflict_manager.cc b/broker/storage/src/conflict_manager.cc index 82a5f7dca58..7b66949af06 100644 --- a/broker/storage/src/conflict_manager.cc +++ b/broker/storage/src/conflict_manager.cc @@ -22,18 +22,19 @@ #include "bbdo/events.hh" #include "bbdo/storage/index_mapping.hh" #include "com/centreon/broker/config/applier/init.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/perfdata.hh" #include "com/centreon/broker/multiplexing/publisher.hh" #include "com/centreon/broker/neb/events.hh" #include "com/centreon/broker/sql/mysql_result.hh" #include "com/centreon/broker/storage/internal.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::database; using namespace com::centreon::broker::storage; +using log_v2 = com::centreon::common::log_v2::log_v2; const std::array conflict_manager::metric_type_name{ "GAUGE", "COUNTER", "DERIVE", "ABSOLUTE", "AUTOMATIC"}; @@ -97,20 +98,22 @@ conflict_manager::conflict_manager(database_config const& dbcfg, _max_pending_queries(dbcfg.get_queries_per_transaction()), _mysql{dbcfg}, _instance_timeout{instance_timeout}, - _stats{stats::center::instance().register_conflict_manager()}, + _center{stats::center::instance_ptr()}, + _stats{_center->register_conflict_manager()}, _ref_count{0}, _group_clean_timer{com::centreon::common::pool::io_context()}, - _oldest_timestamp{std::numeric_limits::max()} { - log_v2::sql()->debug("conflict_manager: class instanciation"); - stats::center::instance().update(&ConflictManagerStats::set_loop_timeout, - _stats, _loop_timeout); - stats::center::instance().update( - &ConflictManagerStats::set_max_pending_events, _stats, - _max_pending_queries); + _oldest_timestamp{std::numeric_limits::max()}, + _logger_sql{log_v2::instance().get(log_v2::SQL)}, + _logger_storage{log_v2::instance().get(log_v2::PERFDATA)} { + _logger_sql->debug("conflict_manager: class instanciation"); + _center->update(&ConflictManagerStats::set_loop_timeout, _stats, + _loop_timeout); + _center->update(&ConflictManagerStats::set_max_pending_events, _stats, + _max_pending_queries); } conflict_manager::~conflict_manager() { - log_v2::sql()->debug("conflict_manager: destruction"); + _logger_sql->debug("conflict_manager: destruction"); std::lock_guard l(_group_clean_timer_m); _group_clean_timer.cancel(); } @@ -132,7 +135,9 @@ bool conflict_manager::init_storage(bool store_in_db, uint32_t rrd_len, uint32_t interval_length, const database_config& dbcfg) { - log_v2::sql()->debug("conflict_manager: storage stream initialization"); + log_v2::instance() + .get(log_v2::CORE) + ->debug("conflict_manager: storage stream initialization"); int count; std::unique_lock lk(_init_m); @@ -145,13 +150,18 @@ bool conflict_manager::init_storage(bool store_in_db, })) { if (_state == finished || config::applier::mode == config::applier::finished) { - log_v2::sql()->info("Conflict manager not started because cbd stopped"); + log_v2::instance() + .get(log_v2::CORE) + ->info("Conflict manager not started because cbd stopped"); return false; } if (_singleton->_mysql.get_config() != dbcfg) { - log_v2::sql()->error( - "Conflict manager: storage and sql streams do not have the same " - "database configuration"); + log_v2::instance() + .get(log_v2::CORE) + ->error( + "Conflict manager: storage and sql streams do not have the " + "same " + "database configuration"); return false; } std::lock_guard lck(_singleton->_loop_m); @@ -169,17 +179,22 @@ bool conflict_manager::init_storage(bool store_in_db, _singleton->_thread = std::thread(&conflict_manager::_callback, _singleton); pthread_setname_np(_singleton->_thread.native_handle(), "conflict_mngr"); - log_v2::sql()->info("Conflict manager running"); + log_v2::instance().get(log_v2::CORE)->info("Conflict manager running"); return true; } - log_v2::sql()->info( - "conflict_manager: Waiting for the sql stream initialization for {} " - "seconds", - count); + log_v2::instance() + .get(log_v2::CORE) + ->info( + "conflict_manager: Waiting for the sql stream initialization for " + "{} " + "seconds", + count); } - log_v2::sql()->error( - "conflict_manager: not initialized after 60s. Probably " - "an issue in the sql output configuration."); + log_v2::instance() + .get(log_v2::CORE) + ->error( + "conflict_manager: not initialized after 60s. Probably " + "an issue in the sql output configuration."); return false; } @@ -201,7 +216,9 @@ bool conflict_manager::init_storage(bool store_in_db, bool conflict_manager::init_sql(database_config const& dbcfg, uint32_t loop_timeout, uint32_t instance_timeout) { - log_v2::sql()->debug("conflict_manager: sql stream initialization"); + log_v2::instance() + .get(log_v2::CORE) + ->debug("conflict_manager: sql stream initialization"); std::lock_guard lk(_init_m); _singleton = new conflict_manager(dbcfg, loop_timeout, instance_timeout); if (!_singleton) { @@ -341,7 +358,7 @@ void conflict_manager::_load_caches() { .special = res.value_as_u32(6) == 2}; uint32_t host_id(res.value_as_u32(1)); uint32_t service_id(res.value_as_u32(2)); - log_v2::perfdata()->debug( + _logger_storage->debug( "storage: loaded index {} of ({}, {}) with rrd_len={}", info.index_id, host_id, service_id, info.rrd_retention); _index_cache[{host_id, service_id}] = std::move(info); @@ -442,7 +459,7 @@ void conflict_manager::update_metric_info_cache(uint64_t index_id, short metric_type) { auto it = _metric_cache.find({index_id, metric_name}); if (it != _metric_cache.end()) { - log_v2::perfdata()->info( + _logger_storage->info( "conflict_manager: updating metric '{}' of id {} at index {} to " "metric_type {}", metric_name, metric_id, index_id, metric_type_name[metric_type]); @@ -466,7 +483,7 @@ void conflict_manager::_callback() { try { _load_caches(); } catch (std::exception const& e) { - log_v2::sql()->error("error while loading caches: {}", e.what()); + _logger_sql->error("error while loading caches: {}", e.what()); _broken = true; } @@ -494,7 +511,7 @@ void conflict_manager::_callback() { /* Time to send logs to database */ _insert_logs(); - log_v2::sql()->trace( + _logger_sql->trace( "conflict_manager: main loop initialized with a timeout of {} " "seconds.", _loop_timeout); @@ -508,7 +525,7 @@ void conflict_manager::_callback() { _check_deleted_index(); time_to_deleted_index += std::chrono::minutes(5); } catch (std::exception const& e) { - log_v2::sql()->error( + _logger_sql->error( "conflict_manager: error while checking deleted indexes: {}", e.what()); _broken = true; @@ -618,8 +635,8 @@ void conflict_manager::_callback() { if (fn) (this->*fn)(tpl); else { - log_v2::sql()->warn("SQL: no function defined for event {}:{}", - cat, elem); + _logger_sql->warn("SQL: no function defined for event {}:{}", + cat, elem); *std::get<2>(tpl) = true; } } else if (std::get<1>(tpl) == storage && cat == io::neb && @@ -633,8 +650,13 @@ void conflict_manager::_callback() { type == make_type(io::bbdo, bbdo::de_remove_graphs)) { remove_graphs(d); *std::get<2>(tpl) = true; + } else if (std::get<1>(tpl) == sql && + type == make_type(io::local, local::de_pb_stop)) { + _logger_sql->info("poller stopped..."); + process_stop(d); + *std::get<2>(tpl) = true; } else { - log_v2::sql()->trace( + _logger_sql->trace( "conflict_manager: event of type {} from channel '{}' thrown " "away ; no need to " "store it in the database.", @@ -674,20 +696,20 @@ void conflict_manager::_callback() { { std::lock_guard lk(_stat_m); _speed = s / _stats_count.size(); - stats::center::instance().execute( + _center->execute( [s = this->_stats, spd = _speed] { s->set_speed(spd); }); } } } } - log_v2::sql()->debug("{} new events to treat", count); + _logger_sql->debug("{} new events to treat", count); /* Here, just before looping, we commit. */ _finish_actions(); if (_fifo.get_pending_elements() == 0) - log_v2::sql()->debug( + _logger_sql->debug( "conflict_manager: acknowledgement - no pending events"); else - log_v2::sql()->debug( + _logger_sql->debug( "conflict_manager: acknowledgement - still {} not acknowledged", _fifo.get_pending_elements()); @@ -700,8 +722,8 @@ void conflict_manager::_callback() { _fifo.get_timeline(storage).size()); } } catch (std::exception const& e) { - log_v2::sql()->error("conflict_manager: error in the main loop: {}", - e.what()); + _logger_sql->error("conflict_manager: error in the main loop: {}", + e.what()); if (strstr(e.what(), "server has gone away")) { // The case where we must restart the connector. _broken = true; @@ -712,7 +734,7 @@ void conflict_manager::_callback() { if (_broken) { std::unique_lock lk(_loop_m); /* Let's wait for the end */ - log_v2::sql()->info( + _logger_sql->info( "conflict_manager: waiting for the end of the conflict manager main " "loop."); _loop_cv.wait(lk, [this]() { return !_exit; }); @@ -748,7 +770,7 @@ int32_t conflict_manager::send_event(conflict_manager::stream_type c, if (_broken) throw msg_fmt("conflict_manager: events loop interrupted"); - log_v2::sql()->trace( + _logger_sql->trace( "conflict_manager: send_event category:{}, element:{} from {}", e->type() >> 16, e->type() & 0xffff, c == 0 ? "sql" : "storage"); @@ -803,15 +825,15 @@ void conflict_manager::_finish_action(int32_t conn, uint32_t action) { * events. */ void conflict_manager::_finish_actions() { - log_v2::sql()->trace("conflict_manager: finish actions"); + _logger_sql->trace("conflict_manager: finish actions"); _mysql.commit(); std::fill(_action.begin(), _action.end(), actions::none); _fifo.clean(sql); _fifo.clean(storage); - log_v2::sql()->debug("conflict_manager: still {} not acknowledged", - _fifo.get_pending_elements()); + _logger_sql->debug("conflict_manager: still {} not acknowledged", + _fifo.get_pending_elements()); } /** @@ -855,7 +877,7 @@ void conflict_manager::_update_stats(const std::uint32_t size, const std::size_t ev_size, const std::size_t sql_size, const std::size_t stor_size) noexcept { - stats::center::instance().execute( + _center->execute( [s = this->_stats, size, mpdq, ev_size, sql_size, stor_size] { s->set_events_handled(size); s->set_max_perfdata_events(mpdq); @@ -891,29 +913,29 @@ nlohmann::json conflict_manager::get_statistics() { * @brief Delete the conflict_manager singleton. */ int32_t conflict_manager::unload(stream_type type) { + auto logger = _singleton->_logger_sql; if (!_singleton) { - log_v2::sql()->info("conflict_manager: already unloaded."); + logger->info("conflict_manager: already unloaded."); return 0; } else { uint32_t count = --_singleton->_ref_count; int retval; if (count == 0) { - __exit(); - retval = _fifo.get_acks(type); + _singleton->__exit(); + retval = _singleton->_fifo.get_acks(type); { - std::lock_guard lck(_init_m); + std::lock_guard lck(_singleton->_init_m); _state = finished; delete _singleton; _singleton = nullptr; } - log_v2::sql()->info( - "conflict_manager: no more user of the conflict manager."); + logger->info("conflict_manager: no more user of the conflict manager."); } else { - log_v2::sql()->info( + logger->info( "conflict_manager: still {} stream{} using the conflict manager.", count, count > 1 ? "s" : ""); - retval = _fifo.get_acks(type); - log_v2::sql()->info( + retval = _singleton->_fifo.get_acks(type); + logger->info( "conflict_manager: still {} events handled but not acknowledged.", retval); } @@ -921,6 +943,42 @@ int32_t conflict_manager::unload(stream_type type) { } } +/** + * @brief Function called when a poller is disconnected from Broker. It cleans + * hosts/services and instances in the storage database. + * + * @param d A pb_stop event with the instance ID. + */ +void conflict_manager::process_stop(const std::shared_ptr& d) { + auto& stop = static_cast(d.get())->obj(); + int32_t conn = _mysql.choose_connection_by_instance(stop.poller_id()); + _finish_action(-1, actions::hosts | actions::acknowledgements | + actions::modules | actions::downtimes | + actions::comments | actions::servicegroups | + actions::hostgroups | actions::service_dependencies | + actions::host_dependencies); + + // Log message. + _logger_sql->info("SQL: Disabling poller (id: {}, running: no)", + stop.poller_id()); + + // Clean tables. + _clean_tables(stop.poller_id()); + + // Processing. + if (_is_valid_poller(stop.poller_id())) { + // Prepare queries. + if (!_instance_insupdate.prepared()) { + std::string query(fmt::format( + "UPDATE instances SET end_time={}, running=0 WHERE instance_id={}", + time(nullptr), stop.poller_id())); + _mysql.run_query(query, database::mysql_error::clean_hosts_services, + conn); + _add_action(conn, actions::instances); + } + } +} + /** * @brief process a remove graphs message. * @@ -979,7 +1037,7 @@ void conflict_manager::remove_graphs(const std::shared_ptr& d) { } } } catch (const std::exception& e) { - log_v2::sql()->error( + _logger_sql->error( "could not query index / metrics table(s) to get index to delete: " "{} ", e.what()); @@ -987,14 +1045,14 @@ void conflict_manager::remove_graphs(const std::shared_ptr& d) { std::string mids_str{fmt::format("{}", fmt::join(metrics_to_delete, ","))}; if (!metrics_to_delete.empty()) { - log_v2::sql()->info("metrics {} erased from database", mids_str); + _logger_sql->info("metrics {} erased from database", mids_str); ms.run_query( fmt::format("DELETE FROM metrics WHERE metric_id in ({})", mids_str), database::mysql_error::delete_metric); } std::string ids_str{fmt::format("{}", fmt::join(indexes_to_delete, ","))}; if (!indexes_to_delete.empty()) { - log_v2::sql()->info("indexes {} erased from database", ids_str); + _logger_sql->info("indexes {} erased from database", ids_str); ms.run_query( fmt::format("DELETE FROM index_data WHERE id in ({})", ids_str), database::mysql_error::delete_index); @@ -1008,7 +1066,7 @@ void conflict_manager::remove_graphs(const std::shared_ptr& d) { rmg->mut_obj().add_index_ids(i); multiplexing::publisher().write(rmg); } else - log_v2::sql()->info( + _logger_sql->info( "metrics {} and indexes {} do not appear in the storage database", fmt::join(ids.obj().metric_ids(), ","), fmt::join(ids.obj().index_ids(), ",")); diff --git a/broker/storage/src/conflict_manager_sql.cc b/broker/storage/src/conflict_manager_sql.cc index d9827215fc9..faafa601c0f 100644 --- a/broker/storage/src/conflict_manager_sql.cc +++ b/broker/storage/src/conflict_manager_sql.cc @@ -17,7 +17,6 @@ */ #include -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/string.hh" #include "com/centreon/broker/neb/events.hh" #include "com/centreon/broker/sql/mysql_result.hh" @@ -50,7 +49,7 @@ void conflict_manager::_clean_tables(uint32_t instance_id) { _finish_action(-1, -1); int32_t conn = _mysql.choose_connection_by_instance(instance_id); - log_v2::sql()->debug( + _logger_sql->debug( "conflict_manager: disable hosts and services (instance_id: {})", instance_id); /* Disable hosts and services. */ @@ -62,7 +61,7 @@ void conflict_manager::_clean_tables(uint32_t instance_id) { _add_action(conn, actions::hosts); /* Remove host group memberships. */ - log_v2::sql()->debug( + _logger_sql->debug( "conflict_manager: remove host group memberships (instance_id: {})", instance_id); query = fmt::format( @@ -73,7 +72,7 @@ void conflict_manager::_clean_tables(uint32_t instance_id) { _add_action(conn, actions::hostgroups); /* Remove service group memberships */ - log_v2::sql()->debug( + _logger_sql->debug( "conflict_manager: remove service group memberships (instance_id: {})", instance_id); query = fmt::format( @@ -86,7 +85,7 @@ void conflict_manager::_clean_tables(uint32_t instance_id) { _add_action(conn, actions::servicegroups); /* Remove host dependencies. */ - log_v2::sql()->debug( + _logger_sql->debug( "conflict_manager: remove host dependencies (instance_id: {})", instance_id); query = fmt::format( @@ -98,8 +97,8 @@ void conflict_manager::_clean_tables(uint32_t instance_id) { _add_action(conn, actions::host_dependencies); /* Remove host parents. */ - log_v2::sql()->debug( - "conflict_manager: remove host parents (instance_id: {})", instance_id); + _logger_sql->debug("conflict_manager: remove host parents (instance_id: {})", + instance_id); query = fmt::format( "DELETE hhp FROM hosts_hosts_parents AS hhp INNER JOIN hosts as h ON " "hhp.child_id=h.host_id OR hhp.parent_id=h.host_id WHERE " @@ -109,7 +108,7 @@ void conflict_manager::_clean_tables(uint32_t instance_id) { _add_action(conn, actions::host_parents); /* Remove service dependencies. */ - log_v2::sql()->debug( + _logger_sql->debug( "conflict_manager: remove service dependencies (instance_id: {})", instance_id); query = fmt::format( @@ -126,15 +125,15 @@ void conflict_manager::_clean_tables(uint32_t instance_id) { _add_action(conn, actions::service_dependencies); /* Remove list of modules. */ - log_v2::sql()->debug("SQL: remove list of modules (instance_id: {})", - instance_id); + _logger_sql->debug("SQL: remove list of modules (instance_id: {})", + instance_id); query = fmt::format("DELETE FROM modules WHERE instance_id={}", instance_id); _mysql.run_query(query, database::mysql_error::clean_modules, conn); _add_action(conn, actions::modules); // Cancellation of downtimes. - log_v2::sql()->debug("SQL: Cancellation of downtimes (instance_id: {})", - instance_id); + _logger_sql->debug("SQL: Cancellation of downtimes (instance_id: {})", + instance_id); query = fmt::format( "UPDATE downtimes SET cancelled=1 WHERE actual_end_time IS NULL AND " "cancelled=0 " @@ -145,8 +144,8 @@ void conflict_manager::_clean_tables(uint32_t instance_id) { _add_action(conn, actions::downtimes); // Remove comments. - log_v2::sql()->debug("conflict_manager: remove comments (instance_id: {})", - instance_id); + _logger_sql->debug("conflict_manager: remove comments (instance_id: {})", + instance_id); query = fmt::format( "UPDATE comments SET deletion_time={} WHERE instance_id={} AND " @@ -159,8 +158,8 @@ void conflict_manager::_clean_tables(uint32_t instance_id) { // Remove custom variables. No need to choose the good instance, there are // no constraint between custom variables and instances. - log_v2::sql()->debug("Removing custom variables (instance_id: {})", - instance_id); + _logger_sql->debug("Removing custom variables (instance_id: {})", + instance_id); query = fmt::format( "DELETE cv FROM customvariables AS cv INNER JOIN hosts AS h ON " "cv.host_id = h.host_id WHERE h.instance_id={}", @@ -182,7 +181,7 @@ void conflict_manager::_clean_tables(uint32_t instance_id) { void conflict_manager::_clean_group_table() { int32_t conn = _mysql.choose_best_connection(-1); /* Remove host groups. */ - log_v2::sql()->debug("conflict_manager: remove empty host groups "); + _logger_sql->debug("conflict_manager: remove empty host groups "); _mysql.run_query( "DELETE hg FROM hostgroups AS hg LEFT JOIN hosts_hostgroups AS hhg ON " "hg.hostgroup_id=hhg.hostgroup_id WHERE hhg.hostgroup_id IS NULL", @@ -190,7 +189,7 @@ void conflict_manager::_clean_group_table() { _add_action(conn, actions::hostgroups); /* Remove service groups. */ - log_v2::sql()->debug("conflict_manager: remove empty service groups"); + _logger_sql->debug("conflict_manager: remove empty service groups"); _mysql.run_query( "DELETE sg FROM servicegroups AS sg LEFT JOIN services_servicegroups as " @@ -204,7 +203,7 @@ void conflict_manager::_clean_group_table() { * Update all the hosts and services of unresponsive instances. */ void conflict_manager::_update_hosts_and_services_of_unresponsive_instances() { - log_v2::sql()->debug("conflict_manager: checking for outdated instances"); + _logger_sql->debug("conflict_manager: checking for outdated instances"); /* Don't do anything if timeout is deactivated. */ if (_instance_timeout == 0) @@ -318,7 +317,7 @@ bool conflict_manager::_is_valid_poller(uint32_t instance_id) { bool deleted = false; if (_cache_deleted_instance_id.find(instance_id) != _cache_deleted_instance_id.end()) { - log_v2::sql()->info( + _logger_sql->info( "conflict_manager: discarding some event related to a deleted poller " "({})", instance_id); @@ -363,7 +362,7 @@ void conflict_manager::_process_acknowledgement( *static_cast(d.get()); // Log message. - log_v2::sql()->info( + _logger_sql->info( "processing acknowledgement event (poller: {}, host: {}, service: {}, " "entry time: {}, deletion time: {})", ack.poller_id, ack.host_id, ack.service_id, ack.entry_time, @@ -410,8 +409,8 @@ void conflict_manager::_process_comment( int32_t conn = _mysql.choose_connection_by_instance(cmmnt.poller_id); // Log message. - log_v2::sql()->info("SQL: processing comment of poller {} on ({}, {})", - cmmnt.poller_id, cmmnt.host_id, cmmnt.service_id); + _logger_sql->info("SQL: processing comment of poller {} on ({}, {})", + cmmnt.poller_id, cmmnt.host_id, cmmnt.service_id); // Prepare queries. if (!_comment_insupdate.prepared()) { @@ -479,8 +478,8 @@ void conflict_manager::_process_custom_variable( int conn = special_conn::custom_variable % _mysql.connections_count(); _finish_action(-1, actions::custom_variables); - log_v2::sql()->info("SQL: disabling custom variable '{}' of ({}, {})", - cv.name, cv.host_id, cv.service_id); + _logger_sql->info("SQL: disabling custom variable '{}' of ({}, {})", + cv.name, cv.host_id, cv.service_id); _custom_variable_delete.bind_value_as_i32_k(":host_id", cv.host_id); _custom_variable_delete.bind_value_as_i32_k(":service_id", cv.service_id); _custom_variable_delete.bind_value_as_str_k(":name", cv.name); @@ -517,8 +516,8 @@ void conflict_manager::_process_custom_variable_status( misc::string::escape( cv.value, get_customvariables_col_size(customvariables_value)))); - log_v2::sql()->info("SQL: updating custom variable '{}' of ({}, {})", cv.name, - cv.host_id, cv.service_id); + _logger_sql->info("SQL: updating custom variable '{}' of ({}, {})", cv.name, + cv.host_id, cv.service_id); } /** @@ -535,7 +534,7 @@ void conflict_manager::_process_downtime( const neb::downtime& dd = *static_cast(d.get()); // Log message. - log_v2::sql()->info( + _logger_sql->info( "SQL: processing downtime event (poller: {}" ", host: {}, service: {}, start time: {}, end_time: {}" ", actual start time: {}" @@ -599,9 +598,8 @@ void conflict_manager::_process_host_check( hc.next_check >= now - 5 * 60 || // - normal case !hc.next_check) { // - initial state // Apply to DB. - log_v2::sql()->info( - "SQL: processing host check event (host: {}, command: {}", hc.host_id, - hc.command_line); + _logger_sql->info("SQL: processing host check event (host: {}, command: {}", + hc.host_id, hc.command_line); // Prepare queries. if (!_host_check_update.prepared()) { @@ -633,7 +631,7 @@ void conflict_manager::_process_host_check( } } else // Do nothing. - log_v2::sql()->info( + _logger_sql->info( "SQL: not processing host check event (host: {}, command: {}, check " "type: {}, next check: {}, now: {})", hc.host_id, hc.command_line, hc.check_type, hc.next_check, now); @@ -662,8 +660,8 @@ void conflict_manager::_process_host_dependency( // Insert/Update. if (hd.enabled) { - log_v2::sql()->info("SQL: enabling host dependency of {} on {}", - hd.dependent_host_id, hd.host_id); + _logger_sql->info("SQL: enabling host dependency of {} on {}", + hd.dependent_host_id, hd.host_id); // Prepare queries. if (!_host_dependency_insupdate.prepared()) { @@ -682,8 +680,8 @@ void conflict_manager::_process_host_dependency( } // Delete. else { - log_v2::sql()->info("SQL: removing host dependency of {} on {}", - hd.dependent_host_id, hd.host_id); + _logger_sql->info("SQL: removing host dependency of {} on {}", + hd.dependent_host_id, hd.host_id); std::string query(fmt::format( "DELETE FROM hosts_hosts_dependencies WHERE dependent_host_id={}" " AND host_id={}", @@ -711,8 +709,8 @@ void conflict_manager::_process_host_group( neb::host_group const& hg{*static_cast(d.get())}; if (hg.enabled) { - log_v2::sql()->info("SQL: enabling host group {} ('{}' on instance {})", - hg.id, hg.name, hg.poller_id); + _logger_sql->info("SQL: enabling host group {} ('{}' on instance {})", + hg.id, hg.name, hg.poller_id); _prepare_hg_insupdate_statement(); _host_group_insupdate << hg; @@ -723,8 +721,8 @@ void conflict_manager::_process_host_group( } // Delete group. else { - log_v2::sql()->info("SQL: disabling host group {} ('{}' on instance {})", - hg.id, hg.name, hg.poller_id); + _logger_sql->info("SQL: disabling host group {} ('{}' on instance {})", + hg.id, hg.name, hg.poller_id); // Delete group members. { @@ -759,7 +757,7 @@ void conflict_manager::_process_host_group_member( if (hgm.enabled) { // Log message. - log_v2::sql()->info( + _logger_sql->info( "SQL: enabling membership of host {} to host group {} on instance {}", hgm.host_id, hgm.group_id, hgm.poller_id); @@ -776,7 +774,7 @@ void conflict_manager::_process_host_group_member( /* If the group does not exist, we create it. */ if (_cache_host_instance[hgm.host_id]) { if (_hostgroup_cache.find(hgm.group_id) == _hostgroup_cache.end()) { - log_v2::sql()->error( + _logger_sql->error( "SQL: host group {} does not exist - insertion before insertion of " "members", hgm.group_id); @@ -800,7 +798,7 @@ void conflict_manager::_process_host_group_member( conn); _add_action(conn, actions::hostgroups); } else - log_v2::sql()->error( + _logger_sql->error( "SQL: host with host_id = {} does not exist - unable to store " "unexisting host in a hostgroup. You should restart centengine.", hgm.host_id); @@ -808,7 +806,7 @@ void conflict_manager::_process_host_group_member( // Delete. else { // Log message. - log_v2::sql()->info( + _logger_sql->info( "SQL: disabling membership of host {} to host group {} on instance {}", hgm.host_id, hgm.group_id, hgm.poller_id); @@ -844,7 +842,7 @@ void conflict_manager::_process_host( neb::host& h = *static_cast(d.get()); // Log message. - log_v2::sql()->debug( + _logger_sql->debug( "SQL: processing host event (poller: {}, host: {}, name: {})", h.poller_id, h.host_id, h.host_name); @@ -876,7 +874,7 @@ void conflict_manager::_process_host( else _cache_host_instance.erase(h.host_id); } else - log_v2::sql()->trace( + _logger_sql->trace( "SQL: host '{}' of poller {} has no ID nor alias, probably bam " "fake host", h.host_name, h.poller_id); @@ -903,8 +901,8 @@ void conflict_manager::_process_host_parent( // Enable parenting. if (hp.enabled) { // Log message. - log_v2::sql()->info("SQL: host {} is parent of host {}", hp.parent_id, - hp.host_id); + _logger_sql->info("SQL: host {} is parent of host {}", hp.parent_id, + hp.host_id); // Prepare queries. if (!_host_parent_insert.prepared()) { @@ -920,8 +918,8 @@ void conflict_manager::_process_host_parent( } // Disable parenting. else { - log_v2::sql()->info("SQL: host {} is not parent of host {} anymore", - hp.parent_id, hp.host_id); + _logger_sql->info("SQL: host {} is not parent of host {} anymore", + hp.parent_id, hp.host_id); // Prepare queries. if (!_host_parent_delete.prepared()) { @@ -966,7 +964,7 @@ void conflict_manager::_process_host_status( hs.next_check >= now - 5 * 60 || // - normal case !hs.next_check) { // - initial state // Apply to DB. - log_v2::sql()->info( + _logger_sql->info( "processing host status event (host: {}, last check: {}, state ({}, " "{}))", hs.host_id, hs.last_check, hs.current_state, hs.state_type); @@ -988,7 +986,7 @@ void conflict_manager::_process_host_status( _add_action(conn, actions::hosts); } else // Do nothing. - log_v2::sql()->info( + _logger_sql->info( "SQL: not processing host status event (id: {}, check type: {}, last " "check: {}, next check: {}, now: {}, state: ({}, {}))", hs.host_id, hs.check_type, hs.last_check, hs.next_check, now, @@ -1016,7 +1014,7 @@ void conflict_manager::_process_instance( actions::host_dependencies); // Log message. - log_v2::sql()->info( + _logger_sql->info( "SQL: processing poller event (id: {}, name: {}, running: {})", i.poller_id, i.name, i.is_running ? "yes" : "no"); @@ -1062,7 +1060,7 @@ void conflict_manager::_process_instance_status( actions::comments); // Log message. - log_v2::sql()->info( + _logger_sql->info( "SQL: processing poller status event (id: {}, last alive: {})", is.poller_id, is.last_alive); @@ -1100,7 +1098,7 @@ void conflict_manager::_process_log( neb::log_entry const& le(*static_cast(d.get())); // Log message. - log_v2::sql()->info( + _logger_sql->info( "SQL: processing log of poller '{}' generated at {} (type {})", le.poller_name, le.c_time, le.msg_type); @@ -1151,7 +1149,7 @@ void conflict_manager::_process_service_check( || (sc.next_check >= now - 5 * 60) || !sc.next_check) { // - initial state // Apply to DB. - log_v2::sql()->info( + _logger_sql->info( "SQL: processing service check event (host: {}, service: {}, command: " "{})", sc.host_id, sc.service_id, sc.command_line); @@ -1184,14 +1182,14 @@ void conflict_manager::_process_service_check( database::mysql_error::store_service_check_command, conn); } else - log_v2::sql()->error( + _logger_sql->error( "SQL: host with host_id = {} does not exist - unable to store " "service command check of that host. You should restart centengine", sc.host_id); } } else // Do nothing. - log_v2::sql()->info( + _logger_sql->info( "SQL: not processing service check event (host: {}, service: {}, " "command: {}, check_type: {}, next_check: {}, now: {})", sc.host_id, sc.service_id, sc.command_line, sc.check_type, @@ -1221,7 +1219,7 @@ void conflict_manager::_process_service_dependency( // Insert/Update. if (sd.enabled) { - log_v2::sql()->info( + _logger_sql->info( "SQL: enabling service dependency of ({}, {}) on ({}, {})", sd.dependent_host_id, sd.dependent_service_id, sd.host_id, sd.service_id); @@ -1245,7 +1243,7 @@ void conflict_manager::_process_service_dependency( } // Delete. else { - log_v2::sql()->info( + _logger_sql->info( "SQL: removing service dependency of ({}, {}) on ({}, {})", sd.dependent_host_id, sd.dependent_service_id, sd.host_id, sd.service_id); @@ -1279,8 +1277,8 @@ void conflict_manager::_process_service_group( // Insert/update group. if (sg.enabled) { - log_v2::sql()->info("SQL: enabling service group {} ('{}' on instance {})", - sg.id, sg.name, sg.poller_id); + _logger_sql->info("SQL: enabling service group {} ('{}' on instance {})", + sg.id, sg.name, sg.poller_id); _prepare_sg_insupdate_statement(); _service_group_insupdate << sg; @@ -1291,8 +1289,8 @@ void conflict_manager::_process_service_group( } // Delete group. else { - log_v2::sql()->info("SQL: disabling service group {} ('{}' on instance {})", - sg.id, sg.name, sg.poller_id); + _logger_sql->info("SQL: disabling service group {} ('{}' on instance {})", + sg.id, sg.name, sg.poller_id); // Delete group members. { @@ -1330,7 +1328,7 @@ void conflict_manager::_process_service_group_member( if (sgm.enabled) { // Log message. - log_v2::sql()->info( + _logger_sql->info( "SQL: enabling membership of service ({}, {}) to service group {} on " "instance {}", sgm.host_id, sgm.service_id, sgm.group_id, sgm.poller_id); @@ -1348,7 +1346,7 @@ void conflict_manager::_process_service_group_member( /* If the group does not exist, we create it. */ if (_servicegroup_cache.find(sgm.group_id) == _servicegroup_cache.end()) { - log_v2::sql()->error( + _logger_sql->error( "SQL: service group {} does not exist - insertion before insertion " "of members", sgm.group_id); @@ -1375,7 +1373,7 @@ void conflict_manager::_process_service_group_member( // Delete. else { // Log message. - log_v2::sql()->info( + _logger_sql->info( "SQL: disabling membership of service ({}, {}) to service group {} on " "instance {}", sgm.host_id, sgm.service_id, sgm.group_id, sgm.poller_id); @@ -1418,7 +1416,7 @@ void conflict_manager::_process_service( _mysql.choose_connection_by_instance(_cache_host_instance[s.host_id]); // Log message. - log_v2::sql()->info( + _logger_sql->info( "SQL: processing service event (host: {}, service: {}, " "description: {})", s.host_id, s.service_id, s.service_description); @@ -1438,12 +1436,12 @@ void conflict_manager::_process_service( database::mysql_error::store_service, conn); _add_action(conn, actions::services); } else - log_v2::sql()->trace( + _logger_sql->trace( "SQL: service '{}' has no host ID, service ID nor hostname, probably " "bam fake service", s.service_description); } else - log_v2::sql()->error( + _logger_sql->error( "SQL: host with host_id = {} does not exist - unable to store service " "of that host. You should restart centengine", s.host_id); @@ -1467,9 +1465,8 @@ void conflict_manager::_process_service_status( neb::service_status const& ss{ *static_cast(d.get())}; - log_v2::perfdata()->info("SQL: service status output: <<{}>>", ss.output); - log_v2::perfdata()->info("SQL: service status perfdata: <<{}>>", - ss.perf_data); + _logger_storage->info("SQL: service status output: <<{}>>", ss.output); + _logger_storage->info("SQL: service status perfdata: <<{}>>", ss.perf_data); time_t now = time(nullptr); if (ss.check_type || // - passive result @@ -1478,7 +1475,7 @@ void conflict_manager::_process_service_status( || // - normal case ss.next_check >= now - 5 * 60 || !ss.next_check) { // - initial state // Apply to DB. - log_v2::sql()->info( + _logger_sql->info( "SQL: processing service status event (host: {}, service: {}, last " "check: {}, state ({}, {}))", ss.host_id, ss.service_id, ss.last_check, ss.current_state, @@ -1502,7 +1499,7 @@ void conflict_manager::_process_service_status( _add_action(conn, actions::services); } else // Do nothing. - log_v2::sql()->info( + _logger_sql->info( "SQL: not processing service status event (host: {}, service: {}, " "check type: {}, last check: {}, next check: {}, now: {}, state ({}, " "{}))", @@ -1523,7 +1520,7 @@ void conflict_manager::_process_responsive_instance( void conflict_manager::_process_severity( std::tuple, uint32_t, bool*>& t) { - log_v2::sql()->debug("SQL: process severity"); + _logger_sql->debug("SQL: process severity"); auto& d = std::get<0>(t); _finish_action(-1, actions::severities); @@ -1545,7 +1542,7 @@ void conflict_manager::_process_severity( case Severity_Action_ADD: _add_action(conn, actions::severities); if (severity_id) { - log_v2::sql()->trace("SQL: add already existing severity {}", sv.id()); + _logger_sql->trace("SQL: add already existing severity {}", sv.id()); _severity_update.bind_value_as_u64(0, sv.id()); _severity_update.bind_value_as_u32(1, sv.type()); _severity_update.bind_value_as_str(2, sv.name()); @@ -1555,7 +1552,7 @@ void conflict_manager::_process_severity( _mysql.run_statement(_severity_update, database::mysql_error::store_severity, conn); } else { - log_v2::sql()->trace("SQL: add severity {}", sv.id()); + _logger_sql->trace("SQL: add severity {}", sv.id()); _severity_insert.bind_value_as_u64(0, sv.id()); _severity_insert.bind_value_as_u32(1, sv.type()); _severity_insert.bind_value_as_str(2, sv.name()); @@ -1571,14 +1568,14 @@ void conflict_manager::_process_severity( severity_id = future.get(); _severity_cache[{sv.id(), sv.type()}] = severity_id; } catch (const std::exception& e) { - log_v2::sql()->error( + _logger_sql->error( "unified sql: unable to insert new severity ({},{}): {}", sv.id(), sv.type(), e.what()); } } break; case Severity_Action_MODIFY: - log_v2::sql()->trace("SQL: modify severity {}", sv.id()); + _logger_sql->trace("SQL: modify severity {}", sv.id()); _severity_update.bind_value_as_u64(0, sv.id()); _severity_update.bind_value_as_u32(1, sv.type()); _severity_update.bind_value_as_str(2, sv.name()); @@ -1590,18 +1587,18 @@ void conflict_manager::_process_severity( database::mysql_error::store_severity, conn); _add_action(conn, actions::severities); } else - log_v2::sql()->error( + _logger_sql->error( "unified sql: unable to modify severity ({}, {}): not in cache", sv.id(), sv.type()); break; case Severity_Action_DELETE: - log_v2::sql()->trace("SQL: remove severity {}: not implemented", sv.id()); + _logger_sql->trace("SQL: remove severity {}: not implemented", sv.id()); // FIXME DBO: Delete should be implemented later. This case is difficult // particularly when several pollers are running and some of them can // be stopped... break; default: - log_v2::sql()->error("Bad action in severity object"); + _logger_sql->error("Bad action in severity object"); break; } *std::get<2>(t) = true; @@ -1609,7 +1606,7 @@ void conflict_manager::_process_severity( void conflict_manager::_process_tag( std::tuple, uint32_t, bool*>& t) { - log_v2::sql()->debug("SQL: process tag"); + _logger_sql->debug("SQL: process tag"); auto& d = std::get<0>(t); _finish_action(-1, actions::tags); @@ -1630,7 +1627,7 @@ void conflict_manager::_process_tag( switch (tg.action()) { case Tag_Action_ADD: if (tag_id) { - log_v2::sql()->trace("SQL: add already existing tag {}", tg.id()); + _logger_sql->trace("SQL: add already existing tag {}", tg.id()); _tag_update.bind_value_as_u64(0, tg.id()); _tag_update.bind_value_as_u32(1, tg.type()); _tag_update.bind_value_as_str(2, tg.name()); @@ -1638,7 +1635,7 @@ void conflict_manager::_process_tag( _mysql.run_statement(_tag_update, database::mysql_error::store_tag, conn); } else { - log_v2::sql()->trace("SQL: add tag {}", tg.id()); + _logger_sql->trace("SQL: add tag {}", tg.id()); _tag_insert.bind_value_as_u64(0, tg.id()); _tag_insert.bind_value_as_u32(1, tg.type()); _tag_insert.bind_value_as_str(2, tg.name()); @@ -1651,7 +1648,7 @@ void conflict_manager::_process_tag( tag_id = future.get(); _tags_cache[{tg.id(), tg.type()}] = tag_id; } catch (const std::exception& e) { - log_v2::sql()->error( + _logger_sql->error( "unified sql: unable to insert new tag ({},{}): {}", tg.id(), tg.type(), e.what()); } @@ -1659,7 +1656,7 @@ void conflict_manager::_process_tag( _add_action(conn, actions::tags); break; case Tag_Action_MODIFY: - log_v2::sql()->trace("SQL: modify tag {}", tg.id()); + _logger_sql->trace("SQL: modify tag {}", tg.id()); _tag_update.bind_value_as_u64(0, tg.id()); _tag_update.bind_value_as_u32(1, tg.type()); _tag_update.bind_value_as_str(2, tg.name()); @@ -1669,13 +1666,13 @@ void conflict_manager::_process_tag( conn); _add_action(conn, actions::tags); } else - log_v2::sql()->error( + _logger_sql->error( "unified sql: unable to modify tag ({}, {}): not in cache", tg.id(), tg.type()); break; break; default: - log_v2::sql()->error("Bad action in tag object"); + _logger_sql->error("Bad action in tag object"); break; } } @@ -1707,8 +1704,8 @@ void conflict_manager::_update_customvariables() { std::string query(oss.str()); _mysql.run_query(query, database::mysql_error::update_customvariables, conn); - log_v2::sql()->debug("{} new custom variables inserted", _cv_queue.size()); - log_v2::sql()->trace("sending query << {} >>", query); + _logger_sql->debug("{} new custom variables inserted", _cv_queue.size()); + _logger_sql->trace("sending query << {} >>", query); _add_action(conn, actions::custom_variables); /* Acknowledgement and cleanup */ @@ -1735,9 +1732,9 @@ void conflict_manager::_update_customvariables() { std::string query(oss.str()); _mysql.run_query(query, database::mysql_error::update_customvariables, conn); - log_v2::sql()->debug("{} new custom variable status inserted", - _cvs_queue.size()); - log_v2::sql()->trace("sending query << {} >>", query); + _logger_sql->debug("{} new custom variable status inserted", + _cvs_queue.size()); + _logger_sql->trace("sending query << {} >>", query); _add_action(conn, actions::custom_variables); /* Acknowledgement and cleanup */ @@ -1757,7 +1754,7 @@ void conflict_manager::_update_customvariables() { * When we exit the function, the downtimes queue is empty. */ void conflict_manager::_update_downtimes() { - log_v2::sql()->debug("sql: update downtimes"); + _logger_sql->debug("sql: update downtimes"); int32_t conn = special_conn::downtime % _mysql.connections_count(); _finish_action(-1, actions::hosts | actions::instances | actions::downtimes | actions::host_parents | actions::host_dependencies | @@ -1786,8 +1783,8 @@ void conflict_manager::_update_downtimes() { std::string query{oss.str()}; _mysql.run_query(query, database::mysql_error::store_downtime, conn); - log_v2::sql()->debug("{} new downtimes inserted", _downtimes_queue.size()); - log_v2::sql()->trace("sending query << {} >>", query); + _logger_sql->debug("{} new downtimes inserted", _downtimes_queue.size()); + _logger_sql->trace("sending query << {} >>", query); _add_action(conn, actions::downtimes); /* Acknowledgement and cleanup */ @@ -1824,8 +1821,8 @@ void conflict_manager::_insert_logs() { std::string query(oss.str()); _mysql.run_query(query, database::mysql_error::update_logs, conn); - log_v2::sql()->debug("{} new logs inserted", _log_queue.size()); - log_v2::sql()->trace("sending query << {} >>", query); + _logger_sql->debug("{} new logs inserted", _log_queue.size()); + _logger_sql->trace("sending query << {} >>", query); /* Acknowledgement and cleanup */ while (!_log_queue.empty()) { diff --git a/broker/storage/src/conflict_manager_storage.cc b/broker/storage/src/conflict_manager_storage.cc index c2921bb4e2b..ba0733dbcde 100644 --- a/broker/storage/src/conflict_manager_storage.cc +++ b/broker/storage/src/conflict_manager_storage.cc @@ -25,7 +25,6 @@ #include "bbdo/storage/metric_mapping.hh" #include "bbdo/storage/remove_graph.hh" #include "bbdo/storage/status.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/misc.hh" #include "com/centreon/broker/misc/perfdata.hh" #include "com/centreon/broker/misc/string.hh" @@ -72,7 +71,7 @@ void conflict_manager::_storage_process_service_status( auto& d = std::get<0>(t); neb::service_status const& ss{*static_cast(d.get())}; uint64_t host_id = ss.host_id, service_id = ss.service_id; - log_v2::perfdata()->debug( + _logger_storage->debug( "conflict_manager::_storage_process_service_status(): host_id:{}, " "service_id:{}", host_id, service_id); @@ -96,7 +95,7 @@ void conflict_manager::_storage_process_service_status( } /* Insert index in cache. */ - log_v2::perfdata()->info( + _logger_storage->info( "conflict_manager: add_metric_in_cache: index {}, for host_id {} and " "service_id {}", index_id, host_id, service_id); @@ -109,7 +108,7 @@ void conflict_manager::_storage_process_service_status( _index_cache[{host_id, service_id}] = std::move(info); rrd_len = _rrd_len; - log_v2::perfdata()->debug( + _logger_storage->debug( "add metric in cache: (host: {}, service: {}, index: {}, returned " "rrd_len {}", ss.host_name, ss.service_description, index_id, rrd_len); @@ -125,7 +124,7 @@ void conflict_manager::_storage_process_service_status( /* Index does not exist */ if (it_index_cache == _index_cache.end()) { _finish_action(-1, actions::index_data); - log_v2::perfdata()->debug( + _logger_storage->debug( "conflict_manager::_storage_process_service_status(): host_id:{}, " "service_id:{} - index not found in cache", host_id, service_id); @@ -167,7 +166,7 @@ void conflict_manager::_storage_process_service_status( { std::promise promise; std::future future = promise.get_future(); - log_v2::sql()->debug( + _logger_sql->debug( "Query for index_data for host_id={} and service_id={}", host_id, service_id); _mysql.run_statement_and_get_result(_index_data_query, @@ -193,7 +192,7 @@ void conflict_manager::_storage_process_service_status( "special=? " "WHERE id=?"); - log_v2::sql()->debug( + _logger_sql->debug( "Updating index_data for host_id={} and service_id={}", host_id, service_id); _index_data_update.bind_value_as_str(0, hv); @@ -211,7 +210,7 @@ void conflict_manager::_storage_process_service_status( add_metric_in_cache(index_id, host_id, service_id, ss, index_locked, special, rrd_len); - log_v2::sql()->debug( + _logger_sql->debug( "Index {} stored in cache for host_id={} and service_id={}", index_id, host_id, service_id); } catch (std::exception const& e) { @@ -225,7 +224,7 @@ void conflict_manager::_storage_process_service_status( index_id = it_index_cache->second.index_id; rrd_len = it_index_cache->second.rrd_retention; index_locked = it_index_cache->second.locked; - log_v2::perfdata()->debug( + _logger_storage->debug( "conflict_manager: host_id:{}, service_id:{} - index already in cache " "- index_id {}, rrd_len {}", host_id, service_id, index_id, rrd_len); @@ -233,7 +232,7 @@ void conflict_manager::_storage_process_service_status( if (index_id) { /* Generate status event */ - log_v2::perfdata()->debug( + _logger_storage->debug( "conflict_manager: host_id:{}, service_id:{} - generating status event " "with index_id {}, rrd_len: {}", host_id, service_id, index_id, rrd_len); @@ -259,7 +258,7 @@ void conflict_manager::_storage_process_service_status( /* Parse perfdata. */ _finish_action(-1, actions::metrics); std::list pds{misc::parse_perfdata( - ss.host_id, ss.service_id, ss.perf_data.c_str())}; + ss.host_id, ss.service_id, ss.perf_data.c_str(), _logger_storage)}; std::deque> to_publish; for (auto& pd : pds) { @@ -269,7 +268,7 @@ void conflict_manager::_storage_process_service_status( uint32_t metric_id; bool need_metric_mapping = true; if (it_index_cache == _metric_cache.end()) { - log_v2::perfdata()->debug( + _logger_storage->debug( "conflict_manager: no metrics corresponding to index {} and " "perfdata '{}' found in cache", index_id, pd.name()); @@ -303,7 +302,7 @@ void conflict_manager::_storage_process_service_status( metric_id = future.get(); // Insert metric in cache. - log_v2::perfdata()->info( + _logger_storage->info( "conflict_manager: new metric {} for index {} and perfdata " "'{}'", metric_id, index_id, pd.name()); @@ -326,7 +325,7 @@ void conflict_manager::_storage_process_service_status( std::lock_guard lock(_metric_cache_m); _metric_cache[{index_id, pd.name()}] = info; } catch (const std::exception& e) { - log_v2::perfdata()->error( + _logger_storage->error( "conflict_manager: failed to create metric {} with type {}, " "value {}, unit_name {}, warn {}, warn_low {}, warn_mode {}, " "crit {}, crit_low {}, crit_mode {}, min {} and max {}", @@ -349,7 +348,7 @@ void conflict_manager::_storage_process_service_status( pd.value_type(it_index_cache->second.type); - log_v2::perfdata()->debug( + _logger_storage->debug( "conflict_manager: metric {} concerning index {}, perfdata " "'{}' found in cache", it_index_cache->second.metric_id, index_id, pd.name()); @@ -366,7 +365,7 @@ void conflict_manager::_storage_process_service_status( it_index_cache->second.crit_mode != pd.critical_mode() || !check_equality(it_index_cache->second.min, pd.min()) || !check_equality(it_index_cache->second.max, pd.max())) { - log_v2::perfdata()->info( + _logger_storage->info( "conflict_manager: updating metric {} of index {}, perfdata " "'{}' with unit: {}, warning: {}:{}, critical: {}:{}, min: " "{}, max: {}", @@ -386,8 +385,8 @@ void conflict_manager::_storage_process_service_status( it_index_cache->second.max = pd.max(); _metrics[it_index_cache->second.metric_id] = &it_index_cache->second; - log_v2::perfdata()->debug("new metric with metric_id={}", - it_index_cache->second.metric_id); + _logger_storage->debug("new metric with metric_id={}", + it_index_cache->second.metric_id); } } if (need_metric_mapping) @@ -411,7 +410,7 @@ void conflict_manager::_storage_process_service_status( static_cast(ss.check_interval * _interval_length), false, metric_id, rrd_len, pd.value(), static_cast(pd.value_type()))}; - log_v2::perfdata()->debug( + _logger_storage->debug( "conflict_manager: generating perfdata event for metric {} " "(name '{}', time {}, value {}, rrd_len {}, data_type {})", perf->metric_id, perf->name, perf->time, perf->value, rrd_len, @@ -473,7 +472,7 @@ void conflict_manager::_update_metrics() { fmt::join(m, ","))); int32_t conn = _mysql.choose_best_connection(-1); _finish_action(-1, actions::metrics); - log_v2::sql()->trace("Send query: {}", query); + _logger_sql->trace("Send query: {}", query); _mysql.run_query(query, database::mysql_error::update_metrics, conn); _add_action(conn, actions::metrics); _metrics.clear(); @@ -528,7 +527,7 @@ void conflict_manager::_insert_perfdatas() { _mysql.run_query(query.str(), database::mysql_error::insert_data); //_update_status(""); - log_v2::sql()->info("storage: {} perfdata inserted in data_bin", count); + _logger_sql->info("storage: {} perfdata inserted in data_bin", count); } } @@ -537,7 +536,7 @@ void conflict_manager::_insert_perfdatas() { */ void conflict_manager::_check_deleted_index() { // Info. - log_v2::sql()->info("storage: starting DB cleanup"); + _logger_sql->info("storage: starting DB cleanup"); uint32_t deleted_index(0); uint32_t deleted_metrics(0); @@ -594,7 +593,7 @@ void conflict_manager::_check_deleted_index() { multiplexing::publisher().write(rg); _metrics.erase(i); - log_v2::perfdata()->debug("metrics erasing metric_id = {}", i); + _logger_storage->debug("metrics erasing metric_id = {}", i); deleted_metrics++; } @@ -613,7 +612,7 @@ void conflict_manager::_check_deleted_index() { } // End. - log_v2::perfdata()->info( + _logger_storage->info( "storage: end of DB cleanup: {} metrics and {} indices removed", deleted_metrics, deleted_index); } diff --git a/broker/storage/src/connector.cc b/broker/storage/src/connector.cc index 013dfa81788..56554a2d0d6 100644 --- a/broker/storage/src/connector.cc +++ b/broker/storage/src/connector.cc @@ -1,20 +1,20 @@ /** -* Copyright 2011-2015,2017 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2015,2017 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/storage/connector.hh" @@ -26,7 +26,12 @@ using namespace com::centreon::broker::storage; /** * Default constructor. */ -connector::connector() : io::endpoint(false, {}) {} +connector::connector() + : io::endpoint( + false, + multiplexing::muxer_filter(multiplexing::muxer_filter::zero_init()), + multiplexing::muxer_filter(multiplexing::muxer_filter::zero_init()) + .add_category(io::local)) {} /** * Set connection parameters. diff --git a/broker/storage/src/factory.cc b/broker/storage/src/factory.cc index 814f79c0968..ee2a4dd79ba 100644 --- a/broker/storage/src/factory.cc +++ b/broker/storage/src/factory.cc @@ -1,39 +1,34 @@ /** -* Copyright 2011-2015,2017 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2015,2017 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/storage/factory.hh" #include #include "com/centreon/broker/config/parser.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/storage/connector.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::storage; - -/************************************** - * * - * Static Objects * - * * - **************************************/ +using log_v2 = com::centreon::common::log_v2::log_v2; /** * Find a parameter in configuration. @@ -93,9 +88,11 @@ io::endpoint* factory::new_endpoint( uint32_t rrd_length; if (!absl::SimpleAtoi(find_param(cfg, "length"), &rrd_length)) { rrd_length = 15552000; - log_v2::sql()->error( - "storage: the length field should contain a string containing a " - "number. We use the default value in replacement 15552000."); + log_v2::instance() + .get(log_v2::CORE) + ->error( + "storage: the length field should contain a string containing a " + "number. We use the default value in replacement 15552000."); } // Find interval length if set. @@ -106,9 +103,12 @@ io::endpoint* factory::new_endpoint( if (it != cfg.params.end()) { if (!absl::SimpleAtoi(it->second, &interval_length)) { interval_length = 60; - log_v2::sql()->error( - "storage: the interval field should contain a string containing a " - "number. We use the default value in replacement 60."); + log_v2::instance() + .get(log_v2::CORE) + ->error( + "storage: the interval field should contain a string " + "containing a " + "number. We use the default value in replacement 60."); } } if (!interval_length) @@ -125,10 +125,12 @@ io::endpoint* factory::new_endpoint( cfg.params.find("store_in_data_bin")}; if (it != cfg.params.end()) { if (!absl::SimpleAtob(it->second, &store_in_data_bin)) { - log_v2::sql()->error( - "factory: cannot parse the 'store_in_data_bin' boolean: the " - "content is '{}'", - it->second); + log_v2::instance() + .get(log_v2::CORE) + ->error( + "factory: cannot parse the 'store_in_data_bin' boolean: the " + "content is '{}'", + it->second); store_in_data_bin = true; } } diff --git a/broker/storage/src/main.cc b/broker/storage/src/main.cc index dec12f0ded9..1826229983f 100644 --- a/broker/storage/src/main.cc +++ b/broker/storage/src/main.cc @@ -1,20 +1,20 @@ /** -* Copyright 2011-2013 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2013 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "bbdo/events.hh" #include "bbdo/storage/index_mapping.hh" @@ -24,14 +24,15 @@ #include "bbdo/storage/status.hh" #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/io/protocols.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/storage/factory.hh" #include "com/centreon/broker/storage/internal.hh" #include "com/centreon/broker/storage/stream.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; +using log_v2 = com::centreon::common::log_v2::log_v2; // Load count. static uint32_t instances{0u}; @@ -74,11 +75,12 @@ bool broker_module_deinit() { void broker_module_init(void const* arg) { (void)arg; + auto logger = log_v2::instance().get(log_v2::PERFDATA); // Increment instance number. if (!instances++) { // Storage module. - log_v2::sql()->info("storage: module for Centreon Broker {}", - CENTREON_BROKER_VERSION); + logger->info("storage: module for Centreon Broker {}", + CENTREON_BROKER_VERSION); io::events& e(io::events::instance()); @@ -119,6 +121,10 @@ void broker_module_init(void const* arg) { e.register_event(make_type(io::storage, storage::de_remove_graph_message), "remove_graphs_message", &storage::pb_remove_graph_message::operations); + /* Let's register the message received when a poller is stopped. This is + * local::pb_stop. */ + e.register_event(make_type(io::local, local::de_pb_stop), "LocStop", + &local::pb_stop::operations); } // Register storage layer. diff --git a/broker/storage/src/rebuilder.cc b/broker/storage/src/rebuilder.cc index 946f80fdae2..39cf5016e6d 100644 --- a/broker/storage/src/rebuilder.cc +++ b/broker/storage/src/rebuilder.cc @@ -22,7 +22,6 @@ #include #include -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/time.hh" #include "com/centreon/broker/multiplexing/publisher.hh" #include "com/centreon/broker/sql/mysql_error.hh" @@ -30,10 +29,12 @@ #include "com/centreon/broker/storage/internal.hh" #include "com/centreon/broker/storage/stream.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::storage; +using com::centreon::common::log_v2::log_v2; /** * Constructor. @@ -45,7 +46,10 @@ using namespace com::centreon::broker::storage; rebuilder::rebuilder(const database_config& db_cfg, uint32_t rrd_length, uint32_t interval_length) - : _db_cfg(db_cfg), _interval_length(interval_length), _rrd_len(rrd_length) { + : _db_cfg(db_cfg), + _interval_length(interval_length), + _rrd_len(rrd_length), + _logger{log_v2::instance().get(log_v2::SQL)} { _db_cfg.set_connections_count(1); _db_cfg.set_queries_per_transaction(1); } @@ -62,7 +66,7 @@ void rebuilder::rebuild_graphs(const std::shared_ptr& d) { std::string ids_str{ fmt::format("{}", fmt::join(ids.obj().index_ids(), ","))}; - log_v2::sql()->debug( + _logger->debug( "Metric rebuild: Rebuild metrics event received for metrics ({})", ids_str); @@ -84,7 +88,7 @@ void rebuilder::rebuild_graphs(const std::shared_ptr& d) { "i ON m.index_id=i.id LEFT JOIN services s ON i.host_id=s.host_id AND " "i.service_id=s.service_id WHERE i.id IN ({})", ids_str)}; - log_v2::sql()->trace("Metric rebuild: Executed query << {} >>", query); + _logger->trace("Metric rebuild: Executed query << {} >>", query); ms.run_query_and_get_result(query, std::move(promise), conn); std::map ret_inter; std::list mids; @@ -96,8 +100,7 @@ void rebuilder::rebuild_graphs(const std::shared_ptr& d) { uint64_t mid = res.value_as_u64(0); uint64_t index_id = res.value_as_u64(5); mids.push_back(mid); - log_v2::sql()->trace("Metric rebuild: metric {} is sent to rebuild", - mid); + _logger->trace("Metric rebuild: metric {} is sent to rebuild", mid); (*start_rebuild->mut_obj().mutable_metric_to_index_id())[mid] = index_id; auto ret = ret_inter.emplace(mid, metric_info()); @@ -128,8 +131,7 @@ void rebuilder::rebuild_graphs(const std::shared_ptr& d) { int32_t db_retention_day1 = res.value_as_i32(1); if (db_retention_day1 < db_retention_day) db_retention_day = db_retention_day1; - log_v2::sql()->debug("Storage retention on RRD: {} days", - db_retention_day); + _logger->debug("Storage retention on RRD: {} days", db_retention_day); } if (db_retention_day) { /* Let's get the start of this day */ @@ -143,8 +145,8 @@ void rebuilder::rebuild_graphs(const std::shared_ptr& d) { tmv.tm_mday -= db_retention_day; start = mktime(&tmv); while (db_retention_day >= 0) { - log_v2::sql()->trace("Metrics rebuild: db_retention_day = {}", - db_retention_day); + _logger->trace("Metrics rebuild: db_retention_day = {}", + db_retention_day); tmv.tm_mday++; end = mktime(&tmv); db_retention_day--; @@ -155,8 +157,7 @@ void rebuilder::rebuild_graphs(const std::shared_ptr& d) { "ctime>={} AND " "ctime<{} AND id_metric IN ({}) ORDER BY ctime ASC", start, end, mids_str)}; - log_v2::sql()->trace("Metrics rebuild: Query << {} >> executed", - query); + _logger->trace("Metrics rebuild: Query << {} >> executed", query); ms.run_query_and_get_result(query, std::move(promise), conn); auto data_rebuild = std::make_shared(); data_rebuild->mut_obj().set_state(RebuildMessage_State_DATA); @@ -188,8 +189,8 @@ void rebuilder::rebuild_graphs(const std::shared_ptr& d) { throw msg_fmt("Metrics rebuild: Cannot get the date structure."); } } catch (const std::exception& e) { - log_v2::sql()->error("Metrics rebuild: Error during metrics rebuild: {}", - e.what()); + _logger->error("Metrics rebuild: Error during metrics rebuild: {}", + e.what()); } auto end_rebuild = std::make_shared(); end_rebuild->set_obj(std::move(start_rebuild->mut_obj())); @@ -200,7 +201,7 @@ void rebuilder::rebuild_graphs(const std::shared_ptr& d) { "UPDATE index_data SET must_be_rebuild='0' WHERE id IN ({})", ids_str), database::mysql_error::update_index_state, false); - log_v2::sql()->debug( + _logger->debug( "Metric rebuild: Rebuild of metrics from the following indexes ({}) " "finished", ids_str); diff --git a/broker/storage/src/stream.cc b/broker/storage/src/stream.cc index 75b7a05a56b..cc4d0905ef5 100644 --- a/broker/storage/src/stream.cc +++ b/broker/storage/src/stream.cc @@ -1,33 +1,33 @@ /** -* Copyright 2011-2021 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2021 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/storage/stream.hh" #include #include +#include "bbdo/events.hh" #include "bbdo/storage/index_mapping.hh" #include "bbdo/storage/metric.hh" #include "bbdo/storage/remove_graph.hh" #include "bbdo/storage/status.hh" #include "com/centreon/broker/exceptions/shutdown.hh" #include "com/centreon/broker/io/events.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/misc.hh" #include "com/centreon/broker/misc/perfdata.hh" #include "com/centreon/broker/multiplexing/publisher.hh" @@ -37,11 +37,13 @@ #include "com/centreon/broker/neb/service_status.hh" #include "com/centreon/broker/storage/conflict_manager.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::misc; using namespace com::centreon::broker::storage; +using log_v2 = com::centreon::common::log_v2::log_v2; /** * Constructor. @@ -58,14 +60,18 @@ stream::stream(database_config const& dbcfg, uint32_t rrd_len, uint32_t interval_length, bool store_in_db) - : io::stream("storage"), _pending_events(0), _stopped(false) { - log_v2::sql()->debug("storage stream instanciation"); + : io::stream("storage"), + _pending_events(0), + _stopped(false), + _logger_sql{log_v2::instance().get(log_v2::SQL)}, + _logger_storage{log_v2::instance().get(log_v2::PERFDATA)} { + _logger_sql->debug("storage stream instanciation"); if (!rrd_len) rrd_len = 15552000; if (!conflict_manager::init_storage(store_in_db, rrd_len, interval_length, dbcfg)) { - log_v2::sql()->error("storage stream instanciation failed"); + _logger_sql->error("storage stream instanciation failed"); throw msg_fmt( "storage: Unable to initialize the storage connection to the database"); } @@ -73,10 +79,10 @@ stream::stream(database_config const& dbcfg, int32_t stream::stop() { // Stop cleanup thread. - int32_t retval = - conflict_manager::instance().unload(conflict_manager::storage); - log_v2::core()->info("storage stream stopped with {} acknowledged events", - retval); + int32_t retval = conflict_manager::unload(conflict_manager::storage); + log_v2::instance() + .get(log_v2::CORE) + ->info("storage stream stopped with {} acknowledged events", retval); _stopped = true; return retval; } @@ -87,7 +93,7 @@ int32_t stream::stop() { stream::~stream() { assert(_stopped); // Stop cleanup thread. - log_v2::sql()->debug("storage: stream destruction"); + _logger_sql->debug("storage: stream destruction"); } /** @@ -101,8 +107,8 @@ int32_t stream::flush() { _pending_events -= retval; // Event acknowledgement. - log_v2::perfdata()->debug("storage: {} / {} events acknowledged", retval, - _pending_events); + _logger_storage->debug("storage: {} / {} events acknowledged", retval, + _pending_events); return retval; } @@ -148,8 +154,8 @@ int32_t stream::write(std::shared_ptr const& data) { conflict_manager::instance().send_event(conflict_manager::storage, data); _pending_events -= ack; // Event acknowledgement. - log_v2::perfdata()->debug("storage: {} / {} events acknowledged", ack, - _pending_events); + _logger_storage->debug("storage: {} / {} events acknowledged", ack, + _pending_events); return ack; } diff --git a/broker/storage/test/conflict_manager.cc b/broker/storage/test/conflict_manager.cc index 90837f3a95a..80df27225ff 100644 --- a/broker/storage/test/conflict_manager.cc +++ b/broker/storage/test/conflict_manager.cc @@ -1,20 +1,20 @@ /** -* Copyright 2018 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2018 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/storage/conflict_manager.hh" diff --git a/broker/storage/test/status-entry.cc b/broker/storage/test/status-entry.cc index f37feef22ad..49ab813d8d6 100644 --- a/broker/storage/test/status-entry.cc +++ b/broker/storage/test/status-entry.cc @@ -1,21 +1,21 @@ /** - * * Copyright 2021 Centreon (https://www.centreon.com/) - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * * - * * For more information : contact@centreon.com - * * - * */ + * Copyright 2021 Centreon (https://www.centreon.com/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include #include @@ -26,16 +26,17 @@ #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/io/protocols.hh" #include "com/centreon/broker/io/raw.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/lua/macro_cache.hh" #include "com/centreon/broker/misc/string.hh" #include "com/centreon/broker/misc/variant.hh" #include "com/centreon/broker/modules/handle.hh" #include "com/centreon/broker/neb/instance.hh" #include "com/centreon/broker/storage/factory.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::misc; +using com::centreon::common::log_v2::log_v2; class into_memory : public io::stream { std::vector _memory; @@ -75,15 +76,15 @@ class StatusEntryTest : public ::testing::Test { } catch (std::exception const& e) { (void)e; } - std::shared_ptr pcache( - std::make_shared("/tmp/broker_test_cache")); + std::shared_ptr pcache(std::make_shared( + "/tmp/broker_test_cache", log_v2::instance().get(log_v2::PERFDATA))); } void TearDown() override { // The cache must be destroyed before the applier deinit() call. config::applier::deinit(); ::remove("/tmp/broker_test_cache"); - ::remove(log_v2::instance()->log_name().c_str()); + ::remove(log_v2::instance().filename().c_str()); } }; diff --git a/broker/tcp/inc/com/centreon/broker/tcp/acceptor.hh b/broker/tcp/inc/com/centreon/broker/tcp/acceptor.hh index b4709cfd7b6..4c9216840d2 100644 --- a/broker/tcp/inc/com/centreon/broker/tcp/acceptor.hh +++ b/broker/tcp/inc/com/centreon/broker/tcp/acceptor.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2011-2013 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2011-2013 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_TCP_ACCEPTOR_HH #define CCB_TCP_ACCEPTOR_HH diff --git a/broker/tcp/inc/com/centreon/broker/tcp/connector.hh b/broker/tcp/inc/com/centreon/broker/tcp/connector.hh index 6d9f8c9a1eb..fa535474db3 100644 --- a/broker/tcp/inc/com/centreon/broker/tcp/connector.hh +++ b/broker/tcp/inc/com/centreon/broker/tcp/connector.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2011-2013, 2020-2021 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2011-2013, 2020-2021 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_TCP_CONNECTOR_HH #define CCB_TCP_CONNECTOR_HH @@ -36,7 +36,7 @@ class connector : public io::limit_endpoint { public: connector(const tcp_config::pointer& conf); - ~connector(); + ~connector() noexcept = default; connector& operator=(const connector&) = delete; connector(const connector&) = delete; @@ -47,6 +47,6 @@ class connector : public io::limit_endpoint { }; } // namespace tcp -} +} // namespace com::centreon::broker #endif // !CCB_TCP_CONNECTOR_HH diff --git a/broker/tcp/inc/com/centreon/broker/tcp/factory.hh b/broker/tcp/inc/com/centreon/broker/tcp/factory.hh index 6ef7e48e2b6..5df442f411b 100644 --- a/broker/tcp/inc/com/centreon/broker/tcp/factory.hh +++ b/broker/tcp/inc/com/centreon/broker/tcp/factory.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2011-2013, 2020-2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2011-2013, 2020-2022 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_TCP_FACTORY_HH #define CCB_TCP_FACTORY_HH @@ -50,6 +50,6 @@ class factory : public io::factory { }; } // namespace tcp -} +} // namespace com::centreon::broker #endif // !CCB_TCP_FACTORY_HH diff --git a/broker/tcp/inc/com/centreon/broker/tcp/stream.hh b/broker/tcp/inc/com/centreon/broker/tcp/stream.hh index 74b412d868c..1d780aff4ac 100644 --- a/broker/tcp/inc/com/centreon/broker/tcp/stream.hh +++ b/broker/tcp/inc/com/centreon/broker/tcp/stream.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2011-2013,2015,2017 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2011-2013,2015,2017 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_TCP_STREAM_HH #define CCB_TCP_STREAM_HH @@ -41,6 +41,7 @@ class stream : public io::stream { tcp_config::pointer _conf; tcp_connection::pointer _connection; acceptor* _parent; + std::shared_ptr _logger; public: stream(const tcp_config::pointer& conf); @@ -58,6 +59,6 @@ class stream : public io::stream { }; } // namespace tcp -} +} // namespace com::centreon::broker #endif // !CCB_TCP_STREAM_HH diff --git a/broker/tcp/inc/com/centreon/broker/tcp/tcp_async.hh b/broker/tcp/inc/com/centreon/broker/tcp/tcp_async.hh index 290227057ed..a8f7ba260bf 100644 --- a/broker/tcp/inc/com/centreon/broker/tcp/tcp_async.hh +++ b/broker/tcp/inc/com/centreon/broker/tcp/tcp_async.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2020-2021 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2020-2021 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CENTREON_BROKER_TCP_INC_COM_CENTREON_BROKER_TCP_TCP_ASYNC_HH_ #define CENTREON_BROKER_TCP_INC_COM_CENTREON_BROKER_TCP_TCP_ASYNC_HH_ @@ -72,12 +72,15 @@ class tcp_async : public std::enable_shared_from_this { std::unique_ptr _timer; std::atomic_bool _clear_available_con_running; + std::shared_ptr _logger; + tcp_async(); void _clear_available_con(boost::system::error_code ec); static void _set_sock_opt(asio::ip::tcp::socket& sock, - const tcp_config::pointer& conf); + const tcp_config::pointer& conf, + const std::shared_ptr& logger); public: static void load(); diff --git a/broker/tcp/inc/com/centreon/broker/tcp/tcp_connection.hh b/broker/tcp/inc/com/centreon/broker/tcp/tcp_connection.hh index b677865bf61..b480cce5f12 100644 --- a/broker/tcp/inc/com/centreon/broker/tcp/tcp_connection.hh +++ b/broker/tcp/inc/com/centreon/broker/tcp/tcp_connection.hh @@ -1,27 +1,24 @@ -/* -** Copyright 2020-2021 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2020-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CENTREON_BROKER_TCP_CONNECTION_HH #define CENTREON_BROKER_TCP_CONNECTION_HH - -namespace com::centreon::broker { - -namespace tcp { +namespace com::centreon::broker::tcp { class tcp_connection : public std::enable_shared_from_this { constexpr static std::size_t async_buf_size = 16384; @@ -51,9 +48,12 @@ class tcp_connection : public std::enable_shared_from_this { std::string _address; uint16_t _port; + std::shared_ptr _logger; + public: typedef std::shared_ptr pointer; tcp_connection(asio::io_context& io_context, + const std::shared_ptr& logger, const std::string& host = "", uint16_t port = 0); ~tcp_connection() noexcept; @@ -83,8 +83,6 @@ class tcp_connection : public std::enable_shared_from_this { bool wait_for_all_events_written(unsigned ms_timeout); }; -} // namespace tcp - -} +} // namespace com::centreon::broker::tcp #endif /* !CENTREON_BROKER_TCP_CONNECTION_HH */ diff --git a/broker/tcp/src/acceptor.cc b/broker/tcp/src/acceptor.cc index 9048e8ebeb4..b39115f62ba 100644 --- a/broker/tcp/src/acceptor.cc +++ b/broker/tcp/src/acceptor.cc @@ -21,12 +21,21 @@ #include -#include "com/centreon/broker/log_v2.hh" +#include "com/centreon/broker/multiplexing/muxer_filter.hh" #include "com/centreon/broker/tcp/stream.hh" #include "com/centreon/broker/tcp/tcp_async.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::tcp; +using log_v2 = com::centreon::common::log_v2::log_v2; + +static constexpr multiplexing::muxer_filter _tcp_stream_filter = + multiplexing::muxer_filter(multiplexing::muxer_filter::zero_init()); + +static constexpr multiplexing::muxer_filter _tcp_forbidden_filter = + multiplexing::muxer_filter(multiplexing::muxer_filter::zero_init()) + .add_category(io::local); /** * @brief Acceptor constructor. It needs the port used to listen and a read @@ -36,13 +45,15 @@ using namespace com::centreon::broker::tcp; * @param read_timeout A duration in seconds. */ acceptor::acceptor(const tcp_config::pointer& conf) - : io::endpoint(true, {}), _conf(conf) {} + : io::endpoint(true, _tcp_stream_filter, _tcp_forbidden_filter), + _conf(conf) {} /** * Destructor. */ acceptor::~acceptor() noexcept { - log_v2::tcp()->trace("acceptor destroyed"); + auto logger = log_v2::instance().get(log_v2::TCP); + logger->trace("acceptor destroyed"); if (_acceptor) { tcp_async::instance().stop_acceptor(_acceptor); } @@ -73,7 +84,8 @@ std::shared_ptr acceptor::open() { auto conn = tcp_async::instance().get_connection(_acceptor, timeout_s); if (conn) { assert(conn->port()); - log_v2::tcp()->info("acceptor gets a new connection from {}", conn->peer()); + auto logger = log_v2::instance().get(log_v2::TCP); + logger->info("acceptor gets a new connection from {}", conn->peer()); add_child(conn->peer()); return std::make_shared(conn, _conf); } diff --git a/broker/tcp/src/connector.cc b/broker/tcp/src/connector.cc index f97dbcd713b..e957eaf1097 100644 --- a/broker/tcp/src/connector.cc +++ b/broker/tcp/src/connector.cc @@ -21,12 +21,22 @@ #include -#include "com/centreon/broker/log_v2.hh" +#include "bbdo/events.hh" +#include "com/centreon/broker/multiplexing/muxer_filter.hh" #include "com/centreon/broker/tcp/stream.hh" #include "com/centreon/broker/tcp/tcp_async.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::tcp; +using log_v2 = com::centreon::common::log_v2::log_v2; + +static constexpr multiplexing::muxer_filter _tcp_stream_filter = + multiplexing::muxer_filter(multiplexing::muxer_filter::zero_init()); + +static constexpr multiplexing::muxer_filter _tcp_forbidden_filter = + multiplexing::muxer_filter(multiplexing::muxer_filter::zero_init()) + .add_category(io::local); /** * @brief Constructor of the connector that will connect to the given host at @@ -37,12 +47,8 @@ using namespace com::centreon::broker::tcp; * @param read_timeout The read timeout in seconds or -1 if no duration. */ connector::connector(const tcp_config::pointer& conf) - : io::limit_endpoint(false, {}), _conf(conf) {} - -/** - * Destructor. - */ -connector::~connector() {} + : io::limit_endpoint(false, _tcp_stream_filter, _tcp_forbidden_filter), + _conf(conf) {} /** * @brief Connect to the remote host. @@ -50,13 +56,15 @@ connector::~connector() {} * @return The TCP connection object. */ std::shared_ptr connector::open() { + auto logger = log_v2::instance().get(log_v2::TCP); + // Launch connection process. - log_v2::tcp()->info("TCP: connecting to {}:{}", _conf->get_host(), - _conf->get_port()); + logger->info("TCP: connecting to {}:{}", _conf->get_host(), + _conf->get_port()); try { return limit_endpoint::open(); } catch (const std::exception& e) { - log_v2::tcp()->debug( + logger->debug( "Unable to establish the connection to {}:{} (attempt {}): {}", _conf->get_host(), _conf->get_port(), _is_ready_count, e.what()); return nullptr; diff --git a/broker/tcp/src/factory.cc b/broker/tcp/src/factory.cc index 9a368560359..edcd0959c28 100644 --- a/broker/tcp/src/factory.cc +++ b/broker/tcp/src/factory.cc @@ -1,5 +1,5 @@ /** - * Copyright 2011 - 2019-2022 Centreon (https://www.centreon.com/) + * Copyright 2011 - 2019-2024 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,15 +22,16 @@ #include #include "com/centreon/broker/config/parser.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/tcp/acceptor.hh" #include "com/centreon/broker/tcp/connector.hh" #include "com/centreon/broker/tcp/tcp_async.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::tcp; using namespace com::centreon::exceptions; +using com::centreon::common::log_v2::log_v2; /** * Check if a configuration supports this protocol. @@ -76,6 +77,8 @@ io::endpoint* factory::new_endpoint( std::shared_ptr cache) const { (void)cache; + auto logger = log_v2::instance().get(log_v2::TCP); + if (cfg.type == "bbdo_server" || cfg.type == "bbdo_client") return _new_endpoint_bbdo_cs(cfg, is_acceptor); @@ -87,7 +90,7 @@ io::endpoint* factory::new_endpoint( host = it->second; if (!host.empty() && (std::isspace(host[0]) || std::isspace(host[host.size() - 1]))) { - log_v2::tcp()->error( + logger->error( "TCP: 'host' must be a string matching a host, not beginning or " "ending with spaces for endpoint {}, it contains '{}'", cfg.name, host); @@ -101,12 +104,12 @@ io::endpoint* factory::new_endpoint( uint16_t port; it = cfg.params.find("port"); if (it == cfg.params.end()) { - log_v2::tcp()->error("TCP: no 'port' defined for endpoint '{}'", cfg.name); + logger->error("TCP: no 'port' defined for endpoint '{}'", cfg.name); throw msg_fmt("TCP: no 'port' defined for endpoint '{}'", cfg.name); } uint32_t port32; if (!absl::SimpleAtoi(it->second, &port32)) { - log_v2::tcp()->error( + logger->error( "TCP: 'port' must be an integer and not '{}' for endpoint '{}'", it->second, cfg.name); throw msg_fmt("TCP: invalid port value '{}' defined for endpoint '{}'", @@ -122,7 +125,7 @@ io::endpoint* factory::new_endpoint( it = cfg.params.find("socket_read_timeout"); if (it != cfg.params.end()) { if (!absl::SimpleAtoi(it->second, &read_timeout)) { - log_v2::tcp()->error( + logger->error( "TCP: 'socket_read_timeout' must be an integer and not '{}' for " "endpoint '{}'", it->second, cfg.name); @@ -138,7 +141,7 @@ io::endpoint* factory::new_endpoint( it = cfg.params.find("keepalive_count"); if (it != cfg.params.end()) { if (!absl::SimpleAtoi(it->second, &keepalive_count)) { - log_v2::tcp()->error( + logger->error( "TCP: 'keepalive_count' field should be an integer and not '{}'", it->second); throw msg_fmt( @@ -151,7 +154,7 @@ io::endpoint* factory::new_endpoint( it = cfg.params.find("keepalive_interval"); if (it != cfg.params.end()) { if (!absl::SimpleAtoi(it->second, &keepalive_interval)) { - log_v2::tcp()->error( + logger->error( "TCP: 'keepalive_interval' field should be an integer and not '{}'", it->second); throw msg_fmt( @@ -192,6 +195,8 @@ io::endpoint* factory::_new_endpoint_bbdo_cs( bool& is_acceptor) const { std::map::const_iterator it; + auto logger = log_v2::instance().get(log_v2::TCP); + // Find host (if exists). std::string host; it = cfg.params.find("host"); @@ -199,7 +204,7 @@ io::endpoint* factory::_new_endpoint_bbdo_cs( host = it->second; if (!host.empty() && (std::isspace(host[0]) || std::isspace(host[host.size() - 1]))) { - log_v2::grpc()->error( + logger->error( "TCP: 'host' must be a string matching a host, not beginning or " "ending with spaces for endpoint {}, it contains '{}'", cfg.name, host); @@ -212,7 +217,7 @@ io::endpoint* factory::_new_endpoint_bbdo_cs( if (cfg.type == "bbdo_server") host = "0.0.0.0"; else { - log_v2::tcp()->error("TCP: you must specify a host to connect to."); + logger->error("TCP: you must specify a host to connect to."); throw msg_fmt("TCP: you must specify a host to connect to."); } } @@ -221,22 +226,21 @@ io::endpoint* factory::_new_endpoint_bbdo_cs( uint16_t port; it = cfg.params.find("port"); if (it == cfg.params.end()) { - log_v2::grpc()->error("TCP: no 'port' defined for endpoint '{}'", cfg.name); + logger->error("TCP: no 'port' defined for endpoint '{}'", cfg.name); throw msg_fmt("TCP: no 'port' defined for endpoint '{}'", cfg.name); } { uint32_t port32; if (!absl::SimpleAtoi(it->second, &port32)) { - log_v2::grpc()->error( + logger->error( "TCP: 'port' must be an integer and not '{}' for endpoint '{}'", it->second, cfg.name); throw msg_fmt("TCP: invalid port value '{}' defined for endpoint '{}'", it->second, cfg.name); } if (port32 > 65535) { - log_v2::tcp()->error( - "TCP: invalid port value '{}' defined for endpoint '{}'", it->second, - cfg.name); + logger->error("TCP: invalid port value '{}' defined for endpoint '{}'", + it->second, cfg.name); throw msg_fmt("TCP: invalid port value '{}' defined for endpoint '{}'", it->second, cfg.name); } else @@ -246,7 +250,7 @@ io::endpoint* factory::_new_endpoint_bbdo_cs( // Find authorization token (if exists). it = cfg.params.find("authorization"); if (it != cfg.params.end()) { - log_v2::tcp()->error( + logger->error( "TCP: 'authorization' token works only with gRPC transport protocol, " "you should fix that"); throw msg_fmt( @@ -258,9 +262,8 @@ io::endpoint* factory::_new_endpoint_bbdo_cs( it = cfg.params.find("retention"); if (it != cfg.params.end()) { if (!absl::SimpleAtob(it->second, &enable_retention)) { - log_v2::tcp()->error( - "TCP: 'retention' field should be a boolean and not '{}'", - it->second); + logger->error("TCP: 'retention' field should be a boolean and not '{}'", + it->second); throw msg_fmt("TCP: 'retention' field should be a boolean and not '{}'", it->second); } @@ -280,7 +283,7 @@ io::endpoint* factory::_new_endpoint_bbdo_cs( it = cfg.params.find("keepalive_count"); if (it != cfg.params.end()) { if (!absl::SimpleAtoi(it->second, &keepalive_count)) { - log_v2::tcp()->error( + logger->error( "TCP: 'keepalive_count' field should be an integer and not '{}'", it->second); throw msg_fmt( @@ -293,7 +296,7 @@ io::endpoint* factory::_new_endpoint_bbdo_cs( it = cfg.params.find("keepalive_interval"); if (it != cfg.params.end()) { if (!absl::SimpleAtoi(it->second, &keepalive_interval)) { - log_v2::tcp()->error( + logger->error( "TCP: 'keepalive_interval' field should be an integer and not '{}'", it->second); throw msg_fmt( diff --git a/broker/tcp/src/main.cc b/broker/tcp/src/main.cc index 9cff5b710ee..6c7eaf6135f 100644 --- a/broker/tcp/src/main.cc +++ b/broker/tcp/src/main.cc @@ -17,11 +17,12 @@ * */ #include "com/centreon/broker/io/protocols.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/tcp/factory.hh" #include "com/centreon/broker/tcp/tcp_async.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; +using log_v2 = com::centreon::common::log_v2::log_v2; // Load count. static uint32_t instances(0); @@ -63,11 +64,11 @@ bool broker_module_deinit() { void broker_module_init(void const* arg) { (void)arg; + auto logger = log_v2::instance().get(log_v2::TCP); // Increment instance number. if (!instances++) { // TCP module. - log_v2::tcp()->info("TCP: module for Centreon Broker {}", - CENTREON_BROKER_VERSION); + logger->info("TCP: module for Centreon Broker {}", CENTREON_BROKER_VERSION); // Register TCP protocol. auto f = std::make_shared(); diff --git a/broker/tcp/src/stream.cc b/broker/tcp/src/stream.cc index 5527fb67d5c..c3f3bf835da 100644 --- a/broker/tcp/src/stream.cc +++ b/broker/tcp/src/stream.cc @@ -25,15 +25,16 @@ #include #include "com/centreon/broker/io/raw.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/tcp/acceptor.hh" #include "com/centreon/broker/tcp/tcp_async.hh" #include "com/centreon/common/pool.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::tcp; using namespace com::centreon::exceptions; +using log_v2 = com::centreon::common::log_v2::log_v2; std::atomic stream::_total_tcp_count{0}; @@ -50,15 +51,14 @@ stream::stream(const tcp_config::pointer& conf) : io::stream("TCP"), _conf(conf), _connection(tcp_async::instance().create_connection(_conf)), - _parent(nullptr) { + _parent(nullptr), + _logger{log_v2::instance().get(log_v2::TCP)} { assert(_connection->port()); _total_tcp_count++; - log_v2::tcp()->trace("New stream to {}:{}", _conf->get_host(), - _conf->get_port()); - log_v2::tcp()->info( - "{} TCP streams are configured on a thread pool of {} threads", - static_cast(_total_tcp_count), - com::centreon::common::pool::instance().get_pool_size()); + _logger->trace("New stream to {}:{}", _conf->get_host(), _conf->get_port()); + _logger->info("{} TCP streams are configured on a thread pool of {} threads", + static_cast(_total_tcp_count), + com::centreon::common::pool::instance().get_pool_size()); } /** @@ -70,15 +70,17 @@ stream::stream(const tcp_config::pointer& conf) */ stream::stream(const tcp_connection::pointer& conn, const tcp_config::pointer& conf) - : io::stream("TCP"), _conf(conf), _connection(conn), _parent(nullptr) { + : io::stream("TCP"), + _conf(conf), + _connection(conn), + _parent(nullptr), + _logger{log_v2::instance().get(log_v2::TCP)} { assert(_connection->port()); _total_tcp_count++; - log_v2::tcp()->info("New stream to {}:{}", _conf->get_host(), - _conf->get_port()); - log_v2::tcp()->info( - "{} TCP streams are configured on a thread pool of {} threads", - static_cast(_total_tcp_count), - com::centreon::common::pool::instance().get_pool_size()); + _logger->info("New stream to {}:{}", _conf->get_host(), _conf->get_port()); + _logger->info("{} TCP streams are configured on a thread pool of {} threads", + static_cast(_total_tcp_count), + com::centreon::common::pool::instance().get_pool_size()); } /** @@ -86,12 +88,12 @@ stream::stream(const tcp_connection::pointer& conn, */ stream::~stream() noexcept { _total_tcp_count--; - log_v2::tcp()->info( + _logger->info( "TCP stream destroyed. Still {} configured on a thread pool of {} " "threads", static_cast(_total_tcp_count), com::centreon::common::pool::instance().get_pool_size()); - log_v2::tcp()->trace("stream closed"); + _logger->trace("stream closed"); if (_connection->socket().is_open()) _connection->close(); @@ -117,7 +119,7 @@ std::string stream::peer() const { * @return Respects io::stream::read()'s return value. */ bool stream::read(std::shared_ptr& d, time_t deadline) { - log_v2::tcp()->trace("read on stream"); + _logger->trace("read on stream"); // Set deadline. { @@ -136,7 +138,7 @@ bool stream::read(std::shared_ptr& d, time_t deadline) { bool timeout = false; d.reset(new io::raw(_connection->read(deadline, &timeout))); std::shared_ptr data{std::static_pointer_cast(d)}; - log_v2::tcp()->trace("TCP Read done : {} bytes", data->get_buffer().size()); + _logger->trace("TCP Read done : {} bytes", data->get_buffer().size()); return !timeout; } @@ -158,7 +160,7 @@ int32_t stream::stop() { try { retval = flush(); } catch (const std::exception& e) { - log_v2::tcp()->error("tcp: error during stop: {}", e.what()); + _logger->error("tcp: error during stop: {}", e.what()); } return retval; } @@ -171,7 +173,7 @@ int32_t stream::stop() { * @return Number of events acknowledged. */ int32_t stream::write(std::shared_ptr const& d) { - log_v2::tcp()->trace("write event of type {} on tcp stream", d->type()); + _logger->trace("write event of type {} on tcp stream", d->type()); // Check that data exists and should be processed. assert(d); @@ -180,13 +182,13 @@ int32_t stream::write(std::shared_ptr const& d) { if (d->type() == io::raw::static_type()) { std::shared_ptr r(std::static_pointer_cast(d)); - log_v2::tcp()->trace("TCP: write request of {} bytes to peer '{}:{}'", - r->size(), _conf->get_host(), _conf->get_port()); - log_v2::tcp()->trace("write {} bytes", r->size()); + _logger->trace("TCP: write request of {} bytes to peer '{}:{}'", r->size(), + _conf->get_host(), _conf->get_port()); + _logger->trace("write {} bytes", r->size()); try { return _connection->write(r->get_buffer()); } catch (std::exception const& e) { - log_v2::tcp()->error("Socket gone"); + _logger->error("Socket gone"); throw; } } diff --git a/broker/tcp/src/tcp_async.cc b/broker/tcp/src/tcp_async.cc index 7b9093a7be3..ee1e2df9e23 100644 --- a/broker/tcp/src/tcp_async.cc +++ b/broker/tcp/src/tcp_async.cc @@ -1,5 +1,5 @@ /** - * Copyright 2020-2021 Centreon + * Copyright 2020-2024 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,13 +17,14 @@ */ #include "com/centreon/broker/tcp/tcp_async.hh" -#include "com/centreon/broker/log_v2.hh" -#include "com/centreon/common/pool.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" +#include "com/centreon/common/pool.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::tcp; +using log_v2 = com::centreon::common::log_v2::log_v2; /** * @brief this option set the interval in seconds between two keepalive sent @@ -75,8 +76,10 @@ tcp_async& tcp_async::instance() { void tcp_async::load() { if (!_instance) _instance = std::shared_ptr(new tcp_async); - else - log_v2::tcp()->error("tcp_async instance already started."); + else { + auto logger = log_v2::instance().get(log_v2::TCP); + logger->error("tcp_async instance already started."); + } } /** @@ -95,13 +98,15 @@ void tcp_async::unload() { * tcp_async::load() function to initialize it and then, use the instance() * method. */ -tcp_async::tcp_async() : _clear_available_con_running(false) {} +tcp_async::tcp_async() + : _clear_available_con_running(false), + _logger{log_v2::instance().get(log_v2::TCP)} {} /** * @brief Stop the timer that clears available connections. */ void tcp_async::stop_timer() { - log_v2::tcp()->trace("tcp_async::stop_timer"); + _logger->trace("tcp_async::stop_timer"); { std::lock_guard l(_acceptor_available_con_m); if (_clear_available_con_running) { @@ -170,15 +175,15 @@ std::shared_ptr tcp_async::create_acceptor( boost::system::error_code ec; asio::ip::tcp::resolver::iterator it = resolver.resolve(query, ec), end; if (ec) { - log_v2::tcp()->error("TCP: error while resolving '{}' name: {}", - conf->get_host(), ec.message()); + _logger->error("TCP: error while resolving '{}' name: {}", + conf->get_host(), ec.message()); listen_endpoint = asio::ip::tcp::endpoint(asio::ip::tcp::v4(), conf->get_port()); } else { for (; it != end; ++it) { listen_endpoint = *it; - log_v2::tcp()->info("TCP: {} gives address {}", conf->get_host(), - listen_endpoint.address().to_string()); + _logger->info("TCP: {} gives address {}", conf->get_host(), + listen_endpoint.address().to_string()); if (listen_endpoint.address().is_v4()) break; } @@ -199,17 +204,23 @@ std::shared_ptr tcp_async::create_acceptor( */ void tcp_async::_clear_available_con(boost::system::error_code ec) { if (ec) - log_v2::core()->info("Available connections cleaning: {}", ec.message()); + log_v2::instance() + .get(log_v2::CORE) + ->info("Available connections cleaning: {}", ec.message()); else { std::lock_guard l(_acceptor_available_con_m); if (_clear_available_con_running) { - log_v2::core()->debug("Available connections cleaning"); + log_v2::instance() + .get(log_v2::CORE) + ->debug("Available connections cleaning"); std::time_t now = std::time(nullptr); for (auto it = _acceptor_available_con.begin(); it != _acceptor_available_con.end();) { if (now >= it->second.second + 10) { - log_v2::tcp()->debug("Destroying connection to '{}'", - it->second.first->peer()); + log_v2::instance() + .get(log_v2::TCP) + ->debug("Destroying connection to '{}'", + it->second.first->peer()); it = _acceptor_available_con.erase(it); } else ++it; @@ -221,7 +232,9 @@ void tcp_async::_clear_available_con(boost::system::error_code ec) { } else _clear_available_con_running = false; } else - log_v2::core()->debug("Available connections cleaner already stopped"); + log_v2::instance() + .get(log_v2::CORE) + ->debug("Available connections cleaner already stopped"); } } @@ -235,7 +248,7 @@ void tcp_async::_clear_available_con(boost::system::error_code ec) { void tcp_async::start_acceptor( const std::shared_ptr& acceptor, const tcp_config::pointer& conf) { - log_v2::tcp()->trace("Start acceptor"); + _logger->trace("Start acceptor"); std::lock_guard l(_acceptor_available_con_m); if (!_timer) _timer = std::make_unique( @@ -244,7 +257,7 @@ void tcp_async::start_acceptor( if (!_clear_available_con_running) _clear_available_con_running = true; - log_v2::tcp()->debug("Reschedule available connections cleaning in 10s"); + _logger->debug("Reschedule available connections cleaning in 10s"); _timer->expires_after(std::chrono::seconds(10)); _timer->async_wait( [me = shared_from_this()](const boost::system::error_code& err) { @@ -252,9 +265,9 @@ void tcp_async::start_acceptor( }); tcp_connection::pointer new_connection = std::make_shared( - com::centreon::common::pool::io_context()); + com::centreon::common::pool::io_context(), _logger); - log_v2::tcp()->debug("Waiting for a connection"); + _logger->debug("Waiting for a connection"); acceptor->async_accept(new_connection->socket(), [this, acceptor, new_connection, conf](const boost::system::error_code& ec) { @@ -269,15 +282,16 @@ void tcp_async::start_acceptor( */ void tcp_async::stop_acceptor( std::shared_ptr acceptor) { - log_v2::tcp()->debug("stop acceptor"); + auto logger = log_v2::instance().get(log_v2::TCP); + logger->debug("stop acceptor"); std::lock_guard l(_acceptor_available_con_m); boost::system::error_code ec; acceptor->cancel(ec); if (ec) - log_v2::tcp()->warn("Error while cancelling acceptor: {}", ec.message()); + logger->warn("Error while cancelling acceptor: {}", ec.message()); acceptor->close(ec); if (ec) - log_v2::tcp()->warn("Error while closing acceptor: {}", ec.message()); + logger->warn("Error while closing acceptor: {}", ec.message()); } /** @@ -292,17 +306,18 @@ void tcp_async::handle_accept(std::shared_ptr acceptor, const boost::system::error_code& ec, const tcp_config::pointer& conf) { /* If we got a connection, we store it */ + auto logger = log_v2::instance().get(log_v2::TCP); if (!ec) { boost::system::error_code ecc; new_connection->update_peer(ecc); if (ecc) - log_v2::tcp()->error( + logger->error( "tcp acceptor handling connection: unable to get peer endpoint: {}", ecc.message()); else { std::time_t now = std::time(nullptr); asio::ip::tcp::socket& sock = new_connection->socket(); - _set_sock_opt(sock, conf); + _set_sock_opt(sock, conf, _logger); { std::lock_guard l(_acceptor_available_con_m); _acceptor_available_con.insert(std::make_pair( @@ -312,7 +327,7 @@ void tcp_async::handle_accept(std::shared_ptr acceptor, start_acceptor(acceptor, conf); } } else - log_v2::tcp()->info("TCP acceptor interrupted: {}", ec.message()); + logger->info("TCP acceptor interrupted: {}", ec.message()); } /** @@ -325,11 +340,11 @@ void tcp_async::handle_accept(std::shared_ptr acceptor, */ tcp_connection::pointer tcp_async::create_connection( const tcp_config::pointer& conf) { - log_v2::tcp()->trace("create connection to host {}:{}", conf->get_host(), - conf->get_port()); + auto logger = log_v2::instance().get(log_v2::TCP); + logger->trace("create connection to host {}:{}", conf->get_host(), + conf->get_port()); tcp_connection::pointer conn = std::make_shared( - com::centreon::common::pool::io_context(), conf->get_host(), - conf->get_port()); + com::centreon::common::pool::io_context(), _logger, conf->get_host(), conf->get_port()); asio::ip::tcp::socket& sock = conn->socket(); asio::ip::tcp::resolver resolver(com::centreon::common::pool::io_context()); @@ -350,21 +365,22 @@ tcp_connection::pointer tcp_async::create_connection( /* Connection refused */ if (err.value() == 111) { - log_v2::tcp()->error("TCP: Connection refused to {}:{}", conf->get_host(), - conf->get_port()); + logger->error("TCP: Connection refused to {}:{}", conf->get_host(), + conf->get_port()); throw std::system_error(err); } else if (err) { - log_v2::tcp()->error("TCP: could not connect to {}:{}", conf->get_host(), - conf->get_port()); + logger->error("TCP: could not connect to {}:{}", conf->get_host(), + conf->get_port()); throw msg_fmt(err.message()); } else { - _set_sock_opt(sock, conf); + _set_sock_opt(sock, conf, _logger); return conn; } } void tcp_async::_set_sock_opt(asio::ip::tcp::socket& sock, - const tcp_config::pointer& conf) { + const tcp_config::pointer& conf, + const std::shared_ptr& logger) { asio::socket_base::keep_alive option1(true); tcp_keep_alive_cnt option2(conf->get_keepalive_count()); tcp_keep_alive_idle option3(conf->get_second_keepalive_interval()); @@ -374,27 +390,26 @@ void tcp_async::_set_sock_opt(asio::ip::tcp::socket& sock, boost::system::error_code err; sock.set_option(option1, err); if (err) { - SPDLOG_LOGGER_ERROR(log_v2::tcp(), "fail to set keepalive option {}", + SPDLOG_LOGGER_ERROR(logger, "fail to set keepalive option {}", err.message()); } else { sock.set_option(option2, err); if (err) { - SPDLOG_LOGGER_ERROR(log_v2::tcp(), "fail to set keepalive cnt {}", + SPDLOG_LOGGER_ERROR(logger, "fail to set keepalive cnt {}", err.message()); } sock.set_option(option3, err); if (err) { - SPDLOG_LOGGER_ERROR(log_v2::tcp(), "fail to set keepalive idle {}", + SPDLOG_LOGGER_ERROR(logger, "fail to set keepalive idle {}", err.message()); } sock.set_option(option4, err); if (err) { - SPDLOG_LOGGER_ERROR(log_v2::tcp(), "fail to set keepalive interval {}", + SPDLOG_LOGGER_ERROR(logger, "fail to set keepalive interval {}", err.message()); } } sock.set_option(option5, err); - if (err) { - SPDLOG_LOGGER_ERROR(log_v2::tcp(), "fail to set keepalive option"); - } + if (err) + SPDLOG_LOGGER_ERROR(logger, "fail to set keepalive option"); } diff --git a/broker/tcp/src/tcp_connection.cc b/broker/tcp/src/tcp_connection.cc index 5c6f2476c18..b029f1f6b82 100644 --- a/broker/tcp/src/tcp_connection.cc +++ b/broker/tcp/src/tcp_connection.cc @@ -1,5 +1,5 @@ /** - * Copyright 2020-2021 Centreon + * Copyright 2020-2024 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,13 +18,14 @@ #include "com/centreon/broker/tcp/tcp_connection.hh" #include "com/centreon/broker/exceptions/connection_closed.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/string.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker::tcp; using com::centreon::broker::misc::string::debug_buf; +using log_v2 = com::centreon::common::log_v2::log_v2; static const boost::system::error_code _eof_error = boost::asio::error::make_error_code(boost::asio::error::misc_errors::eof); @@ -40,6 +41,7 @@ static const boost::system::error_code _eof_error = * side and no connection has been established yet. */ tcp_connection::tcp_connection(asio::io_context& io_context, + const std::shared_ptr& logger, const std::string& host, uint16_t port) : _socket(io_context), @@ -51,13 +53,14 @@ tcp_connection::tcp_connection(asio::io_context& io_context, _closing(false), _closed(false), _address(host), - _port(port) {} + _port(port), + _logger{logger} {} /** * @brief Destructor */ tcp_connection::~tcp_connection() noexcept { - log_v2::tcp()->trace("Connection to {}:{} destroyed.", _address, _port); + _logger->trace("Connection to {}:{} destroyed.", _address, _port); close(); } @@ -163,8 +166,8 @@ int32_t tcp_connection::write(const std::vector& v) { * @return false if timeout expires */ bool tcp_connection::wait_for_all_events_written(unsigned ms_timeout) { - log_v2::tcp()->trace("wait_for_all_events_written _writing={}", - static_cast(_writing)); + _logger->trace("wait_for_all_events_written _writing={}", + static_cast(_writing)); std::mutex dummy; std::unique_lock l(dummy); return _writing_cv.wait_for(l, std::chrono::milliseconds(ms_timeout), @@ -206,10 +209,10 @@ void tcp_connection::writing() { void tcp_connection::handle_write(const boost::system::error_code& ec) { if (ec) { if (ec == _eof_error) - log_v2::tcp()->debug("write: socket closed: {}", _address); + _logger->debug("write: socket closed: {}", _address); else - log_v2::tcp()->error("Error while writing on tcp socket to {}: {}", - _address, ec.message()); + _logger->error("Error while writing on tcp socket to {}: {}", _address, + ec.message()); std::lock_guard lck(_error_m); _current_error = ec; _writing = false; @@ -248,8 +251,8 @@ void tcp_connection::start_reading() { void tcp_connection::handle_read(const boost::system::error_code& ec, size_t read_bytes) { - log_v2::tcp()->trace("Incoming data: {} bytes: {}", read_bytes, - debug_buf(&_read_buffer[0], read_bytes)); + _logger->trace("Incoming data: {} bytes: {}", read_bytes, + debug_buf(&_read_buffer[0], read_bytes)); if (read_bytes > 0) { std::lock_guard lock(_read_queue_m); _read_queue.emplace(_read_buffer.begin(), @@ -258,10 +261,10 @@ void tcp_connection::handle_read(const boost::system::error_code& ec, } if (ec) { if (ec == _eof_error) - log_v2::tcp()->debug("read: socket closed: {}", _address); + _logger->debug("read: socket closed: {}", _address); else - log_v2::tcp()->error("Error while reading on socket from {}: {}", - _address, ec.message()); + _logger->error("Error while reading on socket from {}: {}", _address, + ec.message()); std::lock_guard lck(_read_queue_m); _closing = true; _read_queue_cv.notify_one(); @@ -274,15 +277,14 @@ void tcp_connection::handle_read(const boost::system::error_code& ec, * before the socket to be closed. */ void tcp_connection::close() { - log_v2::tcp()->trace("closing tcp connection"); + _logger->trace("closing tcp connection"); if (!_closed) { std::chrono::system_clock::time_point timeout = std::chrono::system_clock::now() + std::chrono::seconds(10); while (!_closed && (_writing || (_write_queue_has_events && std::chrono::system_clock::now() < timeout))) { - log_v2::tcp()->debug( - "Finishing to write data before closing the connection"); + _logger->debug("Finishing to write data before closing the connection"); if (!_writing) { _writing = true; // The strand is useful because of the flush() method. @@ -293,9 +295,9 @@ void tcp_connection::close() { _closed = true; boost::system::error_code ec; _socket.shutdown(asio::ip::tcp::socket::shutdown_both, ec); - log_v2::tcp()->trace("socket shutdown with message: {}", ec.message()); + _logger->trace("socket shutdown with message: {}", ec.message()); _socket.close(ec); - log_v2::tcp()->trace("socket closed with message: {}", ec.message()); + _logger->trace("socket closed with message: {}", ec.message()); } } @@ -330,8 +332,7 @@ std::vector tcp_connection::read(time_t timeout_time, bool* timeout) { std::swap(_exposed_read_queue, _read_queue); } - log_v2::tcp()->warn( - "Socket is closed. Trying to read the end of its buffer"); + _logger->warn("Socket is closed. Trying to read the end of its buffer"); if (!_exposed_read_queue.empty()) { retval = std::move(_exposed_read_queue.front()); _exposed_read_queue.pop(); @@ -364,8 +365,8 @@ std::vector tcp_connection::read(time_t timeout_time, bool* timeout) { "Attempt to read data from peer {}:{} on a closing socket", _address, _port); } else { - log_v2::tcp()->trace("Timeout during read ; timeout time = {}", - timeout_time); + _logger->trace("Timeout during read ; timeout time = {}", + timeout_time); *timeout = true; return retval; } diff --git a/broker/tcp/test/acceptor.cc b/broker/tcp/test/acceptor.cc index 06a587b1f85..f56cc8cfefa 100644 --- a/broker/tcp/test/acceptor.cc +++ b/broker/tcp/test/acceptor.cc @@ -25,14 +25,15 @@ #include #include "com/centreon/broker/io/raw.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/tcp/connector.hh" #include "com/centreon/broker/tcp/tcp_async.hh" #include "com/centreon/common/pool.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::exceptions; +using com::centreon::common::log_v2::log_v2; const static std::string test_addr("127.0.0.1"); @@ -43,14 +44,18 @@ static tcp::tcp_config::pointer test_conf2( std::make_shared(test_addr, 4141)); class TcpAcceptor : public ::testing::Test { + protected: + std::shared_ptr _logger; + public: void SetUp() override { - log_v2::tcp()->set_level(spdlog::level::debug); + _logger = log_v2::instance().get(log_v2::TCP); + _logger->set_level(spdlog::level::info); tcp::tcp_async::load(); } void TearDown() override { - log_v2::tcp()->info("TCP TearDown"); + _logger->info("TCP TearDown"); tcp::tcp_async::instance().stop_timer(); tcp::tcp_async::unload(); } diff --git a/broker/test/CMakeLists.txt b/broker/test/CMakeLists.txt index 7e7dd8da3b2..00a11a96c49 100644 --- a/broker/test/CMakeLists.txt +++ b/broker/test/CMakeLists.txt @@ -16,8 +16,6 @@ # For more information : contact@centreon.com # -include_directories(${CONAN_INCLUDE_DIRS_GTEST}) - # Tests directory. set(TESTS_DIR ${PROJECT_SOURCE_DIR}/core/test) set(BAM_TESTS_DIR ${PROJECT_SOURCE_DIR}/bam/test) @@ -77,8 +75,12 @@ target_link_libraries( centreon_common spdlog::spdlog -L${PROTOBUF_LIB_DIR} - gRPC::gpr gRPC::grpc gRPC::grpc++ gRPC::grpc++_alts - crypto ssl + gRPC::gpr + gRPC::grpc + gRPC::grpc++ + gRPC::grpc++_alts + crypto + ssl z dl pthread) @@ -131,31 +133,42 @@ add_executable( # Module sources. ${TESTS_SOURCES}) +message(STATUS "###################################") +message(STATUS "###################################") +message(STATUS ${TESTS_SOURCES}) +message(STATUS "###################################") +message(STATUS "###################################") + target_link_libraries( - ut_broker PRIVATE - test_util - roker - rokerbase - rokerlog - multiplexing - ${TESTS_LIBRARIES} - conflictmgr - centreon_common - stdc++fs - nlohmann_json::nlohmann_json - fmt::fmt - spdlog::spdlog - GTest::gtest GTest::gtest_main GTest::gmock GTest::gmock_main - mariadb - crypto ssl - gRPC::gpr gRPC::grpc gRPC::grpc++ gRPC::grpc++_alts) + ut_broker + PRIVATE test_util + roker + rokerbase + multiplexing + ${TESTS_LIBRARIES} + conflictmgr + centreon_common + stdc++fs + nlohmann_json::nlohmann_json + fmt::fmt + log_v2 + GTest::gtest + GTest::gtest_main + GTest::gmock + GTest::gmock_main + mariadb + crypto + ssl + gRPC::gpr + gRPC::grpc + gRPC::grpc++ + gRPC::grpc++_alts) add_dependencies( ut_broker test_util roker rokerbase - rokerlog multiplexing conflictmgr centreon_common) diff --git a/broker/tls/inc/com/centreon/broker/tls/acceptor.hh b/broker/tls/inc/com/centreon/broker/tls/acceptor.hh index 9bd3868c569..8fa7e28535a 100644 --- a/broker/tls/inc/com/centreon/broker/tls/acceptor.hh +++ b/broker/tls/inc/com/centreon/broker/tls/acceptor.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2009-2013, 2021 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2009-2013, 2021-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_TLS_ACCEPTOR_HH #define CCB_TLS_ACCEPTOR_HH @@ -47,13 +47,13 @@ class acceptor : public io::endpoint { const std::string& ca = std::string(), const std::string& tls_hostname = std::string()); ~acceptor() = default; - acceptor(acceptor const& right) = delete; - acceptor& operator=(acceptor const&) = delete; + acceptor(const acceptor&) = delete; + acceptor& operator=(const acceptor&) = delete; std::shared_ptr open() override; std::shared_ptr open(const std::shared_ptr& lower); }; } // namespace tls -} +} // namespace com::centreon::broker #endif // !CCB_TLS_ACCEPTOR_HH diff --git a/broker/tls/inc/com/centreon/broker/tls/connector.hh b/broker/tls/inc/com/centreon/broker/tls/connector.hh index 73061e33e80..2dabc83bd78 100644 --- a/broker/tls/inc/com/centreon/broker/tls/connector.hh +++ b/broker/tls/inc/com/centreon/broker/tls/connector.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2009-2013, 2021 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2009-2013, 2021-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_TLS_CONNECTOR_HH #define CCB_TLS_CONNECTOR_HH @@ -49,6 +49,6 @@ class connector : public io::endpoint { }; } // namespace tls -} +} // namespace com::centreon::broker #endif // !CCB_TLS_CONNECTOR_HH diff --git a/broker/tls/inc/com/centreon/broker/tls/factory.hh b/broker/tls/inc/com/centreon/broker/tls/factory.hh index b3764ee217e..8763f90e735 100644 --- a/broker/tls/inc/com/centreon/broker/tls/factory.hh +++ b/broker/tls/inc/com/centreon/broker/tls/factory.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2013 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2013 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_TLS_FACTORY_HH #define CCB_TLS_FACTORY_HH @@ -49,6 +49,6 @@ class factory : public io::factory { }; } // namespace tls -} +} // namespace com::centreon::broker #endif // !CCB_TLS_FACTORY_HH diff --git a/broker/tls/inc/com/centreon/broker/tls/internal.hh b/broker/tls/inc/com/centreon/broker/tls/internal.hh index fa9fea08f97..da1eda26c61 100644 --- a/broker/tls/inc/com/centreon/broker/tls/internal.hh +++ b/broker/tls/inc/com/centreon/broker/tls/internal.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2009-2013 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2009-2013 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_TLS_INTERNAL_HH #define CCB_TLS_INTERNAL_HH @@ -36,6 +36,6 @@ ssize_t pull_helper(gnutls_transport_ptr_t ptr, void* data, size_t size); ssize_t push_helper(gnutls_transport_ptr_t ptr, void const* data, size_t size); } // namespace tls -} +} // namespace com::centreon::broker #endif // !CCB_TLS_INTERNAL_HH diff --git a/broker/tls/inc/com/centreon/broker/tls/params.hh b/broker/tls/inc/com/centreon/broker/tls/params.hh index cb7135b7623..fd374daa784 100644 --- a/broker/tls/inc/com/centreon/broker/tls/params.hh +++ b/broker/tls/inc/com/centreon/broker/tls/params.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2009-2013 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2009-2013 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_TLS_PARAMS_HH #define CCB_TLS_PARAMS_HH diff --git a/broker/tls/inc/com/centreon/broker/tls/stream.hh b/broker/tls/inc/com/centreon/broker/tls/stream.hh index 8b59b375ae9..57274cb75be 100644 --- a/broker/tls/inc/com/centreon/broker/tls/stream.hh +++ b/broker/tls/inc/com/centreon/broker/tls/stream.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2009-2013 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2009-2013 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_TLS_STREAM_HH #define CCB_TLS_STREAM_HH @@ -39,6 +39,7 @@ class stream : public io::stream { std::vector _buffer; time_t _deadline; gnutls_session_t _session; + std::shared_ptr _logger; public: stream(unsigned int session_flags); diff --git a/broker/tls/src/acceptor.cc b/broker/tls/src/acceptor.cc index 715202ca802..569f5d0081b 100644 --- a/broker/tls/src/acceptor.cc +++ b/broker/tls/src/acceptor.cc @@ -20,19 +20,15 @@ #include -#include "com/centreon/broker/log_v2.hh" +#include "com/centreon/broker/multiplexing/muxer_filter.hh" #include "com/centreon/broker/tls/stream.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::exceptions; using namespace com::centreon::broker::tls; - -/************************************** - * * - * Public Methods * - * * - **************************************/ +using log_v2 = com::centreon::common::log_v2::log_v2; /** * Default constructor. @@ -45,7 +41,10 @@ acceptor::acceptor(std::string const& cert, std::string const& key, std::string const& ca, std::string const& tls_hostname) - : io::endpoint(true, {}), + : io::endpoint( + true, + {}, + multiplexing::muxer_filter(multiplexing::muxer_filter::zero_init())), _ca(ca), _cert(cert), _key(key), @@ -87,6 +86,8 @@ std::shared_ptr acceptor::open( const std::shared_ptr& lower) { std::shared_ptr u; if (lower) { + auto logger = log_v2::instance().get(log_v2::TLS); + // Load parameters. params p(params::SERVER); p.set_cert(_cert, _key); diff --git a/broker/tls/src/connector.cc b/broker/tls/src/connector.cc index 4418c4d624d..67922acccaa 100644 --- a/broker/tls/src/connector.cc +++ b/broker/tls/src/connector.cc @@ -18,19 +18,15 @@ #include "com/centreon/broker/tls/connector.hh" -#include "com/centreon/broker/log_v2.hh" +#include "com/centreon/broker/multiplexing/muxer_filter.hh" #include "com/centreon/broker/tls/stream.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::tls; using namespace com::centreon::exceptions; - -/************************************** - * * - * Public Methods * - * * - **************************************/ +using log_v2 = com::centreon::common::log_v2::log_v2; /** * Default constructor @@ -43,7 +39,10 @@ connector::connector(std::string const& cert, std::string const& key, std::string const& ca, std::string const& tls_hostname) - : io::endpoint(false, {}), + : io::endpoint( + false, + {}, + multiplexing::muxer_filter(multiplexing::muxer_filter::zero_init())), _ca(ca), _cert(cert), _key(key), diff --git a/broker/tls/src/factory.cc b/broker/tls/src/factory.cc index eae3313f81a..67b4ed29352 100644 --- a/broker/tls/src/factory.cc +++ b/broker/tls/src/factory.cc @@ -1,31 +1,32 @@ /** -* Copyright 2013, 2022 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2013, 2022 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/tls/factory.hh" #include #include "com/centreon/broker/config/parser.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/tls/acceptor.hh" #include "com/centreon/broker/tls/connector.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::tls; +using log_v2 = com::centreon::common::log_v2::log_v2; /** * Check if an endpoint configuration match the TLS layer. @@ -44,6 +45,8 @@ bool factory::has_endpoint(config::endpoint& cfg, io::extension* ext) { std::map::iterator it; bool legacy; + auto logger = log_v2::instance().get(log_v2::TLS); + if (ext) { if (direct_grpc_serialized(cfg)) { return false; @@ -70,7 +73,7 @@ bool factory::has_endpoint(config::endpoint& cfg, io::extension* ext) { if (legacy && absl::EqualsIgnoreCase(it->second, "auto")) has_tls = true; else { - log_v2::tls()->error( + logger->error( "TLS: the field 'tls' in endpoint '{}' should be a boolean", cfg.name); has_tls = false; @@ -79,7 +82,7 @@ bool factory::has_endpoint(config::endpoint& cfg, io::extension* ext) { if (!has_tls) *ext = io::extension("TLS", false, false); else { - log_v2::tls()->info("Configuration of TLS for endpoint '{}'", cfg.name); + logger->info("Configuration of TLS for endpoint '{}'", cfg.name); if (absl::EqualsIgnoreCase(it->second, "auto")) *ext = io::extension("TLS", true, false); else @@ -130,6 +133,8 @@ io::endpoint* factory::new_endpoint( std::shared_ptr cache) const { (void)cache; + auto logger = log_v2::instance().get(log_v2::TLS); + // Find TLS parameters (optional). bool tls{false}; std::string private_key; @@ -142,7 +147,7 @@ io::endpoint* factory::new_endpoint( cfg.params.find("tls")}; if (it != cfg.params.end()) { if (!absl::SimpleAtob(it->second, &tls)) { - log_v2::tls()->error( + logger->error( "factory: cannot parse the 'tls' boolean: the content is '{}'", it->second); tls = false; diff --git a/broker/tls/src/internal.cc b/broker/tls/src/internal.cc index 5fc09236db6..337479d2934 100644 --- a/broker/tls/src/internal.cc +++ b/broker/tls/src/internal.cc @@ -26,19 +26,14 @@ #endif // GNU TLS < 3.0.0 #include "com/centreon/broker/io/raw.hh" #include "com/centreon/broker/io/stream.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/tls/internal.hh" #include "com/centreon/broker/tls/stream.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::exceptions; - -/************************************** - * * - * Global Objects * - * * - **************************************/ +using log_v2 = com::centreon::common::log_v2::log_v2; /** * Those 2048-bits wide Diffie-Hellman parameters were generated the @@ -81,25 +76,26 @@ void tls::initialize() { sizeof(dh_params_2048)}; int ret; + auto logger = log_v2::instance().get(log_v2::TLS); + // Eventually initialize libgcrypt. #if GNUTLS_VERSION_NUMBER < 0x030000 - log_v2::tls()->info("TLS: initializing libgcrypt (GNU TLS <= 2.11.0)"); + logger->info("TLS: initializing libgcrypt (GNU TLS <= 2.11.0)"); gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread); #endif // GNU TLS < 3.0.0 // Initialize GNU TLS library. if (gnutls_global_init() != GNUTLS_E_SUCCESS) { - log_v2::tls()->error("TLS: GNU TLS library initialization failed"); + logger->error("TLS: GNU TLS library initialization failed"); throw msg_fmt("TLS: GNU TLS library initialization failed"); } // Log GNU TLS version. { - log_v2::tls()->info("TLS: compiled with GNU TLS version {}", - GNUTLS_VERSION); + logger->info("TLS: compiled with GNU TLS version {}", GNUTLS_VERSION); char const* v(gnutls_check_version(GNUTLS_VERSION)); if (!v) { - log_v2::tls()->error( + logger->error( "TLS: GNU TLS run-time version is incompatible with the compile-time " "version ({}): please update your GNU TLS library", GNUTLS_VERSION); @@ -108,7 +104,7 @@ void tls::initialize() { "version ({}): please update your GNU TLS library", GNUTLS_VERSION); } - log_v2::tls()->info("TLS: loading GNU TLS version {}", v); + logger->info("TLS: loading GNU TLS version {}", v); // gnutls_global_set_log_function(log_gnutls_message); // gnutls_global_set_log_level(11); } @@ -116,16 +112,15 @@ void tls::initialize() { // Load Diffie-Hellman parameters. ret = gnutls_dh_params_init(&dh_params); if (ret != GNUTLS_E_SUCCESS) { - log_v2::tls()->error( - "TLS: could not load TLS Diffie-Hellman parameters: {}", - gnutls_strerror(ret)); + logger->error("TLS: could not load TLS Diffie-Hellman parameters: {}", + gnutls_strerror(ret)); throw msg_fmt("TLS: could not load TLS Diffie-Hellman parameters: {}", gnutls_strerror(ret)); } ret = gnutls_dh_params_import_pkcs3(dh_params, &dhp, GNUTLS_X509_FMT_PEM); if (ret != GNUTLS_E_SUCCESS) { - log_v2::tls()->error("TLS: could not import PKCS #3 parameters: ", - gnutls_strerror(ret)); + logger->error("TLS: could not import PKCS #3 parameters: ", + gnutls_strerror(ret)); throw msg_fmt("TLS: could not import PKCS #3 parameters: {}", gnutls_strerror(ret)); } @@ -139,7 +134,8 @@ ssize_t tls::pull_helper(gnutls_transport_ptr_t ptr, void* data, size_t size) { try { return static_cast(ptr)->read_encrypted(data, size); } catch (const std::exception& e) { - SPDLOG_LOGGER_DEBUG(log_v2::tls(), "read failed: {}", e.what()); + SPDLOG_LOGGER_DEBUG(log_v2::instance().get(log_v2::TLS), "read failed: {}", + e.what()); return -1; } } @@ -154,7 +150,8 @@ ssize_t tls::push_helper(gnutls_transport_ptr_t ptr, try { return static_cast(ptr)->write_encrypted(data, size); } catch (const std::exception& e) { - SPDLOG_LOGGER_DEBUG(log_v2::tls(), "write failed: {}", e.what()); + SPDLOG_LOGGER_DEBUG(log_v2::instance().get(log_v2::TLS), "write failed: {}", + e.what()); return -1; } } diff --git a/broker/tls/src/main.cc b/broker/tls/src/main.cc index a4d3ecdfbb1..2a2a62f0596 100644 --- a/broker/tls/src/main.cc +++ b/broker/tls/src/main.cc @@ -1,27 +1,28 @@ /** -* Copyright 2013 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2013 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/io/protocols.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/tls/factory.hh" #include "com/centreon/broker/tls/internal.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; +using log_v2 = com::centreon::common::log_v2::log_v2; // Load count. static uint32_t instances(0); @@ -55,11 +56,11 @@ bool broker_module_deinit() { void broker_module_init(void const* arg) { (void)arg; + auto logger = log_v2::instance().get(log_v2::TLS); // Increment instance number. if (!instances++) { // TLS module. - log_v2::tls()->info("TLS: module for Centreon Broker {}", - CENTREON_BROKER_VERSION); + logger->info("TLS: module for Centreon Broker {}", CENTREON_BROKER_VERSION); // Initialization. tls::initialize(); diff --git a/broker/tls/src/params.cc b/broker/tls/src/params.cc index 6d633964c32..ae171c62f08 100644 --- a/broker/tls/src/params.cc +++ b/broker/tls/src/params.cc @@ -1,32 +1,33 @@ /** -* Copyright 2009-2013,2021 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2009-2013,2021 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/tls/params.hh" #include -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/tls/internal.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::tls; using namespace com::centreon::exceptions; +using log_v2 = com::centreon::common::log_v2::log_v2; /** * Params constructor. @@ -50,7 +51,7 @@ params::~params() { * * @param[out] session Object on which parameters will be applied. */ -void params::apply(gnutls_session_t session)const { +void params::apply(gnutls_session_t session) const { // Set the encryption method (normal ciphers with anonymous // Diffie-Hellman and optionnally compression). int ret; @@ -63,9 +64,10 @@ void params::apply(gnutls_session_t session)const { "DEFLATE:%COMPAT"), nullptr); + auto logger = log_v2::instance().get(log_v2::TLS); if (ret != GNUTLS_E_SUCCESS) { - log_v2::tls()->error("TLS: encryption parameter application failed: {}", - gnutls_strerror(ret)); + logger->error("TLS: encryption parameter application failed: {}", + gnutls_strerror(ret)); throw msg_fmt("TLS: encryption parameter application failed: {}", gnutls_strerror(ret)); } @@ -73,23 +75,22 @@ void params::apply(gnutls_session_t session)const { // Set anonymous credentials... if (_cert.empty() || _key.empty()) { if (CLIENT == _type) { - log_v2::tls()->info("TLS: using anonymous client credentials"); + logger->info("TLS: using anonymous client credentials"); ret = gnutls_credentials_set(session, GNUTLS_CRD_ANON, _cred.client); } else { - log_v2::tls()->info("TLS: using anonymous server credentials"); + logger->info("TLS: using anonymous server credentials"); ret = gnutls_credentials_set(session, GNUTLS_CRD_ANON, _cred.server); } } // ... or certificate credentials. else { - log_v2::tls()->info("TLS: using certificates as credentials"); + logger->info("TLS: using certificates as credentials"); ret = gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, _cred.cert); if (SERVER == _type) gnutls_certificate_server_set_request(session, GNUTLS_CERT_REQUEST); } if (ret != GNUTLS_E_SUCCESS) { - log_v2::tls()->error("TLS: could not set credentials: {}", - gnutls_strerror(ret)); + logger->error("TLS: could not set credentials: {}", gnutls_strerror(ret)); throw msg_fmt("TLS: could not set credentials: {}", gnutls_strerror(ret)); } } @@ -100,12 +101,13 @@ void params::apply(gnutls_session_t session)const { void params::load() { // Certificate-based. if (!_cert.empty() && !_key.empty()) { + auto logger = log_v2::instance().get(log_v2::TLS); // Initialize credentials. int ret; ret = gnutls_certificate_allocate_credentials(&_cred.cert); if (ret != GNUTLS_E_SUCCESS) { - log_v2::tls()->error("TLS: credentials allocation failed: {}", - gnutls_strerror(ret)); + logger->error("TLS: credentials allocation failed: {}", + gnutls_strerror(ret)); throw msg_fmt("TLS: credentials allocation failed: {}", gnutls_strerror(ret)); } @@ -116,8 +118,8 @@ void params::load() { ret = gnutls_certificate_set_x509_key_file( _cred.cert, _cert.c_str(), _key.c_str(), GNUTLS_X509_FMT_PEM); if (ret != GNUTLS_E_SUCCESS) { - log_v2::tls()->error("TLS: could not load certificate ({}, {}): {}", - _cert, _key, gnutls_strerror(ret)); + logger->error("TLS: could not load certificate ({}, {}): {}", _cert, _key, + gnutls_strerror(ret)); throw msg_fmt("TLS: could not load certificate: {}", gnutls_strerror(ret)); } @@ -127,7 +129,7 @@ void params::load() { ret = gnutls_certificate_set_x509_trust_file(_cred.cert, _ca.c_str(), GNUTLS_X509_FMT_PEM); if (ret <= 0) { - log_v2::tls()->error( + logger->error( "TLS: could not load trusted Certificate Authority's certificate " "'{}': {}", _ca, gnutls_strerror(ret)); @@ -223,22 +225,21 @@ void params::set_trusted_ca(std::string const& ca_cert) { */ void params::validate_cert(gnutls_session_t session) const { if (!_ca.empty()) { + auto logger = log_v2::instance().get(log_v2::TLS); int ret; uint32_t status; if (!_tls_hostname.empty()) { - log_v2::tls()->info( - "TLS: common name '{}' used for certificate verification", - _tls_hostname); + logger->info("TLS: common name '{}' used for certificate verification", + _tls_hostname); ret = gnutls_certificate_verify_peers3(session, _tls_hostname.c_str(), &status); } else { - log_v2::tls()->info( - "TLS: Server hostname used for certificate verification"); + logger->info("TLS: Server hostname used for certificate verification"); ret = gnutls_certificate_verify_peers2(session, &status); } if (ret != GNUTLS_E_SUCCESS) { - log_v2::tls()->error( + logger->error( "TLS: certificate verification failed , assuming invalid " "certificate: {}", gnutls_strerror(ret)); @@ -247,18 +248,18 @@ void params::validate_cert(gnutls_session_t session) const { "{}", gnutls_strerror(ret)); } else if (status & GNUTLS_CERT_INVALID) { - log_v2::tls()->error("TLS: peer certificate is invalid"); + logger->error("TLS: peer certificate is invalid"); throw msg_fmt("TLS: peer certificate is invalid"); } else if (status & GNUTLS_CERT_REVOKED) { - log_v2::tls()->error("TLS: peer certificate was revoked"); + logger->error("TLS: peer certificate was revoked"); throw msg_fmt("TLS: peer certificate was revoked"); } else if (status & GNUTLS_CERT_SIGNER_NOT_FOUND) { - log_v2::tls()->error( + logger->error( "TLS: peer certificate was not issued by a trusted authority"); throw msg_fmt( "TLS: peer certificate was not issued by a trusted authority"); } else if (status & GNUTLS_CERT_INSECURE_ALGORITHM) { - log_v2::tls()->error( + logger->error( "TLS: peer certificate is using an insecure algorithm that cannot be " "trusted"); throw msg_fmt( @@ -296,8 +297,10 @@ void params::_init_anonymous() { else ret = gnutls_anon_allocate_server_credentials(&_cred.server); if (ret != GNUTLS_E_SUCCESS) { - log_v2::tls()->error("TLS: anonymous credentials initialization failed: {}", - gnutls_strerror(ret)); + log_v2::instance() + .get(log_v2::TLS) + ->error("TLS: anonymous credentials initialization failed: {}", + gnutls_strerror(ret)); throw msg_fmt("TLS: anonymous credentials initialization failed: {}", gnutls_strerror(ret)); } diff --git a/broker/tls/src/stream.cc b/broker/tls/src/stream.cc index b0528e8a555..1e36d6f9dfc 100644 --- a/broker/tls/src/stream.cc +++ b/broker/tls/src/stream.cc @@ -20,8 +20,8 @@ #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/io/raw.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" #include "com/centreon/broker/tls/internal.hh" #include "com/centreon/broker/tls/stream.hh" @@ -29,12 +29,7 @@ using namespace com::centreon::broker; using namespace com::centreon::broker::tls; using namespace com::centreon::exceptions; - -/************************************** - * * - * Public Methods * - * * - **************************************/ +using log_v2 = com::centreon::common::log_v2::log_v2; /** * @brief Constructor. @@ -46,12 +41,15 @@ using namespace com::centreon::exceptions; * encryption that should be used. */ stream::stream(unsigned int session_flags) - : io::stream("TLS"), _deadline((time_t)-1), _session(nullptr) { - SPDLOG_LOGGER_DEBUG(log_v2::tls(), "{:p} TLS: created", + : io::stream("TLS"), + _deadline((time_t)-1), + _session(nullptr), + _logger{log_v2::instance().get(log_v2::TLS)} { + SPDLOG_LOGGER_DEBUG(_logger, "{:p} TLS: created", static_cast(this)); int ret = gnutls_init(&_session, session_flags); if (ret != GNUTLS_E_SUCCESS) { - SPDLOG_LOGGER_ERROR(log_v2::tls(), "TLS: cannot initialize session: {}", + SPDLOG_LOGGER_ERROR(_logger, "TLS: cannot initialize session: {}", gnutls_strerror(ret)); throw msg_fmt("TLS: cannot initialize session: {}", gnutls_strerror(ret)); } @@ -75,20 +73,20 @@ void stream::init(const params& param) { gnutls_transport_set_ptr(_session, this); // Perform the TLS handshake. - SPDLOG_LOGGER_DEBUG(log_v2::tls(), "{:p} TLS: performing handshake", + SPDLOG_LOGGER_DEBUG(_logger, "{:p} TLS: performing handshake", static_cast(this)); do { ret = gnutls_handshake(_session); } while (GNUTLS_E_AGAIN == ret || GNUTLS_E_INTERRUPTED == ret); if (ret != GNUTLS_E_SUCCESS) { - SPDLOG_LOGGER_ERROR(log_v2::tls(), "TLS: handshake failed: {}", + SPDLOG_LOGGER_ERROR(_logger, "TLS: handshake failed: {}", gnutls_strerror(ret)); throw msg_fmt("TLS: handshake failed: {} ", gnutls_strerror(ret)); } - SPDLOG_LOGGER_DEBUG(log_v2::tls(), "TLS: successful handshake"); + SPDLOG_LOGGER_DEBUG(_logger, "TLS: successful handshake"); gnutls_protocol_t prot = gnutls_protocol_get_version(_session); gnutls_cipher_algorithm_t ciph = gnutls_cipher_get(_session); - SPDLOG_LOGGER_DEBUG(log_v2::tls(), "TLS: protocol and cipher {} {} used", + SPDLOG_LOGGER_DEBUG(_logger, "TLS: protocol and cipher {} {} used", gnutls_protocol_get_name(prot), gnutls_cipher_get_name(ciph)); @@ -105,7 +103,7 @@ void stream::init(const params& param) { stream::~stream() { if (_session) { try { - SPDLOG_LOGGER_DEBUG(log_v2::tls(), "{:p} TLS: destroy session: {:p}", + SPDLOG_LOGGER_DEBUG(_logger, "{:p} TLS: destroy session: {:p}", static_cast(this), static_cast(_session)); gnutls_bye(_session, GNUTLS_SHUT_RDWR); @@ -141,7 +139,7 @@ bool stream::read(std::shared_ptr& d, time_t deadline) { int ret(gnutls_record_recv(_session, buffer->data(), buffer->size())); if (ret < 0) { if ((ret != GNUTLS_E_INTERRUPTED) && (ret != GNUTLS_E_AGAIN)) { - SPDLOG_LOGGER_ERROR(log_v2::tls(), "TLS: could not receive data: {}", + SPDLOG_LOGGER_ERROR(_logger, "TLS: could not receive data: {}", gnutls_strerror(ret)); throw msg_fmt("TLS: could not receive data: {} ", gnutls_strerror(ret)); } else @@ -151,7 +149,7 @@ bool stream::read(std::shared_ptr& d, time_t deadline) { d = buffer; return true; } else { - SPDLOG_LOGGER_ERROR(log_v2::tls(), "TLS session is terminated"); + SPDLOG_LOGGER_ERROR(_logger, "TLS session is terminated"); throw msg_fmt("TLS session is terminated"); } return false; @@ -202,7 +200,7 @@ long long stream::read_encrypted(void* buffer, long long size) { return size; } } catch (const std::exception& e) { - SPDLOG_LOGGER_DEBUG(log_v2::tls(), "tls read fail: {}", e.what()); + SPDLOG_LOGGER_DEBUG(_logger, "tls read fail: {}", e.what()); gnutls_transport_set_errno(_session, EPIPE); throw; } @@ -229,7 +227,7 @@ int stream::write(std::shared_ptr const& d) { while (size > 0) { int ret(gnutls_record_send(_session, ptr, size)); if (ret < 0) { - SPDLOG_LOGGER_ERROR(log_v2::tls(), "TLS: could not send data: {}", + SPDLOG_LOGGER_ERROR(_logger, "TLS: could not send data: {}", gnutls_strerror(ret)); throw msg_fmt("TLS: could not send data: {}", gnutls_strerror(ret)); } @@ -254,13 +252,13 @@ long long stream::write_encrypted(void const* buffer, long long size) { std::vector tmp(const_cast(static_cast(buffer)), const_cast(static_cast(buffer)) + static_cast(size)); - SPDLOG_LOGGER_TRACE(log_v2::tls(), "tls write enc: {}", size); + SPDLOG_LOGGER_TRACE(_logger, "tls write enc: {}", size); r->get_buffer() = std::move(tmp); try { _substream->write(r); _substream->flush(); } catch (const std::exception& e) { - SPDLOG_LOGGER_DEBUG(log_v2::tls(), "tls write fail: {}", e.what()); + SPDLOG_LOGGER_DEBUG(_logger, "tls write fail: {}", e.what()); gnutls_transport_set_errno(_session, EPIPE); throw; } diff --git a/broker/tls/test/acceptor.cc b/broker/tls/test/acceptor.cc index 404e63b3b7b..f2a051b4fc0 100644 --- a/broker/tls/test/acceptor.cc +++ b/broker/tls/test/acceptor.cc @@ -55,9 +55,7 @@ class TlsTest : public ::testing::Test { tls::initialize(); } - void TearDown() override { - tcp::tcp_async::unload(); - } + void TearDown() override { tcp::tcp_async::unload(); } }; TEST_F(TlsTest, AnonTlsStream) { @@ -415,7 +413,7 @@ TEST_F(TlsTest, TlsStreamCaError) { cbd_finished = true; }); - std::thread centengine([&cbd_finished] { + std::thread centengine([] { auto c{std::make_unique(test_conf2)}; /* the name does not match with the CN of the server certificate */ diff --git a/broker/unified_sql/inc/com/centreon/broker/unified_sql/bulk_bind.hh b/broker/unified_sql/inc/com/centreon/broker/unified_sql/bulk_bind.hh index a7482a1a87a..41d8c2eb9a7 100644 --- a/broker/unified_sql/inc/com/centreon/broker/unified_sql/bulk_bind.hh +++ b/broker/unified_sql/inc/com/centreon/broker/unified_sql/bulk_bind.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2022-2023 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2022-2023 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_UNIFIED_SQL_BULK_BIND_HH #define CCB_UNIFIED_SQL_BULK_BIND_HH @@ -63,12 +63,14 @@ class bulk_bind { mutable std::mutex _queue_m; std::vector> _bind; std::vector _next_time; + std::shared_ptr _logger; public: bulk_bind(const size_t connections_count, const uint32_t max_interval, const uint32_t max_rows, - database::mysql_bulk_stmt& stmt); + database::mysql_bulk_stmt& stmt, + const std::shared_ptr& logger); bulk_bind(const bulk_bind&) = delete; std::unique_ptr& bind(int32_t conn); void apply_to_stmt(int32_t conn); @@ -81,6 +83,6 @@ class bulk_bind { void unlock(); }; } // namespace unified_sql -} +} // namespace com::centreon::broker #endif /* !CCB_UNIFIED_SQL_BULK_BIND_HH */ diff --git a/broker/unified_sql/inc/com/centreon/broker/unified_sql/bulk_queries.hh b/broker/unified_sql/inc/com/centreon/broker/unified_sql/bulk_queries.hh index 7f782182b9e..3574cf4ce96 100644 --- a/broker/unified_sql/inc/com/centreon/broker/unified_sql/bulk_queries.hh +++ b/broker/unified_sql/inc/com/centreon/broker/unified_sql/bulk_queries.hh @@ -1,24 +1,23 @@ -/* -** Copyright 2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_UNIFIED_SQL_BULK_QUERIES_HH #define CCB_UNIFIED_SQL_BULK_QUERIES_HH - namespace com::centreon::broker { namespace unified_sql { /** @@ -59,11 +58,13 @@ class bulk_queries { mutable std::mutex _queue_m; std::time_t _next_time; std::deque _queue; + std::shared_ptr _logger; public: bulk_queries(const uint32_t max_interval, const uint32_t max_queries, - const std::string& query); + const std::string& query, + const std::shared_ptr& logger); std::string get_query(); void push_query(const std::string& query); void push_query(std::string&& query); @@ -72,6 +73,6 @@ class bulk_queries { std::time_t next_time() const; }; } // namespace unified_sql -} +} // namespace com::centreon::broker #endif /* !CCB_UNIFIED_SQL_BULK_QUERIES_HH */ diff --git a/broker/unified_sql/inc/com/centreon/broker/unified_sql/internal.hh b/broker/unified_sql/inc/com/centreon/broker/unified_sql/internal.hh index 0672493abbf..38c60929dd9 100644 --- a/broker/unified_sql/inc/com/centreon/broker/unified_sql/internal.hh +++ b/broker/unified_sql/inc/com/centreon/broker/unified_sql/internal.hh @@ -1,24 +1,25 @@ -/* -** Copyright 2020-2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2020-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_UNIFIED_SQL_INTERNAL_HH #define CCB_UNIFIED_SQL_INTERNAL_HH +#include "bbdo/bbdo.pb.h" #include "bbdo/events.hh" #include "bbdo/neb.pb.h" #include "bbdo/rebuild_message.pb.h" @@ -42,6 +43,10 @@ using pb_remove_poller = make_type(io::bbdo, bbdo::de_remove_poller)>; } // namespace bbdo +namespace local { +using pb_stop = io::protobuf; +} // namespace local + namespace storage { /** * Here is the declaration of the message sent by unified_sql to rrd to rebuild @@ -64,6 +69,6 @@ using pb_metric_mapping = make_type(io::storage, storage::de_pb_metric_mapping)>; } // namespace storage -} +} // namespace com::centreon::broker #endif // !CCB_UNIFIED_SQL_INTERNAL_HH diff --git a/broker/unified_sql/inc/com/centreon/broker/unified_sql/stream.hh b/broker/unified_sql/inc/com/centreon/broker/unified_sql/stream.hh index 8e151fe3d0f..45563a1d8cc 100644 --- a/broker/unified_sql/inc/com/centreon/broker/unified_sql/stream.hh +++ b/broker/unified_sql/inc/com/centreon/broker/unified_sql/stream.hh @@ -259,13 +259,14 @@ class stream : public io::stream { std::time_t _next_update_metrics; std::time_t _next_loop_timeout; - asio::steady_timer _queues_timer; + asio::steady_timer _queues_timer ABSL_GUARDED_BY(_timer_m); /* To give the order to stop the check_queues */ std::atomic_bool _stop_check_queues; /* When the check_queues is really stopped */ bool _check_queues_stopped; /* Stats */ + std::shared_ptr _center; ConflictManagerStats* _stats; absl::flat_hash_set _cache_deleted_instance_id; @@ -283,9 +284,18 @@ class stream : public io::stream { absl::flat_hash_map, uint64_t> _resource_cache; - mutable std::mutex _timer_m; - asio::system_timer _group_clean_timer; - asio::system_timer _loop_timer; + mutable absl::Mutex _timer_m; + /* This is a barrier for timers. It must be locked in shared mode in the + * timers functions. So we can execute several timer functions at the same + * time. But it is locked in write mode in the stream destructor. So When + * executed, we are sure that all the timer functions have finished. */ + mutable absl::Mutex _barrier_timer_m; + asio::system_timer _group_clean_timer ABSL_GUARDED_BY(_timer_m); + asio::system_timer _loop_timer ABSL_GUARDED_BY(_timer_m); + + /* loggers */ + std::shared_ptr _logger_sql; + std::shared_ptr _logger_sto; absl::flat_hash_set _hostgroup_cache; absl::flat_hash_set _servicegroup_cache; @@ -392,7 +402,8 @@ class stream : public io::stream { void _update_hosts_and_services_of_instance(uint32_t id, bool responsive); void _update_timestamp(uint32_t instance_id); bool _is_valid_poller(uint32_t instance_id); - void _check_queues(boost::system::error_code ec); + void _check_queues(boost::system::error_code ec) + ABSL_SHARED_LOCKS_REQUIRED(_barrier_timer_m); void _check_deleted_index(); void _check_rebuild_index(); @@ -458,7 +469,7 @@ class stream : public io::stream { void _init_statements(); void _load_caches(); void _clean_tables(uint32_t instance_id); - void _clean_group_table(); + void _clean_group_table() ABSL_SHARED_LOCKS_REQUIRED(_barrier_timer_m); void _prepare_hg_insupdate_statement(); void _prepare_pb_hg_insupdate_statement(); void _prepare_sg_insupdate_statement(); @@ -471,7 +482,7 @@ class stream : public io::stream { void _clear_instances_cache(const std::list& ids); bool _host_instance_known(uint64_t host_id) const; - void _start_loop_timer(); + void _start_loop_timer() ABSL_EXCLUSIVE_LOCKS_REQUIRED(_timer_m); public: static void (stream::*const neb_processing_table[])( @@ -488,9 +499,10 @@ class stream : public io::stream { stream() = delete; stream& operator=(const stream&) = delete; stream(const stream&) = delete; - ~stream() noexcept; + ~stream() noexcept ABSL_LOCKS_EXCLUDED(_barrier_timer_m); static const multiplexing::muxer_filter& get_muxer_filter(); + static const multiplexing::muxer_filter& get_forbidden_filter(); void update_metric_info_cache(uint64_t index_id, uint32_t metric_id, @@ -503,6 +515,7 @@ class stream : public io::stream { void statistics(nlohmann::json& tree) const override; void remove_graphs(const std::shared_ptr& d); void remove_poller(const std::shared_ptr& d); + void process_stop(const std::shared_ptr& d); void update() override; }; } // namespace unified_sql diff --git a/broker/unified_sql/src/bulk_bind.cc b/broker/unified_sql/src/bulk_bind.cc index 079eefb6051..d61eecbf891 100644 --- a/broker/unified_sql/src/bulk_bind.cc +++ b/broker/unified_sql/src/bulk_bind.cc @@ -1,27 +1,29 @@ /** -* Copyright 2022-2023 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2022-2023 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/unified_sql/bulk_bind.hh" -#include "com/centreon/broker/log_v2.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::unified_sql; +using log_v2 = com::centreon::common::log_v2::log_v2; + /** * @brief Constructor * @@ -33,12 +35,14 @@ using namespace com::centreon::broker::unified_sql; bulk_bind::bulk_bind(const size_t connections_count, const uint32_t max_interval, const uint32_t max_rows, - database::mysql_bulk_stmt& stmt) + database::mysql_bulk_stmt& stmt, + const std::shared_ptr& logger) : _interval{max_interval}, _max_size{max_rows}, _stmt(stmt), _bind(connections_count), - _next_time(connections_count) {} + _next_time(connections_count), + _logger{logger} {} /** * @brief Return true when the time limit or the row counter are reached with @@ -54,27 +58,26 @@ bool bulk_bind::ready(int32_t conn) { return false; if (b->rows_count() >= _max_size) { - log_v2::sql()->trace("The bind rows count {} reaches its max size {}", - b->rows_count(), _max_size); + _logger->trace("The bind rows count {} reaches its max size {}", + b->rows_count(), _max_size); return true; } std::time_t now = time(nullptr); if (_next_time[conn] <= now) { - log_v2::sql()->trace( + _logger->trace( "The bind next time {} has been reached by the current time {}", _next_time[conn], now); if (b->current_row() == 0) { - log_v2::sql()->trace( - "the rows count of the binding is 0 so nothing to do"); + _logger->trace("the rows count of the binding is 0 so nothing to do"); _next_time[conn] = std::time(nullptr) + _interval; - log_v2::sql()->trace(" => bind not ready"); + _logger->trace(" => bind not ready"); return false; } - log_v2::sql()->trace(" => bind ready"); + _logger->trace(" => bind ready"); return true; } - log_v2::sql()->trace(" => bind not ready"); + _logger->trace(" => bind not ready"); return false; } diff --git a/broker/unified_sql/src/bulk_queries.cc b/broker/unified_sql/src/bulk_queries.cc index e7a591c113f..87995d902a4 100644 --- a/broker/unified_sql/src/bulk_queries.cc +++ b/broker/unified_sql/src/bulk_queries.cc @@ -1,26 +1,29 @@ /** -* Copyright 2022 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/unified_sql/bulk_queries.hh" -#include "com/centreon/broker/log_v2.hh" + +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker::unified_sql; +using log_v2 = com::centreon::common::log_v2::log_v2; + /** * @brief Constructor * @@ -31,11 +34,13 @@ using namespace com::centreon::broker::unified_sql; */ bulk_queries::bulk_queries(const uint32_t max_interval, const uint32_t max_queries, - const std::string& query) + const std::string& query, + const std::shared_ptr& logger) : _interval{max_interval}, _max_size{max_queries}, _query(query), - _next_time{std::time(nullptr) + max_interval} {} + _next_time{std::time(nullptr) + max_interval}, + _logger{logger} {} /** * @brief Compute the query to execute as a string and return it. The container @@ -53,9 +58,9 @@ std::string bulk_queries::get_query() { std::string query; if (!queue.empty()) { /* Building the query */ - log_v2::sql()->debug("SQL: {} items sent in bulk", queue.size()); + _logger->debug("SQL: {} items sent in bulk", queue.size()); query = fmt::format(_query, fmt::join(queue, ",")); - log_v2::sql()->trace("Sending query << {} >>", query); + _logger->trace("Sending query << {} >>", query); } _next_time = std::time(nullptr) + _interval; return query; diff --git a/broker/unified_sql/src/connector.cc b/broker/unified_sql/src/connector.cc index fb382f4d62a..a5b156b987a 100644 --- a/broker/unified_sql/src/connector.cc +++ b/broker/unified_sql/src/connector.cc @@ -1,20 +1,20 @@ /** -* Copyright 2011-2015,2017 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2015,2017 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/unified_sql/connector.hh" @@ -26,7 +26,10 @@ using namespace com::centreon::broker::unified_sql; /** * Default constructor. */ -connector::connector() : io::endpoint(false, stream::get_muxer_filter()) {} +connector::connector() + : io::endpoint(false, + stream::get_muxer_filter(), + stream::get_forbidden_filter()) {} /** * Set connection parameters. diff --git a/broker/unified_sql/src/factory.cc b/broker/unified_sql/src/factory.cc index 2a40b4b46fc..4c9ef804ac5 100644 --- a/broker/unified_sql/src/factory.cc +++ b/broker/unified_sql/src/factory.cc @@ -1,20 +1,20 @@ /** -* Copyright 2022 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/unified_sql/factory.hh" @@ -23,13 +23,14 @@ #include #include "com/centreon/broker/config/parser.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/unified_sql/connector.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::unified_sql; +using com::centreon::common::log_v2::log_v2; /** * Find a parameter in configuration. @@ -79,12 +80,13 @@ io::endpoint* factory::new_endpoint( std::shared_ptr cache) const { (void)cache; + auto logger = log_v2::instance().get(log_v2::SQL); // Find RRD length. uint32_t rrd_length; if (!absl::SimpleAtoi(find_param(cfg, "length"), &rrd_length)) { /* This default length represents 180 days. */ rrd_length = 15552000; - log_v2::sql()->error( + logger->error( "unified_sql: the length field should contain a string containing a " "number. We use the default value in replacement 15552000."); } @@ -97,7 +99,7 @@ io::endpoint* factory::new_endpoint( if (it != cfg.params.end()) { if (!absl::SimpleAtoi(it->second, &interval_length)) { interval_length = 60; - log_v2::sql()->error( + logger->error( "unified_sql: the interval field should contain a string " "containing a number. We use the default value in replacement 60."); } @@ -116,7 +118,7 @@ io::endpoint* factory::new_endpoint( cfg.params.find("store_in_data_bin")}; if (it != cfg.params.end()) { if (!absl::SimpleAtob(it->second, &store_in_data_bin)) { - log_v2::sql()->error( + logger->error( "factory: cannot parse the 'store_in_data_bin' boolean: the " "content is '{}'", it->second); @@ -132,7 +134,7 @@ io::endpoint* factory::new_endpoint( cfg.params.find("store_in_resources")}; if (it != cfg.params.end()) { if (!absl::SimpleAtob(it->second, &store_in_resources)) { - log_v2::sql()->error( + logger->error( "factory: cannot parse the 'store_in_resources' boolean: the " "content is '{}'", it->second); @@ -148,7 +150,7 @@ io::endpoint* factory::new_endpoint( cfg.params.find("store_in_hosts_services")}; if (it != cfg.params.end()) { if (!absl::SimpleAtob(it->second, &store_in_hosts_services)) { - log_v2::sql()->error( + logger->error( "factory: cannot parse the 'store_in_hosts_services' boolean: the " "content is '{}'", it->second); @@ -157,10 +159,10 @@ io::endpoint* factory::new_endpoint( } } - log_v2::sql()->debug("SQL: store in hosts/services: {}", - store_in_hosts_services ? "yes" : "no"); - log_v2::sql()->debug("SQL: store in resources: {}", - store_in_resources ? "yes" : "no"); + logger->debug("SQL: store in hosts/services: {}", + store_in_hosts_services ? "yes" : "no"); + logger->debug("SQL: store in resources: {}", + store_in_resources ? "yes" : "no"); // Loop timeout // By default, 30 seconds @@ -175,7 +177,7 @@ io::endpoint* factory::new_endpoint( auto it = cfg.params.find("instance_timeout"); if (it != cfg.params.end() && !absl::SimpleAtoi(it->second, &instance_timeout)) { - log_v2::sql()->error( + logger->error( "factory: cannot parse the 'instance_timeout' value. It should be an " "unsigned integer. 300 is set by default."); instance_timeout = 300; diff --git a/broker/unified_sql/src/main.cc b/broker/unified_sql/src/main.cc index f963dc02a1c..cae259e86bb 100644 --- a/broker/unified_sql/src/main.cc +++ b/broker/unified_sql/src/main.cc @@ -1,20 +1,20 @@ /** -* Copyright 2011-2013 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2013 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "bbdo/events.hh" #include "bbdo/storage/index_mapping.hh" @@ -24,15 +24,17 @@ #include "bbdo/storage/status.hh" #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/io/protocols.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/unified_sql/factory.hh" #include "com/centreon/broker/unified_sql/internal.hh" #include "com/centreon/broker/unified_sql/stream.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; +using log_v2 = com::centreon::common::log_v2::log_v2; + // Load count. static uint32_t instances{0u}; @@ -74,11 +76,13 @@ bool broker_module_deinit() { void broker_module_init(void const* arg) { (void)arg; + auto logger = log_v2::instance().get(log_v2::SQL); + // Increment instance number. if (!instances++) { // Storage module. - log_v2::sql()->info("unified_sql: module for Centreon Broker {}", - CENTREON_BROKER_VERSION); + logger->info("unified_sql: module for Centreon Broker {}", + CENTREON_BROKER_VERSION); io::events& e(io::events::instance()); @@ -144,6 +148,11 @@ void broker_module_init(void const* arg) { e.register_event(make_type(io::storage, storage::de_pb_metric_mapping), "pb_metric_mapping", &storage::pb_metric_mapping::operations); + + /* Let's register the message received when a poller is stopped. This is + * pb_stop. */ + e.register_event(make_type(io::local, local::de_pb_stop), "LocStop", + &local::pb_stop::operations); } // Register unified_sql layer. diff --git a/broker/unified_sql/src/rebuilder.cc b/broker/unified_sql/src/rebuilder.cc index 123a8a7a9d6..0f75add35f6 100644 --- a/broker/unified_sql/src/rebuilder.cc +++ b/broker/unified_sql/src/rebuilder.cc @@ -1,5 +1,5 @@ /** - * Copyright 2012-2015,2017,2020-2021 Centreon + * Copyright 2012-2015,2017,2020-2024 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,6 @@ #include #include -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/time.hh" #include "com/centreon/broker/multiplexing/publisher.hh" #include "com/centreon/broker/sql/mysql_error.hh" @@ -33,11 +32,14 @@ #include "com/centreon/broker/unified_sql/internal.hh" #include "com/centreon/broker/unified_sql/stream.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::unified_sql; +using com::centreon::common::log_v2::log_v2; + /** * Constructor. * @@ -54,7 +56,7 @@ rebuilder::rebuilder(const database_config& db_cfg, } rebuilder::~rebuilder() noexcept { - log_v2::sql()->debug("SQL: stopping rebuilder"); + log_v2::instance().get(log_v2::SQL)->debug("SQL: stopping rebuilder"); std::unique_lock lck(_rebuilding_m); _rebuilding_cv.wait_for(lck, std::chrono::seconds(20), [this] { return _rebuilding == 0; }); @@ -66,7 +68,9 @@ rebuilder::~rebuilder() noexcept { * @param d The BBDO message with all the metric ids to rebuild. */ void rebuilder::rebuild_graphs(const std::shared_ptr& d) { - asio::post(com::centreon::common::pool::io_context(), [this, data = d] { + asio::post(com::centreon::common::pool::io_context(), [this, data = d, + logger = + log_v2::instance().get(log_v2::SQL)] { { std::lock_guard lck(_rebuilding_m); _rebuilding++; @@ -77,7 +81,7 @@ void rebuilder::rebuild_graphs(const std::shared_ptr& d) { std::string ids_str{ fmt::format("{}", fmt::join(ids.obj().index_ids(), ","))}; - log_v2::sql()->debug( + logger->debug( "Metric rebuild: Rebuild metrics event received for metrics ({})", ids_str); @@ -101,7 +105,7 @@ void rebuilder::rebuild_graphs(const std::shared_ptr& d) { "i.host_id=s.host_id AND " "i.service_id=s.service_id WHERE i.id IN ({})", ids_str)}; - log_v2::sql()->trace("Metric rebuild: Executed query << {} >>", query); + logger->trace("Metric rebuild: Executed query << {} >>", query); ms.run_query_and_get_result(query, std::move(promise), conn); std::map ret_inter; std::list mids; @@ -113,8 +117,7 @@ void rebuilder::rebuild_graphs(const std::shared_ptr& d) { uint64_t mid = res.value_as_u64(0); uint64_t index_id = res.value_as_u64(5); mids.push_back(mid); - log_v2::sql()->trace("Metric rebuild: metric {} is sent to rebuild", - mid); + logger->trace("Metric rebuild: metric {} is sent to rebuild", mid); (*start_rebuild->mut_obj().mutable_metric_to_index_id())[mid] = index_id; auto ret = ret_inter.emplace(mid, metric_info()); @@ -130,8 +133,7 @@ void rebuilder::rebuild_graphs(const std::shared_ptr& d) { } if (mids.empty()) { - log_v2::sql()->error("Metrics rebuild: metrics don't exist: {}", - ids_str); + logger->error("Metrics rebuild: metrics don't exist: {}", ids_str); return; } @@ -151,8 +153,7 @@ void rebuilder::rebuild_graphs(const std::shared_ptr& d) { int32_t db_retention_day1 = res.value_as_i32(1); if (db_retention_day1 < db_retention_day) db_retention_day = db_retention_day1; - log_v2::sql()->debug("Storage retention on RRD: {} days", - db_retention_day); + logger->debug("Storage retention on RRD: {} days", db_retention_day); } if (db_retention_day) { /* Let's get the start of this day */ @@ -166,8 +167,8 @@ void rebuilder::rebuild_graphs(const std::shared_ptr& d) { tmv.tm_mday -= db_retention_day; start = mktime(&tmv); while (db_retention_day >= 0) { - log_v2::sql()->trace("Metrics rebuild: db_retention_day = {}", - db_retention_day); + logger->trace("Metrics rebuild: db_retention_day = {}", + db_retention_day); tmv.tm_mday++; end = mktime(&tmv); db_retention_day--; @@ -179,8 +180,7 @@ void rebuilder::rebuild_graphs(const std::shared_ptr& d) { "ctime>={} AND " "ctime<{} AND id_metric IN ({}) ORDER BY ctime ASC", start, end, mids_str)}; - log_v2::sql()->trace("Metrics rebuild: Query << {} >> executed", - query); + logger->trace("Metrics rebuild: Query << {} >> executed", query); ms.run_query_and_get_result(query, std::move(promise_bin), conn); auto data_rebuild = std::make_shared(); @@ -224,8 +224,8 @@ void rebuilder::rebuild_graphs(const std::shared_ptr& d) { throw msg_fmt("Metrics rebuild: Cannot get the date structure."); } } catch (const std::exception& e) { - log_v2::sql()->error( - "Metrics rebuild: Error during metrics rebuild: {}", e.what()); + logger->error("Metrics rebuild: Error during metrics rebuild: {}", + e.what()); } auto end_rebuild = std::make_shared(); end_rebuild->set_obj(std::move(start_rebuild->mut_obj())); @@ -236,13 +236,12 @@ void rebuilder::rebuild_graphs(const std::shared_ptr& d) { "UPDATE index_data SET must_be_rebuild='0' WHERE id IN ({})", ids_str), database::mysql_error::update_index_state, false); - log_v2::sql()->debug( + logger->debug( "Metric rebuild: Rebuild of metrics from the following indexes ({}) " "finished", ids_str); } catch (const std::exception& e) { - log_v2::sql()->error("Metric rebuild: error with the database: {}", - e.what()); + logger->error("Metric rebuild: error with the database: {}", e.what()); } { std::lock_guard lck(_rebuilding_m); diff --git a/broker/unified_sql/src/stream.cc b/broker/unified_sql/src/stream.cc index 4b8fe58ea0f..63d8423f646 100644 --- a/broker/unified_sql/src/stream.cc +++ b/broker/unified_sql/src/stream.cc @@ -18,16 +18,17 @@ #include "com/centreon/broker/unified_sql/stream.hh" #include +#include #include #include #include +#include "bbdo/events.hh" #include "bbdo/remove_graph_message.pb.h" #include "bbdo/storage/index_mapping.hh" #include "com/centreon/broker/cache/global_cache.hh" #include "com/centreon/broker/config/applier/state.hh" #include "com/centreon/broker/exceptions/shutdown.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/perfdata.hh" #include "com/centreon/broker/multiplexing/publisher.hh" #include "com/centreon/broker/neb/events.hh" @@ -36,11 +37,13 @@ #include "com/centreon/broker/stats/center.hh" #include "com/centreon/broker/unified_sql/internal.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::database; using namespace com::centreon::broker::unified_sql; +using log_v2 = com::centreon::common::log_v2::log_v2; const std::string stream::_index_data_insert_request( "INSERT INTO index_data " @@ -169,9 +172,12 @@ stream::stream(const database_config& dbcfg, _queues_timer{com::centreon::common::pool::io_context()}, _stop_check_queues{false}, _check_queues_stopped{false}, - _stats{stats::center::instance().register_conflict_manager()}, + _center{stats::center::instance_ptr()}, + _stats{_center->register_conflict_manager()}, _group_clean_timer{com::centreon::common::pool::io_context()}, _loop_timer{com::centreon::common::pool::io_context()}, + _logger_sql{log_v2::instance().get(log_v2::SQL)}, + _logger_sto{log_v2::instance().get(log_v2::PERFDATA)}, _cv(queue_timer_duration, _max_pending_queries, "INSERT INTO customvariables " @@ -179,16 +185,18 @@ stream::stream(const database_config& dbcfg, "value) VALUES {} " " ON DUPLICATE KEY UPDATE " "default_value=VALUES(default_VALUE),modified=VALUES(modified),type=" - "VALUES(type),update_time=VALUES(update_time),value=VALUES(value)"), + "VALUES(type),update_time=VALUES(update_time),value=VALUES(value)", + _logger_sql), _cvs(queue_timer_duration, _max_pending_queries, "INSERT INTO customvariables " "(name,host_id,service_id,modified,update_time,value) VALUES {} " " ON DUPLICATE KEY UPDATE " "modified=VALUES(modified),update_time=VALUES(update_time),value=" - "VALUES(value)"), + "VALUES(value)", + _logger_sql), _oldest_timestamp{std::numeric_limits::max()} { - SPDLOG_LOGGER_DEBUG(log_v2::sql(), "unified sql: stream class instanciation"); + SPDLOG_LOGGER_DEBUG(_logger_sql, "unified sql: stream class instanciation"); // dedicated connections for data_bin and logs? unsigned nb_dedicated_connection = 0; @@ -206,7 +214,7 @@ stream::stream(const database_config& dbcfg, if (nb_dedicated_connection > 0) { SPDLOG_LOGGER_INFO( - log_v2::sql(), + _logger_sql, "use of {} dedicated connection for logs and data_bin tables", nb_dedicated_connection); database_config dedicated_cfg(dbcfg); @@ -217,9 +225,8 @@ stream::stream(const database_config& dbcfg, _dedicated_connections = std::make_unique(dedicated_cfg); } - stats::center::instance().execute([stats = _stats, - loop_timeout = _loop_timeout, - max_queries = _max_pending_queries] { + _center->execute([stats = _stats, loop_timeout = _loop_timeout, + max_queries = _max_pending_queries] { stats->set_loop_timeout(loop_timeout); stats->set_max_pending_events(max_queries); }); @@ -227,33 +234,39 @@ stream::stream(const database_config& dbcfg, _action.resize(_mysql.connections_count()); _bulk_prepared_statement = _mysql.support_bulk_statement(); - log_v2::sql()->info("Unified sql stream connected to '{}' Server", - _mysql.get_server_version()); + _logger_sql->info("Unified sql stream connected to '{}' Server", + _mysql.get_server_version()); try { _init_statements(); _load_caches(); } catch (const std::exception& e) { - SPDLOG_LOGGER_ERROR(log_v2::sql(), "error while loading caches: {}", + SPDLOG_LOGGER_ERROR(_logger_sql, "error while loading caches: {}", e.what()); throw; } - std::lock_guard l(_timer_m); + absl::MutexLock l(&_timer_m); _queues_timer.expires_after(std::chrono::seconds(queue_timer_duration)); - _queues_timer.async_wait( - [this](const boost::system::error_code& err) { _check_queues(err); }); + _queues_timer.async_wait([this](const boost::system::error_code& err) { + absl::ReaderMutexLock lck(&_barrier_timer_m); + _check_queues(err); + }); _start_loop_timer(); - SPDLOG_LOGGER_INFO(log_v2::sql(), - "Unified sql stream running loop_interval={}", + SPDLOG_LOGGER_INFO(_logger_sql, "Unified sql stream running loop_interval={}", _loop_timeout); } stream::~stream() noexcept { - std::lock_guard l(_timer_m); - _group_clean_timer.cancel(); - _queues_timer.cancel(); - _loop_timer.cancel(); - SPDLOG_LOGGER_DEBUG(log_v2::sql(), "unified sql: stream destruction"); + { + absl::MutexLock l(&_timer_m); + _group_clean_timer.cancel(); + _queues_timer.cancel(); + _loop_timer.cancel(); + } + /* Let's wait a little if one of the timers is working during the cancellation + */ + absl::MutexLock lck(&_barrier_timer_m); + SPDLOG_LOGGER_DEBUG(_logger_sql, "unified sql: stream destruction"); } void stream::_load_deleted_instances() { @@ -268,7 +281,7 @@ void stream::_load_deleted_instances() { int32_t instance_id = res.value_as_i32(0); if (instance_id <= 0) SPDLOG_LOGGER_ERROR( - log_v2::sql(), + _logger_sql, "unified_sql: The 'instances' table contains rows with instance_id " "<= 0 ; you should remove them."); else @@ -397,18 +410,18 @@ void stream::_load_caches() { if (host_id <= 0 || service_id <= 0) { if (host_id <= 0) SPDLOG_LOGGER_ERROR( - log_v2::sql(), + _logger_sql, "unified_sql: the 'index_data' table contains rows with host_id " "<= " "0, you should remove them."); if (service_id <= 0) SPDLOG_LOGGER_ERROR( - log_v2::sql(), + _logger_sql, "unified_sql: the 'index_data' table contains rows with " "service_id " "<= 0, you should remove them."); } else { - log_v2::perfdata()->debug( + _logger_sto->debug( "unified_sql: loaded index {} of ({}, {}) with rrd_len={}", info.index_id, host_id, service_id, info.rrd_retention); _index_cache[{host_id, service_id}] = std::move(info); @@ -449,12 +462,12 @@ void stream::_load_caches() { else { if (host_id <= 0) SPDLOG_LOGGER_ERROR( - log_v2::sql(), + _logger_sql, "unified_sql: the 'hosts' table contains rows with host_id <= 0, " "you should remove them."); if (instance_id <= 0) SPDLOG_LOGGER_ERROR( - log_v2::sql(), + _logger_sql, "unified_sql: the 'hosts' table contains rows with instance_id " "<= 0, you should remove them."); } @@ -474,7 +487,7 @@ void stream::_load_caches() { _hostgroup_cache.insert(hg_id); else SPDLOG_LOGGER_ERROR( - log_v2::sql(), + _logger_sql, "unified_sql: the table 'hostgroups' contains rows with " "hostgroup_id <= 0, you should remove them."); } @@ -490,7 +503,7 @@ void stream::_load_caches() { int32_t sg_id = res.value_as_i32(0); if (sg_id <= 0) SPDLOG_LOGGER_ERROR( - log_v2::sql(), + _logger_sql, "unified_sql: the 'servicegroups' table contains rows with " "servicegroup_id <= 0, you should remove them."); else @@ -521,7 +534,7 @@ void stream::_load_caches() { if (metric_id <= 0) SPDLOG_LOGGER_ERROR( - log_v2::sql(), + _logger_sql, "unified_sql: the 'metrics' table contains row with metric_id " "<= 0 ; you should remove them."); else { @@ -597,7 +610,7 @@ void stream::update_metric_info_cache(uint64_t index_id, misc::read_lock lck(_metric_cache_m); auto it = _metric_cache.find({index_id, metric_name}); if (it != _metric_cache.end()) { - log_v2::perfdata()->info( + _logger_sto->info( "unified sql: updating metric '{}' of id {} at index {} to " "metric_type {}", metric_name, metric_id, index_id, metric_type_name[metric_type]); @@ -642,14 +655,14 @@ void stream::_finish_action(int32_t conn, uint32_t action) { * events. */ void stream::_finish_actions() { - SPDLOG_LOGGER_TRACE(log_v2::sql(), "unified sql: finish actions"); + SPDLOG_LOGGER_TRACE(_logger_sql, "unified sql: finish actions"); _mysql.commit(); for (uint32_t& v : _action) v = actions::none; _ack += _processed; _processed = 0; - SPDLOG_LOGGER_TRACE(log_v2::sql(), "finish actions processed = {}", - static_cast(_processed)); + SPDLOG_LOGGER_TRACE(_logger_sql, "finish actions processed = {}", + static_cast(_processed)); } /** @@ -705,7 +718,7 @@ int32_t stream::write(const std::shared_ptr& data) { assert(data); SPDLOG_LOGGER_TRACE( - log_v2::sql(), "unified sql: write event category:{}, element:{}", + _logger_sql, "unified sql: write event category:{}, element:{}", category_of_type(data->type()), element_of_type(data->type())); uint32_t type = data->type(); @@ -715,18 +728,35 @@ int32_t stream::write(const std::shared_ptr& data) { if (elem < neb_processing_table_size && neb_processing_table[elem]) { (this->*(neb_processing_table[elem]))(data); } else { - SPDLOG_LOGGER_ERROR(log_v2::sql(), "unknown neb event type: {}", elem); + SPDLOG_LOGGER_ERROR(_logger_sql, "unknown neb event type: {}", elem); + } + } else if (cat == io::bbdo) { + switch (elem) { + case bbdo::de_rebuild_graphs: + _rebuilder.rebuild_graphs(data); + break; + case bbdo::de_remove_graphs: + remove_graphs(data); + break; + case bbdo::de_remove_poller: + SPDLOG_LOGGER_INFO(_logger_sql, "remove poller..."); + remove_poller(data); + break; + default: + SPDLOG_LOGGER_TRACE( + _logger_sql, + "unified sql: event of category bbdo and type {} thrown away ; no " + "need to store it in the database.", + type); + } + } else if (cat == io::local) { + if (elem == local::de_pb_stop) { + SPDLOG_LOGGER_INFO(_logger_sql, "poller stopped..."); + process_stop(data); } - } else if (type == make_type(io::bbdo, bbdo::de_rebuild_graphs)) - _rebuilder.rebuild_graphs(data); - else if (type == make_type(io::bbdo, bbdo::de_remove_graphs)) - remove_graphs(data); - else if (type == make_type(io::bbdo, bbdo::de_remove_poller)) { - SPDLOG_LOGGER_INFO(log_v2::sql(), "remove poller..."); - remove_poller(data); } else { SPDLOG_LOGGER_TRACE( - log_v2::sql(), + _logger_sql, "unified sql: event of type {} thrown away ; no need to store it in " "the database.", type); @@ -763,16 +793,23 @@ class unified_muxer_filter : public multiplexing::muxer_filter { _mask[io::bbdo] |= 1ULL << bbdo::de_rebuild_graphs; _mask[io::bbdo] |= 1ULL << bbdo::de_remove_graphs; _mask[io::bbdo] |= 1ULL << bbdo::de_remove_poller; + _mask[io::local] |= 1ULL << local::de_pb_stop; _mask[io::extcmd] |= 1ULL << extcmd::de_pb_bench; } }; constexpr unified_muxer_filter _muxer_filter; +constexpr multiplexing::muxer_filter _forbidden_filter = + multiplexing::muxer_filter(_muxer_filter).reverse(); const multiplexing::muxer_filter& stream::get_muxer_filter() { return _muxer_filter; } +const multiplexing::muxer_filter& stream::get_forbidden_filter() { + return _forbidden_filter; +} + /** * @brief Flush the stream. * @@ -785,7 +822,7 @@ int32_t stream::flush() { _ack -= retval; _pending_events -= retval; // Event acknowledgement. - SPDLOG_LOGGER_TRACE(log_v2::sql(), "SQL: {} / {} events acknowledged", retval, + SPDLOG_LOGGER_TRACE(_logger_sql, "SQL: {} / {} events acknowledged", retval, static_cast(_pending_events)); return retval; } @@ -812,6 +849,7 @@ bool stream::read(std::shared_ptr& d, time_t deadline) { * @return the number of events to ack. */ int32_t stream::stop() { + _logger_sql->trace("unified_sql::stream stop {}", static_cast(this)); int32_t retval = flush(); /* We give the order to stop the check_queues */ _stop_check_queues = true; @@ -819,24 +857,59 @@ int32_t stream::stop() { std::unique_lock lck(_queues_m); if (_queues_cond_var.wait_for(lck, std::chrono::seconds(queue_timer_duration), [this] { return _check_queues_stopped; })) { - SPDLOG_LOGGER_INFO(log_v2::sql(), "SQL: stream correctly stopped"); + SPDLOG_LOGGER_INFO(_logger_sql, "SQL: stream correctly stopped"); } else { - SPDLOG_LOGGER_ERROR(log_v2::sql(), + SPDLOG_LOGGER_ERROR(_logger_sql, "SQL: stream queues check still running..."); } return retval; } +/** + * @brief Function called when a poller is disconnected from Broker. It cleans + * hosts/services and instances in the storage database. + * + * @param d A pb_stop event with the instance ID. + */ +void stream::process_stop(const std::shared_ptr& d) { + auto& stop = static_cast(d.get())->obj(); + int32_t conn = _mysql.choose_connection_by_instance(stop.poller_id()); + _finish_action(-1, actions::hosts | actions::acknowledgements | + actions::modules | actions::downtimes | + actions::comments | actions::servicegroups | + actions::hostgroups | actions::service_dependencies | + actions::host_dependencies); + + // Log message. + _logger_sql->info("unified_sql: Disabling poller (id: {}, running: no)", + stop.poller_id()); + + // Clean tables. + _clean_tables(stop.poller_id()); + + // Processing. + if (_is_valid_poller(stop.poller_id())) { + // Prepare queries. + if (!_instance_insupdate.prepared()) { + std::string query(fmt::format( + "UPDATE instances SET end_time={}, running=0 WHERE instance_id={}", + time(nullptr), stop.poller_id())); + _mysql.run_query(query, database::mysql_error::clean_hosts_services, + conn); + _add_action(conn, actions::instances); + } + } +} + /** * @brief process a remove graphs message. * * @param d The BBDO message with all the metrics/indexes to remove. */ void stream::remove_graphs(const std::shared_ptr& d) { - SPDLOG_LOGGER_INFO(log_v2::sql(), "remove graphs call"); - asio::post(com::centreon::common::pool::instance().io_context(), [this, - data = d] { + SPDLOG_LOGGER_INFO(_logger_sql, "remove graphs call"); + asio::post(com::centreon::common::pool::instance().io_context(), [this, data = d] { mysql ms(_dbcfg); bbdo::pb_remove_graphs* ids = static_cast(data.get()); @@ -865,17 +938,17 @@ void stream::remove_graphs(const std::shared_ptr& d) { if (mid <= 0 || host_id <= 0 || service_id <= 0) { if (mid <= 0) SPDLOG_LOGGER_ERROR( - log_v2::sql(), + _logger_sql, "unified_sql: the 'metrics' table contains rows with " "metric_id <= 0 ; you should remove them."); if (host_id <= 0) - SPDLOG_LOGGER_ERROR(log_v2::sql(), + SPDLOG_LOGGER_ERROR(_logger_sql, "unified_sql: the 'metrics' table " "contains rows with host_id " "<= 0 ; you should remove them."); if (service_id <= 0) SPDLOG_LOGGER_ERROR( - log_v2::sql(), + _logger_sql, "unified_sql: the 'metrics' table contains rows with " "service_id <= 0 ; you should remove them."); } else { @@ -902,7 +975,7 @@ void stream::remove_graphs(const std::shared_ptr& d) { while (ms.fetch_row(res)) { int32_t metric_id = res.value_as_i32(1); if (metric_id <= 0) - SPDLOG_LOGGER_ERROR(log_v2::sql(), + SPDLOG_LOGGER_ERROR(_logger_sql, "unified_sql: the 'metrics' table contains " "rows with metric_id " "<= 0 ; you should remove them."); @@ -913,7 +986,7 @@ void stream::remove_graphs(const std::shared_ptr& d) { } } } catch (const std::exception& e) { - SPDLOG_LOGGER_ERROR(log_v2::sql(), + SPDLOG_LOGGER_ERROR(_logger_sql, "could not query index / metrics table(s) to get " "index to delete: " "{} ", @@ -922,7 +995,7 @@ void stream::remove_graphs(const std::shared_ptr& d) { std::string mids_str{fmt::format("{}", fmt::join(metrics_to_delete, ","))}; if (!metrics_to_delete.empty()) { - SPDLOG_LOGGER_INFO(log_v2::sql(), "metrics {} erased from database", + SPDLOG_LOGGER_INFO(_logger_sql, "metrics {} erased from database", mids_str); ms.run_query( fmt::format("DELETE FROM metrics WHERE metric_id in ({})", mids_str), @@ -930,7 +1003,7 @@ void stream::remove_graphs(const std::shared_ptr& d) { } std::string ids_str{fmt::format("{}", fmt::join(indexes_to_delete, ","))}; if (!indexes_to_delete.empty()) { - SPDLOG_LOGGER_INFO(log_v2::sql(), "indexes {} erased from database", + SPDLOG_LOGGER_INFO(_logger_sql, "indexes {} erased from database", ids_str); ms.run_query( fmt::format("DELETE FROM index_data WHERE id in ({})", ids_str), @@ -944,13 +1017,13 @@ void stream::remove_graphs(const std::shared_ptr& d) { for (uint64_t i : indexes_to_delete) rmg->mut_obj().add_index_ids(i); SPDLOG_LOGGER_INFO( - log_v2::sql(), + _logger_sql, "publishing pb remove graph with {} metrics and {} indexes", metrics_to_delete.size(), indexes_to_delete.size()); multiplexing::publisher().write(rmg); } else SPDLOG_LOGGER_INFO( - log_v2::sql(), + _logger_sql, "metrics {} and indexes {} do not appear in the storage database", mids_str, ids_str); }); @@ -986,9 +1059,8 @@ void stream::remove_poller(const std::shared_ptr& d) { } if (count == 0) { SPDLOG_LOGGER_WARN( - log_v2::sql(), - "Unable to remove poller '{}', {} not running found in the " - "database", + _logger_sql, + "Unable to remove poller '{}', {} running found in the database", poller.obj().str(), count == 0 ? "none" : "more than one"); std::promise promise; std::future future = promise.get_future(); @@ -1002,7 +1074,7 @@ void stream::remove_poller(const std::shared_ptr& d) { if (!config::applier::state::instance().has_connection_from_poller( res.value_as_u64(0))) { SPDLOG_LOGGER_WARN( - log_v2::sql(), + _logger_sql, "The poller '{}' id {} is not connected (even if it looks " "running or not deleted)", poller.obj().str(), res.value_as_u64(0)); @@ -1026,8 +1098,8 @@ void stream::remove_poller(const std::shared_ptr& d) { } if (count == 0) { SPDLOG_LOGGER_WARN( - log_v2::sql(), - "Unable to remove poller {}, {} not running found in the " + _logger_sql, + "Unable to remove poller {}, {} running found in the " "database", poller.obj().idx(), count == 0 ? "none" : "more than one"); std::promise promise; @@ -1042,7 +1114,7 @@ void stream::remove_poller(const std::shared_ptr& d) { if (!config::applier::state::instance().has_connection_from_poller( poller.obj().idx())) { SPDLOG_LOGGER_WARN( - log_v2::sql(), + _logger_sql, "The poller '{}' id {} is not connected (even if it looks " "running or not deleted)", res.value_as_str(0), poller.obj().idx()); @@ -1055,17 +1127,17 @@ void stream::remove_poller(const std::shared_ptr& d) { for (uint64_t id : ids) { conn = _mysql.choose_connection_by_instance(id); - SPDLOG_LOGGER_INFO(log_v2::sql(), "unified sql: removing poller {}", id); + SPDLOG_LOGGER_INFO(_logger_sql, "unified sql: removing poller {}", id); _mysql.run_query( fmt::format("DELETE FROM instances WHERE instance_id={}", id), database::mysql_error::delete_poller, conn); - SPDLOG_LOGGER_TRACE(log_v2::sql(), - "unified sql: removing poller {} hosts", id); + SPDLOG_LOGGER_TRACE(_logger_sql, "unified sql: removing poller {} hosts", + id); _mysql.run_query( fmt::format("DELETE FROM hosts WHERE instance_id={}", id), database::mysql_error::delete_poller, conn); - SPDLOG_LOGGER_TRACE(log_v2::sql(), + SPDLOG_LOGGER_TRACE(_logger_sql, "unified sql: removing poller {} resources", id); _mysql.run_query( fmt::format("DELETE FROM resources WHERE poller_id={}", id), @@ -1074,9 +1146,8 @@ void stream::remove_poller(const std::shared_ptr& d) { } _clear_instances_cache(ids); } catch (const std::exception& e) { - SPDLOG_LOGGER_ERROR(log_v2::sql(), - "Error encountered while removing a poller: {}", - e.what()); + SPDLOG_LOGGER_ERROR( + _logger_sql, "Error encountered while removing a poller: {}", e.what()); } } @@ -1122,7 +1193,7 @@ void stream::_clear_instances_cache(const std::list& ids) { } void stream::update() { - SPDLOG_LOGGER_INFO(log_v2::sql(), "unified_sql stream update"); + SPDLOG_LOGGER_INFO(_logger_sql, "unified_sql stream update"); _check_deleted_index(); _check_rebuild_index(); } @@ -1133,8 +1204,12 @@ void stream::_start_loop_timer() { if (err) { return; } + absl::ReaderMutexLock lck(&_barrier_timer_m); _update_hosts_and_services_of_unresponsive_instances(); - _start_loop_timer(); + { + absl::MutexLock l(&_timer_m); + _start_loop_timer(); + } }); } @@ -1341,16 +1416,16 @@ void stream::_init_statements() { if (_bulk_prepared_statement) { auto hu = std::make_unique(hscr_query); _mysql.prepare_statement(*hu); - _hscr_bind = std::make_unique(_dbcfg.get_connections_count(), - dt_queue_timer_duration, - _max_pending_queries, *hu); + _hscr_bind = std::make_unique( + _dbcfg.get_connections_count(), dt_queue_timer_duration, + _max_pending_queries, *hu, _logger_sql); _hscr_update = std::move(hu); auto su = std::make_unique(sscr_query); _mysql.prepare_statement(*su); - _sscr_bind = std::make_unique(_dbcfg.get_connections_count(), - dt_queue_timer_duration, - _max_pending_queries, *su); + _sscr_bind = std::make_unique( + _dbcfg.get_connections_count(), dt_queue_timer_duration, + _max_pending_queries, *su, _logger_sql); _sscr_update = std::move(su); } else { _hscr_update = std::make_unique(hscr_query); @@ -1367,7 +1442,7 @@ void stream::_init_statements() { _mysql.prepare_statement(*hu); _hscr_resources_bind = std::make_unique( _dbcfg.get_connections_count(), dt_queue_timer_duration, - _max_pending_queries, *hu); + _max_pending_queries, *hu, _logger_sql); _hscr_resources_update = std::move(hu); auto su = @@ -1375,7 +1450,7 @@ void stream::_init_statements() { _mysql.prepare_statement(*su); _sscr_resources_bind = std::make_unique( _dbcfg.get_connections_count(), dt_queue_timer_duration, - _max_pending_queries, *su); + _max_pending_queries, *su, _logger_sql); _sscr_resources_update = std::move(su); } else { _hscr_resources_update = diff --git a/broker/unified_sql/src/stream_sql.cc b/broker/unified_sql/src/stream_sql.cc index 06ca4e710ae..42cd3ef6852 100644 --- a/broker/unified_sql/src/stream_sql.cc +++ b/broker/unified_sql/src/stream_sql.cc @@ -15,13 +15,13 @@ * * For more information : contact@centreon.com */ +#include #include #include "bbdo/neb.pb.h" #include "bbdo/storage/index_mapping.hh" #include "com/centreon/broker/cache/global_cache.hh" #include "com/centreon/broker/config/applier/state.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/string.hh" #include "com/centreon/broker/neb/events.hh" #include "com/centreon/broker/sql/mysql_result.hh" @@ -51,7 +51,7 @@ static const std::string _insert_or_update_tags = void stream::_clean_tables(uint32_t instance_id) { // no hostgroup and servicegroup clean during this function { - std::lock_guard l(_timer_m); + absl::MutexLock l(&_timer_m); _group_clean_timer.cancel(); } @@ -62,7 +62,7 @@ void stream::_clean_tables(uint32_t instance_id) { _finish_action(-1, -1); if (_store_in_resources) { SPDLOG_LOGGER_DEBUG( - log_v2::sql(), "unified sql: remove tags memberships (instance_id: {})", + _logger_sql, "unified sql: remove tags memberships (instance_id: {})", instance_id); conn = special_conn::tag % _mysql.connections_count(); _mysql.run_query( @@ -80,8 +80,8 @@ void stream::_clean_tables(uint32_t instance_id) { database::mysql_error::clean_resources, conn); _add_action(conn, actions::resources); SPDLOG_LOGGER_DEBUG( - log_v2::sql(), - "unified sql: disable hosts and services (instance_id: {})", instance_id); + _logger_sql, "unified sql: disable hosts and services (instance_id: {})", + instance_id); /* Disable hosts and services. */ std::string query(fmt::format( "UPDATE hosts AS h LEFT JOIN services AS s ON h.host_id = s.host_id " @@ -92,7 +92,7 @@ void stream::_clean_tables(uint32_t instance_id) { /* Remove host group memberships. */ SPDLOG_LOGGER_DEBUG( - log_v2::sql(), + _logger_sql, "unified sql: remove host group memberships (instance_id: {})", instance_id); query = fmt::format( @@ -104,7 +104,7 @@ void stream::_clean_tables(uint32_t instance_id) { /* Remove service group memberships */ SPDLOG_LOGGER_DEBUG( - log_v2::sql(), + _logger_sql, "unified sql: remove service group memberships (instance_id: {})", instance_id); query = fmt::format( @@ -117,7 +117,7 @@ void stream::_clean_tables(uint32_t instance_id) { _add_action(conn, actions::servicegroups); /* Remove host dependencies. */ - SPDLOG_LOGGER_DEBUG(log_v2::sql(), + SPDLOG_LOGGER_DEBUG(_logger_sql, "unified sql: remove host dependencies (instance_id: {})", instance_id); query = fmt::format( @@ -129,7 +129,7 @@ void stream::_clean_tables(uint32_t instance_id) { _add_action(conn, actions::host_dependencies); /* Remove host parents. */ - SPDLOG_LOGGER_DEBUG(log_v2::sql(), + SPDLOG_LOGGER_DEBUG(_logger_sql, "unified sql: remove host parents (instance_id: {})", instance_id); query = fmt::format( @@ -142,8 +142,7 @@ void stream::_clean_tables(uint32_t instance_id) { /* Remove service dependencies. */ SPDLOG_LOGGER_DEBUG( - log_v2::sql(), - "unified sql: remove service dependencies (instance_id: {})", + _logger_sql, "unified sql: remove service dependencies (instance_id: {})", instance_id); query = fmt::format( "DELETE ssd FROM services_services_dependencies AS ssd" @@ -159,17 +158,17 @@ void stream::_clean_tables(uint32_t instance_id) { _add_action(conn, actions::service_dependencies); /* Remove list of modules. */ - SPDLOG_LOGGER_DEBUG(log_v2::sql(), - "SQL: remove list of modules (instance_id: {})", + SPDLOG_LOGGER_DEBUG(_logger_sql, + "unified_sql: remove list of modules (instance_id: {})", instance_id); query = fmt::format("DELETE FROM modules WHERE instance_id={}", instance_id); _mysql.run_query(query, database::mysql_error::clean_modules, conn); _add_action(conn, actions::modules); // Cancellation of downtimes. - SPDLOG_LOGGER_DEBUG(log_v2::sql(), - "SQL: Cancellation of downtimes (instance_id: {})", - instance_id); + SPDLOG_LOGGER_DEBUG( + _logger_sql, "unified_sql: Cancellation of downtimes (instance_id: {})", + instance_id); query = fmt::format( "UPDATE downtimes SET cancelled=1 WHERE actual_end_time IS NULL AND " "cancelled=0 " @@ -180,14 +179,13 @@ void stream::_clean_tables(uint32_t instance_id) { _add_action(conn, actions::downtimes); // Remove comments. - SPDLOG_LOGGER_DEBUG(log_v2::sql(), + SPDLOG_LOGGER_DEBUG(_logger_sql, "unified sql: remove comments (instance_id: {})", instance_id); query = fmt::format( "UPDATE comments SET deletion_time={} WHERE instance_id={} AND " - "persistent=0 AND " - "(deletion_time IS NULL OR deletion_time=0)", + "persistent=0 AND (deletion_time IS NULL OR deletion_time=0)", time(nullptr), instance_id); _mysql.run_query(query, database::mysql_error::clean_comments, conn); @@ -195,9 +193,8 @@ void stream::_clean_tables(uint32_t instance_id) { // Remove custom variables. No need to choose the good instance, there are // no constraint between custom variables and instances. - SPDLOG_LOGGER_DEBUG(log_v2::sql(), - "Removing custom variables (instance_id: {})", - instance_id); + SPDLOG_LOGGER_DEBUG( + _logger_sql, "Removing custom variables (instance_id: {})", instance_id); query = fmt::format( "DELETE cv FROM customvariables AS cv INNER JOIN hosts AS h ON " "cv.host_id = h.host_id WHERE h.instance_id={}", @@ -207,10 +204,11 @@ void stream::_clean_tables(uint32_t instance_id) { _mysql.run_query(query, database::mysql_error::clean_customvariables, conn); _add_action(conn, actions::custom_variables); - std::lock_guard l(_timer_m); + absl::MutexLock l(&_timer_m); _group_clean_timer.expires_after(std::chrono::minutes(1)); _group_clean_timer.async_wait([this](const boost::system::error_code& err) { if (!err) { + absl::ReaderMutexLock lck(&_barrier_timer_m); _clean_group_table(); } }); @@ -220,8 +218,7 @@ void stream::_clean_group_table() { int32_t conn = _mysql.choose_best_connection(-1); try { /* Remove host groups. */ - SPDLOG_LOGGER_DEBUG(log_v2::sql(), - "unified_sql: remove empty host groups "); + SPDLOG_LOGGER_DEBUG(_logger_sql, "unified_sql: remove empty host groups "); _mysql.run_query( "DELETE hg FROM hostgroups AS hg LEFT JOIN hosts_hostgroups AS hhg ON " "hg.hostgroup_id=hhg.hostgroup_id WHERE hhg.hostgroup_id IS NULL", @@ -229,7 +226,7 @@ void stream::_clean_group_table() { _add_action(conn, actions::hostgroups); /* Remove service groups. */ - SPDLOG_LOGGER_DEBUG(log_v2::sql(), + SPDLOG_LOGGER_DEBUG(_logger_sql, "unified_sql: remove empty service groups"); _mysql.run_query( @@ -241,7 +238,7 @@ void stream::_clean_group_table() { database::mysql_error::clean_empty_servicegroups, conn); _add_action(conn, actions::servicegroups); } catch (const std::exception& e) { - SPDLOG_LOGGER_ERROR(log_v2::sql(), "fail to clean group tables: {}", + SPDLOG_LOGGER_ERROR(_logger_sql, "fail to clean group tables: {}", e.what()); } } @@ -251,7 +248,7 @@ void stream::_clean_group_table() { */ void stream::_update_hosts_and_services_of_unresponsive_instances() { SPDLOG_LOGGER_DEBUG( - log_v2::sql(), + _logger_sql, "unified sql: checking for outdated instances instance_timeout={}", _instance_timeout); @@ -301,7 +298,7 @@ void stream::_update_hosts_and_services_of_instance(uint32_t id, _finish_action(-1, actions::acknowledgements | actions::modules | actions::downtimes | actions::comments); - SPDLOG_LOGGER_TRACE(log_v2::sql(), + SPDLOG_LOGGER_TRACE(_logger_sql, "_update_hosts_and_services_of_instance " "_stored_timestamps.size()={} id={}, responsive={}", _stored_timestamps.size(), id, responsive); @@ -343,7 +340,7 @@ void stream::_update_hosts_and_services_of_instance(uint32_t id, } auto bbdo = config::applier::state::instance().get_bbdo_version(); SPDLOG_LOGGER_TRACE( - log_v2::sql(), + _logger_sql, "unified sql: SendResponsiveInstance vers:{} poller:{} alive:{}", bbdo.major_v, id, responsive); if (bbdo.major_v < 3) { @@ -392,9 +389,8 @@ bool stream::_is_valid_poller(uint32_t instance_id) { bool deleted = false; if (_cache_deleted_instance_id.contains(instance_id)) { SPDLOG_LOGGER_INFO( - log_v2::sql(), - "unified sql: discarding some event related to a deleted poller " - "({})", + _logger_sql, + "unified sql: discarding some event related to a deleted poller ({})", instance_id); deleted = true; } else @@ -420,7 +416,7 @@ void stream::_prepare_pb_hg_insupdate_statement() { query_preparator qp(neb::pb_host_group::static_type(), unique); _pb_host_group_insupdate = qp.prepare_insert_or_update_table( _mysql, "hostgroups ", /*space is mandatory to avoid - conflict with _process_host_dependency*/ + conflict with _host_group_insupdate*/ {{3, "hostgroup_id", io::protobuf_base::invalid_on_zero, 0}, {4, "name", 0, get_hostgroups_col_size(hostgroups_name)}}); } @@ -442,7 +438,7 @@ void stream::_prepare_pb_sg_insupdate_statement() { query_preparator qp(neb::pb_service_group::static_type(), unique); _pb_service_group_insupdate = qp.prepare_insert_or_update_table( _mysql, "servicegroups ", /*space is mandatory to avoid - conflict with _process_host_dependency*/ + conflict with _service_group_insupdate*/ {{3, "servicegroup_id", io::protobuf_base::invalid_on_zero, 0}, {4, "name", 0, get_servicegroups_col_size(servicegroups_name)}}); } @@ -462,7 +458,7 @@ void stream::_process_acknowledgement(const std::shared_ptr& d) { // Log message. SPDLOG_LOGGER_INFO( - log_v2::sql(), + _logger_sql, "processing acknowledgement event (poller: {}, host: {}, service: {}, " "entry time: {}, deletion time: {})", ack.poller_id, ack.host_id, ack.service_id, ack.entry_time, @@ -503,7 +499,7 @@ void stream::_process_pb_acknowledgement(const std::shared_ptr& d) { // Log message. SPDLOG_LOGGER_INFO( - log_v2::sql(), + _logger_sql, "processing pb acknowledgement event (poller: {}, host: {}, service: {}, " "entry time: {}, deletion time: {})", ack_obj.instance_id(), ack_obj.host_id(), ack_obj.service_id(), @@ -568,8 +564,8 @@ void stream::_process_comment(const std::shared_ptr& d) { neb::comment const& cmmnt{*static_cast(d.get())}; // Log message. - SPDLOG_LOGGER_INFO(log_v2::sql(), - "SQL: processing comment of poller {} on ({}, {})", + SPDLOG_LOGGER_INFO(_logger_sql, + "unified_sql: processing comment of poller {} on ({}, {})", cmmnt.poller_id, cmmnt.host_id, cmmnt.service_id); if (_comments->is_bulk()) { @@ -640,8 +636,8 @@ void stream::_process_pb_custom_variable(const std::shared_ptr& d) { // Processing. if (cv.enabled()) { - SPDLOG_LOGGER_INFO(log_v2::sql(), - "SQL: enable custom variable '{}' of ({}, {})", + SPDLOG_LOGGER_INFO(_logger_sql, + "unified_sql: enable custom variable '{}' of ({}, {})", cv.name(), cv.host_id(), cv.service_id()); std::lock_guard lck(_queues_m); @@ -660,9 +656,9 @@ void stream::_process_pb_custom_variable(const std::shared_ptr& d) { int conn = special_conn::custom_variable % _mysql.connections_count(); _finish_action(-1, actions::custom_variables); - SPDLOG_LOGGER_INFO(log_v2::sql(), - "SQL: disabling custom variable '{}' of ({}, {})", - cv.name(), cv.host_id(), cv.service_id()); + SPDLOG_LOGGER_INFO( + _logger_sql, "unified_sql: disabling custom variable '{}' of ({}, {})", + cv.name(), cv.host_id(), cv.service_id()); _custom_variable_delete.bind_value_as_i32_k(":host_id", cv.host_id()); _custom_variable_delete.bind_value_as_i32_k(":service_id", cv.service_id()); _custom_variable_delete.bind_value_as_str_k(":name", cv.name()); @@ -686,8 +682,8 @@ void stream::_process_pb_comment(const std::shared_ptr& d) { // Log message. SPDLOG_LOGGER_INFO( - log_v2::sql(), - "SQL: processing pb comment (poller: {}, host: {}, serv: {})", + _logger_sql, + "unified_sql: processing pb comment (poller: {}, host: {}, serv: {})", cmmnt.instance_id(), cmmnt.host_id(), cmmnt.service_id()); if (_comments->is_bulk()) { @@ -779,9 +775,9 @@ void stream::_process_custom_variable(const std::shared_ptr& d) { int conn = special_conn::custom_variable % _mysql.connections_count(); _finish_action(-1, actions::custom_variables); - SPDLOG_LOGGER_INFO(log_v2::sql(), - "SQL: disabling custom variable '{}' of ({}, {})", - cv.name, cv.host_id, cv.service_id); + SPDLOG_LOGGER_INFO( + _logger_sql, "unified_sql: disabling custom variable '{}' of ({}, {})", + cv.name, cv.host_id, cv.service_id); _custom_variable_delete.bind_value_as_i32_k(":host_id", cv.host_id); _custom_variable_delete.bind_value_as_i32_k(":service_id", cv.service_id); _custom_variable_delete.bind_value_as_str_k(":name", cv.name); @@ -813,9 +809,9 @@ void stream::_process_custom_variable_status( misc::string::escape( cv.value, get_customvariables_col_size(customvariables_value)))); - SPDLOG_LOGGER_INFO(log_v2::sql(), - "SQL: updating custom variable '{}' of ({}, {})", cv.name, - cv.host_id, cv.service_id); + SPDLOG_LOGGER_INFO(_logger_sql, + "unified_sql: updating custom variable '{}' of ({}, {})", + cv.name, cv.host_id, cv.service_id); } /** @@ -841,8 +837,8 @@ void stream::_process_pb_custom_variable_status( misc::string::escape( data.value(), get_customvariables_col_size(customvariables_value)))); - SPDLOG_LOGGER_INFO(log_v2::sql(), - "SQL: updating custom variable '{}' of ({}, {})", + SPDLOG_LOGGER_INFO(_logger_sql, + "unified_sql: updating custom variable '{}' of ({}, {})", data.name(), data.host_id(), data.service_id()); } @@ -858,8 +854,8 @@ void stream::_process_downtime(const std::shared_ptr& d) { const neb::downtime& dd = *static_cast(d.get()); // Log message. - SPDLOG_LOGGER_INFO(log_v2::sql(), - "SQL: processing downtime event (poller: {}" + SPDLOG_LOGGER_INFO(_logger_sql, + "unified_sql: processing downtime event (poller: {}" ", host: {}, service: {}, start time: {}, end_time: {}" ", actual start time: {}" ", actual end time: {}" @@ -920,10 +916,10 @@ void stream::_process_downtime(const std::shared_ptr& d) { }; _downtimes->add_bulk_row(binder); } else { - log_v2::sql()->error("original actual end time {} is null {}", - dd.actual_end_time.get_time_t(), - dd.actual_end_time.is_null()); - log_v2::sql()->error("actual end time {}", dd.actual_end_time); + _logger_sql->error("original actual end time {} is null {}", + dd.actual_end_time.get_time_t(), + dd.actual_end_time.is_null()); + _logger_sql->error("actual end time {}", dd.actual_end_time); _downtimes->add_multi_row(fmt::format( "({},{},'{}',{},{},{},{},{},{},{},{},{},{},{},{},{},{},'{}')", dd.actual_end_time.to_string(), dd.actual_start_time.to_string(), @@ -953,8 +949,8 @@ void stream::_process_pb_downtime(const std::shared_ptr& d) { auto& dt_obj = dd.obj(); // Log message. - SPDLOG_LOGGER_INFO(log_v2::sql(), - "SQL: processing pb downtime event (poller: {}" + SPDLOG_LOGGER_INFO(_logger_sql, + "unified_sql: processing pb downtime event (poller: {}" ", host: {}, service: {}, start time: {}, end_time: {}" ", actual start time: {}" ", actual end time: {}" @@ -1006,9 +1002,9 @@ void stream::_process_pb_downtime(const std::shared_ptr& d) { }; _downtimes->add_bulk_row(binder); } else { - log_v2::sql()->error("PB actual end time {} -> {}", - dt_obj.actual_end_time(), - uint64_not_null_not_neg_1{dt_obj.actual_end_time()}); + _logger_sql->error("PB actual end time {} -> {}", + dt_obj.actual_end_time(), + uint64_not_null_not_neg_1{dt_obj.actual_end_time()}); _downtimes->add_multi_row(fmt::format( "({},{},'{}',{},{},{},{},{},{},{},{},{},{},{},{},{},{},'{}')", uint64_not_null_not_neg_1{dt_obj.actual_end_time()}, @@ -1052,11 +1048,10 @@ void stream::_process_host_check(const std::shared_ptr& d) { // Cast object. neb::host_check const& hc = *static_cast(d.get()); if (!_host_instance_known(hc.host_id)) { - SPDLOG_LOGGER_WARN( - log_v2::sql(), - "SQL: host check for host{} thrown away because host is not known by " - "any poller", - hc.host_id); + SPDLOG_LOGGER_WARN(_logger_sql, + "unified_sql: host check for host{} thrown away because " + "host is not known by any poller", + hc.host_id); return; } @@ -1068,9 +1063,9 @@ void stream::_process_host_check(const std::shared_ptr& d) { !hc.next_check) { // - initial state // Apply to DB. SPDLOG_LOGGER_INFO( - log_v2::sql(), - "SQL: processing host check event (host: {}, command: {}", hc.host_id, - hc.command_line); + _logger_sql, + "unified_sql: processing host check event (host: {}, command: {}", + hc.host_id, hc.command_line); // Prepare queries. if (!_host_check_update.prepared()) { @@ -1101,11 +1096,12 @@ void stream::_process_host_check(const std::shared_ptr& d) { } } else // Do nothing. - SPDLOG_LOGGER_INFO( - log_v2::sql(), - "SQL: not processing host check event (host: {}, command: {}, check " - "type: {}, next check: {}, now: {})", - hc.host_id, hc.command_line, hc.check_type, hc.next_check, now); + SPDLOG_LOGGER_INFO(_logger_sql, + "unified_sql: not processing host check event (host: " + "{}, command: {}, check " + "type: {}, next check: {}, now: {})", + hc.host_id, hc.command_line, hc.check_type, + hc.next_check, now); } /** @@ -1125,11 +1121,11 @@ void stream::_process_pb_host_check(const std::shared_ptr& d) { *static_cast(d.get()); const HostCheck& hc = hc_obj.obj(); if (!_host_instance_known(hc.host_id())) { - SPDLOG_LOGGER_WARN( - log_v2::sql(), - "SQL: host check for host{} thrown away because host is not known by " - "any poller", - hc.host_id()); + SPDLOG_LOGGER_WARN(_logger_sql, + "unified_sql: host check for host{} thrown away because " + "host is not known by " + "any poller", + hc.host_id()); return; } @@ -1142,9 +1138,9 @@ void stream::_process_pb_host_check(const std::shared_ptr& d) { !hc.next_check()) { // - initial state // Apply to DB. SPDLOG_LOGGER_INFO( - log_v2::sql(), - "SQL: processing host check event (host: {}, command: {}", hc.host_id(), - hc.command_line()); + _logger_sql, + "unified_sql: processing host check event (host: {}, command: {}", + hc.host_id(), hc.command_line()); // Prepare queries. if (!_pb_host_check_update.prepared()) { @@ -1179,11 +1175,12 @@ void stream::_process_pb_host_check(const std::shared_ptr& d) { } } else // Do nothing. - SPDLOG_LOGGER_INFO( - log_v2::sql(), - "SQL: not processing host check event (host: {}, command: {}, check " - "type: {}, next check: {}, now: {})", - hc.host_id(), hc.command_line(), hc.check_type(), hc.next_check(), now); + SPDLOG_LOGGER_INFO(_logger_sql, + "unified_sql: not processing host check event (host: " + "{}, command: {}, check " + "type: {}, next check: {}, now: {})", + hc.host_id(), hc.command_line(), hc.check_type(), + hc.next_check(), now); } /** @@ -1206,7 +1203,7 @@ void stream::_process_host_dependency(const std::shared_ptr& d) { // Insert/Update. if (hd.enabled) { - SPDLOG_LOGGER_INFO(log_v2::sql(), + SPDLOG_LOGGER_INFO(_logger_sql, "SQL: enabling host dependency of {} on {}: execution " "failure options: {} - notification failure options: {}", hd.dependent_host_id, hd.host_id, @@ -1240,8 +1237,7 @@ void stream::_process_host_dependency(const std::shared_ptr& d) { } // Delete. else { - SPDLOG_LOGGER_INFO(log_v2::sql(), - "SQL: removing host dependency of {} on {}", + SPDLOG_LOGGER_INFO(_logger_sql, "SQL: removing host dependency of {} on {}", hd.dependent_host_id, hd.host_id); std::string query(fmt::format( "DELETE FROM hosts_hosts_dependencies WHERE dependent_host_id={}" @@ -1274,7 +1270,7 @@ void stream::_process_pb_host_dependency(const std::shared_ptr& d) { // Insert/Update. if (hd.enabled()) { SPDLOG_LOGGER_INFO( - log_v2::sql(), + _logger_sql, "SQL: enabling pb host dependency of {} on {}: execution failure " "options: {} - notification failure options: {}", hd.dependent_host_id(), hd.host_id(), hd.execution_failure_options(), @@ -1310,8 +1306,7 @@ void stream::_process_pb_host_dependency(const std::shared_ptr& d) { } // Delete. else { - SPDLOG_LOGGER_INFO(log_v2::sql(), - "SQL: removing host dependency of {} on {}", + SPDLOG_LOGGER_INFO(_logger_sql, "SQL: removing host dependency of {} on {}", hd.dependent_host_id(), hd.host_id()); std::string query(fmt::format( "DELETE FROM hosts_hosts_dependencies WHERE dependent_host_id={}" @@ -1336,9 +1331,10 @@ void stream::_process_host_group(const std::shared_ptr& d) { const neb::host_group& hg{*static_cast(d.get())}; if (hg.enabled) { - SPDLOG_LOGGER_INFO(log_v2::sql(), - "SQL: enabling host group {} ('{}' on instance {})", - hg.id, hg.name, hg.poller_id); + SPDLOG_LOGGER_INFO( + _logger_sql, + "unified_sql: enabling host group {} ('{}' on instance {})", hg.id, + hg.name, hg.poller_id); _prepare_hg_insupdate_statement(); _host_group_insupdate << hg; @@ -1348,9 +1344,10 @@ void stream::_process_host_group(const std::shared_ptr& d) { } // Delete group. else { - SPDLOG_LOGGER_INFO(log_v2::sql(), - "SQL: disabling host group {} ('{}' on instance {})", - hg.id, hg.name, hg.poller_id); + SPDLOG_LOGGER_INFO( + _logger_sql, + "unified_sql: disabling host group {} ('{}' on instance {})", hg.id, + hg.name, hg.poller_id); auto cache_ptr = cache::global_cache::instance_ptr(); if (cache_ptr) { @@ -1390,7 +1387,7 @@ void stream::_process_pb_host_group(const std::shared_ptr& d) { const HostGroup& hg = hgd->obj(); if (hg.enabled()) { - SPDLOG_LOGGER_INFO(log_v2::sql(), + SPDLOG_LOGGER_INFO(_logger_sql, "SQL: enabling host group {} ('{}' on instance {})", hg.hostgroup_id(), hg.name(), hg.poller_id()); _prepare_pb_hg_insupdate_statement(); @@ -1402,7 +1399,7 @@ void stream::_process_pb_host_group(const std::shared_ptr& d) { } // Delete group. else { - SPDLOG_LOGGER_INFO(log_v2::sql(), + SPDLOG_LOGGER_INFO(_logger_sql, "SQL: disabling host group {} ('{}' on instance {})", hg.hostgroup_id(), hg.name(), hg.poller_id()); @@ -1445,7 +1442,7 @@ void stream::_process_host_group_member(const std::shared_ptr& d) { if (!_host_instance_known(hgm.host_id)) { SPDLOG_LOGGER_WARN( - log_v2::sql(), + _logger_sql, "SQL: host {0} not added to hostgroup {1} because host {0} is not " "known by any poller", hgm.host_id, hgm.group_id); @@ -1457,7 +1454,7 @@ void stream::_process_host_group_member(const std::shared_ptr& d) { if (hgm.enabled) { // Log message. SPDLOG_LOGGER_INFO( - log_v2::sql(), + _logger_sql, "SQL: enabling membership of host {} to host group {} on instance {}", hgm.host_id, hgm.group_id, hgm.poller_id); @@ -1477,7 +1474,7 @@ void stream::_process_host_group_member(const std::shared_ptr& d) { /* If the group does not exist, we create it. */ if (_cache_host_instance[hgm.host_id]) { if (_hostgroup_cache.find(hgm.group_id) == _hostgroup_cache.end()) { - SPDLOG_LOGGER_ERROR(log_v2::sql(), + SPDLOG_LOGGER_ERROR(_logger_sql, "SQL: host group {} {} does not exist - insertion " "before insertion of " "members", @@ -1503,7 +1500,7 @@ void stream::_process_host_group_member(const std::shared_ptr& d) { _add_action(conn, actions::hostgroups); } else SPDLOG_LOGGER_ERROR( - log_v2::sql(), + _logger_sql, "SQL: host with host_id = {} does not exist - unable to store " "unexisting host in a hostgroup. You should restart centengine.", hgm.host_id); @@ -1512,7 +1509,7 @@ void stream::_process_host_group_member(const std::shared_ptr& d) { else { // Log message. SPDLOG_LOGGER_INFO( - log_v2::sql(), + _logger_sql, "SQL: disabling membership of host {} to host group {} on instance {}", hgm.host_id, hgm.group_id, hgm.poller_id); @@ -1552,7 +1549,7 @@ void stream::_process_pb_host_group_member(const std::shared_ptr& d) { if (!_host_instance_known(hgm.host_id())) { SPDLOG_LOGGER_WARN( - log_v2::sql(), + _logger_sql, "SQL: host {0} not added to hostgroup {1} because host {0} is not " "known by any poller", hgm.host_id(), hgm.hostgroup_id()); @@ -1564,7 +1561,7 @@ void stream::_process_pb_host_group_member(const std::shared_ptr& d) { if (hgm.enabled()) { // Log message. SPDLOG_LOGGER_INFO( - log_v2::sql(), + _logger_sql, "SQL: enabling membership of host {} to host group {} on instance {}", hgm.host_id(), hgm.hostgroup_id(), hgm.poller_id()); @@ -1589,7 +1586,7 @@ void stream::_process_pb_host_group_member(const std::shared_ptr& d) { /* If the group does not exist, we create it. */ if (_cache_host_instance[hgm.host_id()]) { if (_hostgroup_cache.find(hgm.hostgroup_id()) == _hostgroup_cache.end()) { - SPDLOG_LOGGER_ERROR(log_v2::sql(), + SPDLOG_LOGGER_ERROR(_logger_sql, "SQL: host group {} {} does not exist - insertion " "before insertion of " "members", @@ -1615,7 +1612,7 @@ void stream::_process_pb_host_group_member(const std::shared_ptr& d) { _add_action(conn, actions::hostgroups); } else SPDLOG_LOGGER_ERROR( - log_v2::sql(), + _logger_sql, "SQL: host with host_id = {} does not exist - unable to store " "unexisting host in a hostgroup. You should restart centengine.", hgm.host_id()); @@ -1624,7 +1621,7 @@ void stream::_process_pb_host_group_member(const std::shared_ptr& d) { else { // Log message. SPDLOG_LOGGER_INFO( - log_v2::sql(), + _logger_sql, "SQL: disabling membership of host {} to host group {} on instance {}", hgm.host_id(), hgm.hostgroup_id(), hgm.poller_id()); @@ -1658,7 +1655,7 @@ void stream::_process_host(const std::shared_ptr& d) { // Log message. SPDLOG_LOGGER_INFO( - log_v2::sql(), + _logger_sql, "SQL: processing host event (poller: {}, host: {}, name: {})", h.poller_id, h.host_id, h.host_name); @@ -1696,7 +1693,7 @@ void stream::_process_host(const std::shared_ptr& d) { _cache_host_instance.erase(h.host_id); } else SPDLOG_LOGGER_TRACE( - log_v2::sql(), + _logger_sql, "SQL: host '{}' of poller {} has no ID nor alias, probably bam " "fake host", h.host_name, h.poller_id); @@ -1720,7 +1717,7 @@ void stream::_process_host_parent(const std::shared_ptr& d) { // Enable parenting. if (hp.enabled) { // Log message. - SPDLOG_LOGGER_INFO(log_v2::sql(), "SQL: host {} is parent of host {}", + SPDLOG_LOGGER_INFO(_logger_sql, "unified_sql: host {} is parent of host {}", hp.parent_id, hp.host_id); // Prepare queries. @@ -1737,8 +1734,8 @@ void stream::_process_host_parent(const std::shared_ptr& d) { } // Disable parenting. else { - SPDLOG_LOGGER_INFO(log_v2::sql(), - "SQL: host {} is not parent of host {} anymore", + SPDLOG_LOGGER_INFO(_logger_sql, + "unified_sql: host {} is not parent of host {} anymore", hp.parent_id, hp.host_id); // Prepare queries. @@ -1777,7 +1774,7 @@ void stream::_process_pb_host_parent(const std::shared_ptr& d) { // Enable parenting. if (hp.enabled()) { // Log message. - SPDLOG_LOGGER_INFO(log_v2::sql(), "SQL: pb host {} is parent of host {}", + SPDLOG_LOGGER_INFO(_logger_sql, "SQL: pb host {} is parent of host {}", hp.parent_id(), hp.child_id()); // Prepare queries. @@ -1801,7 +1798,7 @@ void stream::_process_pb_host_parent(const std::shared_ptr& d) { } // Disable parenting. else { - SPDLOG_LOGGER_INFO(log_v2::sql(), + SPDLOG_LOGGER_INFO(_logger_sql, "SQL: pb host {} is not parent of host {} anymore", hp.parent_id(), hp.child_id()); @@ -1843,11 +1840,11 @@ void stream::_process_host_status(const std::shared_ptr& d) { neb::host_status const& hs(*static_cast(d.get())); if (!_host_instance_known(hs.host_id)) { - SPDLOG_LOGGER_WARN( - log_v2::sql(), - "SQL: host status {0} thrown away because host {0} is not known by any " - "poller", - hs.host_id); + SPDLOG_LOGGER_WARN(_logger_sql, + "unified_sql: host status {0} thrown away because host " + "{0} is not known by any " + "poller", + hs.host_id); return; } time_t now = time(nullptr); @@ -1858,7 +1855,7 @@ void stream::_process_host_status(const std::shared_ptr& d) { !hs.next_check) { // - initial state // Apply to DB. SPDLOG_LOGGER_INFO( - log_v2::sql(), + _logger_sql, "processing host status event (host: {}, last check: {}, state ({}, " "{}))", hs.host_id, hs.last_check, hs.current_state, hs.state_type); @@ -1880,12 +1877,12 @@ void stream::_process_host_status(const std::shared_ptr& d) { _add_action(conn, actions::hosts); } else // Do nothing. - SPDLOG_LOGGER_INFO( - log_v2::sql(), - "SQL: not processing host status event (id: {}, check type: {}, last " - "check: {}, next check: {}, now: {}, state: ({}, {}))", - hs.host_id, hs.check_type, hs.last_check, hs.next_check, now, - hs.current_state, hs.state_type); + SPDLOG_LOGGER_INFO(_logger_sql, + "unified_sql: not processing host status event (id: {}, " + "check type: {}, last " + "check: {}, next check: {}, now: {}, state: ({}, {}))", + hs.host_id, hs.check_type, hs.last_check, hs.next_check, + now, hs.current_state, hs.state_type); } /** @@ -1907,8 +1904,8 @@ void stream::_process_pb_host(const std::shared_ptr& d) { // Log message. SPDLOG_LOGGER_INFO( - log_v2::sql(), - "SQL: processing pb host event (poller: {}, host: {}, name: {})", + _logger_sql, + "unified_sql: processing pb host event (poller: {}, host: {}, name: {})", h.instance_id(), h.host_id(), h.name()); auto cache_ptr = cache::global_cache::instance_ptr(); @@ -2081,11 +2078,11 @@ void stream::_process_pb_host(const std::shared_ptr& d) { }); } } else - SPDLOG_LOGGER_TRACE( - log_v2::sql(), - "SQL: host '{}' of poller {} has no ID nor alias, probably bam " - "fake host", - h.name(), h.instance_id()); + SPDLOG_LOGGER_TRACE(_logger_sql, + "unified_sql: host '{}' of poller {} has no ID nor " + "alias, probably bam " + "fake host", + h.name(), h.instance_id()); } } @@ -2130,11 +2127,11 @@ uint64_t stream::_process_pb_host_in_resources(const Host& h, int32_t conn) { 9, _cache_host_instance[h.host_id()]); if (h.severity_id()) { sid = _severity_cache[{h.severity_id(), 1}]; - SPDLOG_LOGGER_DEBUG(log_v2::sql(), + SPDLOG_LOGGER_DEBUG(_logger_sql, "host {} with severity_id {} => uid = {}", h.host_id(), h.severity_id(), sid); } else - SPDLOG_LOGGER_INFO(log_v2::sql(), + SPDLOG_LOGGER_INFO(_logger_sql, "no host severity found in cache for host {}", h.host_id()); if (sid) @@ -2163,7 +2160,7 @@ uint64_t stream::_process_pb_host_in_resources(const Host& h, int32_t conn) { res_id = future.get(); _resource_cache.insert({{h.host_id(), 0}, res_id}); } catch (const std::exception& e) { - SPDLOG_LOGGER_CRITICAL(log_v2::sql(), + SPDLOG_LOGGER_CRITICAL(_logger_sql, "SQL: unable to insert new host resource {}: {}", h.host_id(), e.what()); @@ -2182,31 +2179,31 @@ uint64_t stream::_process_pb_host_in_resources(const Host& h, int32_t conn) { _resource_cache.insert({{h.host_id(), 0}, res.value_as_u64(0)}); found = r.first; SPDLOG_LOGGER_DEBUG( - log_v2::sql(), + _logger_sql, "Host resource (host {}) found in database with id {}", h.host_id(), found->second); } else { SPDLOG_LOGGER_CRITICAL( - log_v2::sql(), + _logger_sql, "Could not insert host resource in database and no host " "resource in database with id {}: {}", h.host_id(), e.what()); return 0; } } catch (const std::exception& e) { - SPDLOG_LOGGER_CRITICAL(log_v2::sql(), + SPDLOG_LOGGER_CRITICAL(_logger_sql, "No host resource in database with id {}: {}", h.host_id(), e.what()); return 0; } } - SPDLOG_LOGGER_DEBUG(log_v2::sql(), "insert resource {} for host{}", - res_id, h.host_id()); + SPDLOG_LOGGER_DEBUG(_logger_sql, "insert resource {} for host{}", res_id, + h.host_id()); } if (res_id == 0) { res_id = found->second; - SPDLOG_LOGGER_DEBUG(log_v2::sql(), "update resource {} for host{}", - res_id, h.host_id()); + SPDLOG_LOGGER_DEBUG(_logger_sql, "update resource {} for host{}", res_id, + h.host_id()); // UPDATE _resources_host_update.bind_value_as_u32(0, h.state()); _resources_host_update.bind_value_as_u32(1, @@ -2225,11 +2222,11 @@ uint64_t stream::_process_pb_host_in_resources(const Host& h, int32_t conn) { 8, _cache_host_instance[h.host_id()]); if (h.severity_id()) { sid = _severity_cache[{h.severity_id(), 1}]; - SPDLOG_LOGGER_DEBUG(log_v2::sql(), + SPDLOG_LOGGER_DEBUG(_logger_sql, "host {} with severity_id {} => uid = {}", h.host_id(), h.severity_id(), sid); } else - SPDLOG_LOGGER_INFO(log_v2::sql(), + SPDLOG_LOGGER_INFO(_logger_sql, "no host severity found in cache for host {}", h.host_id()); if (sid) @@ -2267,7 +2264,7 @@ uint64_t stream::_process_pb_host_in_resources(const Host& h, int32_t conn) { _mysql.run_statement(_resources_tags_remove, database::mysql_error::delete_resources_tags, conn); for (auto& tag : h.tags()) { - SPDLOG_LOGGER_DEBUG(log_v2::sql(), + SPDLOG_LOGGER_DEBUG(_logger_sql, "add tag ({}, {}) for resource {} for host{}", tag.id(), tag.type(), res_id, h.host_id()); @@ -2275,7 +2272,7 @@ uint64_t stream::_process_pb_host_in_resources(const Host& h, int32_t conn) { if (it_tags_cache == _tags_cache.end()) { SPDLOG_LOGGER_ERROR( - log_v2::sql(), + _logger_sql, "SQL: could not find in cache the tag ({}, {}) for host " "'{}': " "trying to add it.", @@ -2296,7 +2293,7 @@ uint64_t stream::_process_pb_host_in_resources(const Host& h, int32_t conn) { it_tags_cache = _tags_cache.insert({{tag.id(), tag.type()}, tag_id}).first; } catch (const std::exception& e) { - SPDLOG_LOGGER_ERROR(log_v2::sql(), + SPDLOG_LOGGER_ERROR(_logger_sql, "SQL: unable to insert new tag ({},{}): {}", tag.id(), tag.type(), e.what()); } @@ -2306,7 +2303,7 @@ uint64_t stream::_process_pb_host_in_resources(const Host& h, int32_t conn) { _resources_tags_insert.bind_value_as_u64(0, it_tags_cache->second); _resources_tags_insert.bind_value_as_u64(1, res_id); SPDLOG_LOGGER_DEBUG( - log_v2::sql(), + _logger_sql, "SQL: new relation between host (resource_id: {}, host_id: " "{}) " "and tag ({},{},{})", @@ -2327,8 +2324,8 @@ uint64_t stream::_process_pb_host_in_resources(const Host& h, int32_t conn) { _add_action(conn, actions::resources); } else { SPDLOG_LOGGER_INFO( - log_v2::sql(), - "SQL: no need to remove host {}, it is not in database", h.host_id()); + _logger_sql, "SQL: no need to remove host {}, it is not in database", + h.host_id()); } } return res_id; @@ -2341,7 +2338,7 @@ uint64_t stream::_process_pb_host_in_resources(const Host& h, int32_t conn) { * */ void stream::_process_pb_adaptive_host(const std::shared_ptr& d) { - SPDLOG_LOGGER_INFO(log_v2::sql(), "SQL: processing pb adaptive host"); + SPDLOG_LOGGER_INFO(_logger_sql, "unified_sql: processing pb adaptive host"); _finish_action(-1, actions::host_parents | actions::comments | actions::downtimes | actions::host_dependencies | actions::service_dependencies); @@ -2349,10 +2346,10 @@ void stream::_process_pb_adaptive_host(const std::shared_ptr& d) { auto h{static_cast(d.get())}; auto& ah = h->obj(); if (!_host_instance_known(ah.host_id())) { - SPDLOG_LOGGER_WARN( - log_v2::sql(), - "SQL: adaptive host on host {} thrown away because host not known", - ah.host_id()); + SPDLOG_LOGGER_WARN(_logger_sql, + "unified_sql: adaptive host on host {} thrown away " + "because host not known", + ah.host_id()); return; } int32_t conn = _mysql.choose_connection_by_instance( @@ -2412,7 +2409,7 @@ void stream::_process_pb_adaptive_host(const std::shared_ptr& d) { if (query.size() > buf.size()) { query.resize(query.size() - 1); query += fmt::format(" WHERE host_id={}", ah.host_id()); - SPDLOG_LOGGER_TRACE(log_v2::sql(), "SQL: query <<{}>>", query); + SPDLOG_LOGGER_TRACE(_logger_sql, "unified_sql: query <<{}>>", query); _mysql.run_query(query, database::mysql_error::store_host, conn); _add_action(conn, actions::hosts); @@ -2435,7 +2432,8 @@ void stream::_process_pb_adaptive_host(const std::shared_ptr& d) { if (res_query.size() > res_buf.size()) { res_query.resize(res_query.size() - 1); res_query += fmt::format(" WHERE parent_id=0 AND id={}", ah.host_id()); - SPDLOG_LOGGER_TRACE(log_v2::sql(), "SQL: query <<{}>>", res_query); + SPDLOG_LOGGER_TRACE(_logger_sql, "unified_sql: query <<{}>>", + res_query); _mysql.run_query(res_query, database::mysql_error::update_resources, conn); _add_action(conn, actions::resources); @@ -2457,19 +2455,19 @@ void stream::_process_pb_host_status(const std::shared_ptr& d) { auto h{static_cast(d.get())}; auto& hscr = h->obj(); - SPDLOG_LOGGER_DEBUG(log_v2::sql(), - "SQL: pb host status check result output: <<{}>>", + SPDLOG_LOGGER_DEBUG(_logger_sql, + "unified_sql: pb host status check result output: <<{}>>", hscr.output()); - SPDLOG_LOGGER_DEBUG(log_v2::sql(), - "SQL: pb host status check result perfdata: <<{}>>", - hscr.perfdata()); + SPDLOG_LOGGER_DEBUG( + _logger_sql, "unified_sql: pb host status check result perfdata: <<{}>>", + hscr.perfdata()); if (!_host_instance_known(hscr.host_id())) { - SPDLOG_LOGGER_WARN( - log_v2::sql(), - "SQL: pb host status {} thrown away because host {} is not known by " - "any poller", - hscr.host_id(), hscr.host_id()); + SPDLOG_LOGGER_WARN(_logger_sql, + "unified_sql: pb host status {} thrown away because " + "host {} is not known by " + "any poller", + hscr.host_id(), hscr.host_id()); return; } time_t now = time(nullptr); @@ -2477,11 +2475,12 @@ void stream::_process_pb_host_status(const std::shared_ptr& d) { hscr.next_check() >= now - 5 * 60 || // usual case hscr.next_check() == 0) { // initial state // Apply to DB. - SPDLOG_LOGGER_INFO( - log_v2::sql(), - "SQL: processing host status check result event proto (host: {}, " - "last check: {}, state ({}, {}))", - hscr.host_id(), hscr.last_check(), hscr.state(), hscr.state_type()); + SPDLOG_LOGGER_INFO(_logger_sql, + "unified_sql: processing host status check result event " + "proto (host: {}, " + "last check: {}, state ({}, {}))", + hscr.host_id(), hscr.last_check(), hscr.state(), + hscr.state_type()); // Processing. if (_store_in_hosts_services) { @@ -2537,7 +2536,7 @@ void stream::_process_pb_host_status(const std::shared_ptr& d) { b->set_value_as_i32(26, hscr.scheduled_downtime_depth()); b->set_value_as_i32(27, hscr.host_id()); b->next_row(); - SPDLOG_LOGGER_TRACE(log_v2::sql(), + SPDLOG_LOGGER_TRACE(_logger_sql, "{} waiting updates for host status in hosts", b->current_row()); } else { @@ -2648,8 +2647,9 @@ void stream::_process_pb_host_status(const std::shared_ptr& d) { } else // Do nothing. SPDLOG_LOGGER_INFO( - log_v2::sql(), - "SQL: not processing pb host status check result event (host: {}, " + _logger_sql, + "unified_sql: not processing pb host status check result event (host: " + "{}, " "check type: {}, last check: {}, next check: {}, now: {}, state ({}, " "{}))", hscr.host_id(), hscr.check_type(), hscr.last_check(), hscr.next_check(), @@ -2676,8 +2676,8 @@ void stream::_process_instance(const std::shared_ptr& d) { // Log message. SPDLOG_LOGGER_INFO( - log_v2::sql(), - "SQL: processing poller event (id: {}, name: {}, running: {})", + _logger_sql, + "unified_sql: processing poller event (id: {}, name: {}, running: {})", i.poller_id, i.name, i.is_running ? "yes" : "no"); // Clean tables. @@ -2726,10 +2726,12 @@ void stream::_process_pb_instance(const std::shared_ptr& d) { actions::hostgroups | actions::service_dependencies | actions::host_dependencies); + /* Now, the local::pb_stop is handled by unified_sql. So the pb_instance with + * running = false, seems no more useful. */ // Log message. SPDLOG_LOGGER_INFO( - log_v2::sql(), - "SQL: processing poller event (id: {}, name: {}, running: {})", + _logger_sql, + "unified_sql: processing poller event (id: {}, name: {}, running: {})", inst.instance_id(), inst.name(), inst.running() ? "yes" : "no"); // Clean tables. @@ -2785,8 +2787,8 @@ void stream::_process_instance_status(const std::shared_ptr& d) { // Log message. SPDLOG_LOGGER_INFO( - log_v2::sql(), - "SQL: processing poller status event (id: {}, last alive: {})", + _logger_sql, + "unified_sql: processing poller status event (id: {}, last alive: {})", is.poller_id, is.last_alive); // Processing. @@ -2829,8 +2831,8 @@ void stream::_process_pb_instance_status(const std::shared_ptr& d) { // Log message. SPDLOG_LOGGER_DEBUG( - log_v2::sql(), - "SQL: processing poller status event (id: {}, last alive: {} {})", + _logger_sql, + "unified_sql: processing poller status event (id: {}, last alive: {} {})", is.instance_id(), is.last_alive(), is.ShortDebugString()); // Processing. @@ -2883,8 +2885,8 @@ void stream::_process_log(const std::shared_ptr& d) { // Log message. SPDLOG_LOGGER_INFO( - log_v2::sql(), - "SQL: processing log of poller '{}' generated at {} (type {})", + _logger_sql, + "unified_sql: processing log of poller '{}' generated at {} (type {})", le.poller_name, le.c_time, le.msg_type); // Push query. @@ -2951,8 +2953,8 @@ void stream::_process_pb_log(const std::shared_ptr& d) { // Log message. SPDLOG_LOGGER_INFO( - log_v2::sql(), - "SQL: processing pb log of poller '{}' generated at {} (type {})", + _logger_sql, + "unified_sql: processing pb log of poller '{}' generated at {} (type {})", le_obj.instance_name(), le_obj.ctime(), le_obj.msg_type()); if (_logs->is_bulk()) { @@ -3023,11 +3025,11 @@ void stream::_process_service_check(const std::shared_ptr& d) { *static_cast(d.get())); if (!_host_instance_known(sc.host_id)) { - SPDLOG_LOGGER_WARN( - log_v2::sql(), - "SQL: service check on service ({}, {}) thrown away because host " - "unknown", - sc.host_id, sc.service_id); + SPDLOG_LOGGER_WARN(_logger_sql, + "unified_sql: service check on service ({}, {}) thrown " + "away because host " + "unknown", + sc.host_id, sc.service_id); return; } time_t now{time(nullptr)}; @@ -3038,8 +3040,8 @@ void stream::_process_service_check(const std::shared_ptr& d) { || (sc.next_check >= now - 5 * 60) || !sc.next_check) { // - initial state // Apply to DB. - SPDLOG_LOGGER_INFO(log_v2::sql(), - "SQL: processing service check event (host: {}, " + SPDLOG_LOGGER_INFO(_logger_sql, + "unified_sql: processing service check event (host: {}, " "service: {}, command: " "{})", sc.host_id, sc.service_id, sc.command_line); @@ -3072,12 +3074,12 @@ void stream::_process_service_check(const std::shared_ptr& d) { } } else // Do nothing. - SPDLOG_LOGGER_INFO( - log_v2::sql(), - "SQL: not processing service check event (host: {}, service: {}, " - "command: {}, check_type: {}, next_check: {}, now: {})", - sc.host_id, sc.service_id, sc.command_line, sc.check_type, - sc.next_check, now); + SPDLOG_LOGGER_INFO(_logger_sql, + "unified_sql: not processing service check event (host: " + "{}, service: {}, " + "command: {}, check_type: {}, next_check: {}, now: {})", + sc.host_id, sc.service_id, sc.command_line, + sc.check_type, sc.next_check, now); } /** @@ -3098,11 +3100,11 @@ void stream::_process_pb_service_check(const std::shared_ptr& d) { const ServiceCheck& sc(pb_sc.obj()); if (!_host_instance_known(sc.host_id())) { - SPDLOG_LOGGER_WARN( - log_v2::sql(), - "SQL: service check on service ({}, {}) thrown away because host " - "unknown", - sc.host_id(), sc.service_id()); + SPDLOG_LOGGER_WARN(_logger_sql, + "unified_sql: service check on service ({}, {}) thrown " + "away because host " + "unknown", + sc.host_id(), sc.service_id()); return; } time_t now{time(nullptr)}; @@ -3111,14 +3113,14 @@ void stream::_process_pb_service_check(const std::shared_ptr& d) { || !sc.active_checks_enabled() // - active checks are disabled, // status might not be updated // - normal case - || (sc.next_check() >= now - 5 * 60) || + || (static_cast(sc.next_check()) >= now - 5 * 60) || !sc.next_check()) { // - initial state // Apply to DB. - SPDLOG_LOGGER_INFO( - log_v2::sql(), - "SQL: processing service check event (host: {}, service: {}, command: " - "{})", - sc.host_id(), sc.service_id(), sc.command_line()); + SPDLOG_LOGGER_INFO(_logger_sql, + "unified_sql: processing service check event (host: {}, " + "service: {}, command: " + "{})", + sc.host_id(), sc.service_id(), sc.command_line()); // Prepare queries. if (!_pb_service_check_update.prepared()) { @@ -3154,12 +3156,12 @@ void stream::_process_pb_service_check(const std::shared_ptr& d) { } } else // Do nothing. - SPDLOG_LOGGER_INFO( - log_v2::sql(), - "SQL: not processing service check event (host: {}, service: {}, " - "command: {}, check_type: {}, next_check: {}, now: {})", - sc.host_id(), sc.service_id(), sc.command_line(), sc.check_type(), - sc.next_check(), now); + SPDLOG_LOGGER_INFO(_logger_sql, + "unified_sql: not processing service check event (host: " + "{}, service: {}, " + "command: {}, check_type: {}, next_check: {}, now: {})", + sc.host_id(), sc.service_id(), sc.command_line(), + sc.check_type(), sc.next_check(), now); } /** @@ -3183,8 +3185,7 @@ void stream::_process_service_dependency(const std::shared_ptr& d) { // Insert/Update. if (sd.enabled) { SPDLOG_LOGGER_INFO( - log_v2::sql(), - "SQL: enabling service dependency of ({}, {}) on ({}, {})", + _logger_sql, "SQL: enabling service dependency of ({}, {}) on ({}, {})", sd.dependent_host_id, sd.dependent_service_id, sd.host_id, sd.service_id); @@ -3208,8 +3209,7 @@ void stream::_process_service_dependency(const std::shared_ptr& d) { // Delete. else { SPDLOG_LOGGER_INFO( - log_v2::sql(), - "SQL: removing service dependency of ({}, {}) on ({}, {})", + _logger_sql, "SQL: removing service dependency of ({}, {}) on ({}, {})", sd.dependent_host_id, sd.dependent_service_id, sd.host_id, sd.service_id); std::string query(fmt::format( @@ -3245,8 +3245,7 @@ void stream::_process_pb_service_dependency( // Insert/Update. if (sd.enabled()) { SPDLOG_LOGGER_INFO( - log_v2::sql(), - "SQL: enabling service dependency of ({}, {}) on ({}, {})", + _logger_sql, "SQL: enabling service dependency of ({}, {}) on ({}, {})", sd.dependent_host_id(), sd.dependent_service_id(), sd.host_id(), sd.service_id()); @@ -3286,8 +3285,7 @@ void stream::_process_pb_service_dependency( // Delete. else { SPDLOG_LOGGER_INFO( - log_v2::sql(), - "SQL: removing service dependency of ({}, {}) on ({}, {})", + _logger_sql, "SQL: removing service dependency of ({}, {}) on ({}, {})", sd.dependent_host_id(), sd.dependent_service_id(), sd.host_id(), sd.service_id()); std::string query(fmt::format( @@ -3316,9 +3314,10 @@ void stream::_process_service_group(const std::shared_ptr& d) { // Insert/update group. if (sg.enabled) { - SPDLOG_LOGGER_INFO(log_v2::sql(), - "SQL: enabling service group {} ('{}' on instance {})", - sg.id, sg.name, sg.poller_id); + SPDLOG_LOGGER_INFO( + _logger_sql, + "unified_sql: enabling service group {} ('{}' on instance {})", sg.id, + sg.name, sg.poller_id); _prepare_sg_insupdate_statement(); _service_group_insupdate << sg; @@ -3328,9 +3327,10 @@ void stream::_process_service_group(const std::shared_ptr& d) { } // Delete group. else { - SPDLOG_LOGGER_INFO(log_v2::sql(), - "SQL: disabling service group {} ('{}' on instance {})", - sg.id, sg.name, sg.poller_id); + SPDLOG_LOGGER_INFO( + _logger_sql, + "unified_sql: disabling service group {} ('{}' on instance {})", sg.id, + sg.name, sg.poller_id); auto cache_ptr = cache::global_cache::instance_ptr(); if (cache_ptr) { cache_ptr->remove_service_group_members(sg.id, sg.poller_id); @@ -3371,7 +3371,7 @@ void stream::_process_pb_service_group(const std::shared_ptr& d) { // Insert/update group. if (sg.enabled()) { - SPDLOG_LOGGER_INFO(log_v2::sql(), + SPDLOG_LOGGER_INFO(_logger_sql, "SQL: enabling service group {} ('{}' on instance {})", sg.servicegroup_id(), sg.name(), sg.poller_id()); _prepare_pb_sg_insupdate_statement(); @@ -3383,7 +3383,7 @@ void stream::_process_pb_service_group(const std::shared_ptr& d) { } // Delete group. else { - SPDLOG_LOGGER_INFO(log_v2::sql(), + SPDLOG_LOGGER_INFO(_logger_sql, "SQL: disabling service group {} ('{}' on instance {})", sg.servicegroup_id(), sg.name(), sg.poller_id()); auto cache_ptr = cache::global_cache::instance_ptr(); @@ -3428,11 +3428,12 @@ void stream::_process_service_group_member(const std::shared_ptr& d) { auto cache_ptr = cache::global_cache::instance_ptr(); if (sgm.enabled) { // Log message. - SPDLOG_LOGGER_INFO( - log_v2::sql(), - "SQL: enabling membership of service ({}, {}) to service group {} on " - "instance {}", - sgm.host_id, sgm.service_id, sgm.group_id, sgm.poller_id); + SPDLOG_LOGGER_INFO(_logger_sql, + "unified_sql: enabling membership of service ({}, {}) " + "to service group {} on " + "instance {}", + sgm.host_id, sgm.service_id, sgm.group_id, + sgm.poller_id); if (cache_ptr) { cache_ptr->add_service_to_group(sgm.group_id, sgm.host_id, sgm.service_id, @@ -3451,11 +3452,11 @@ void stream::_process_service_group_member(const std::shared_ptr& d) { /* If the group does not exist, we create it. */ if (_servicegroup_cache.find(sgm.group_id) == _servicegroup_cache.end()) { - SPDLOG_LOGGER_ERROR( - log_v2::sql(), - "SQL: service group {} does not exist - insertion before insertion " - "of members", - sgm.group_id); + SPDLOG_LOGGER_ERROR(_logger_sql, + "unified_sql: service group {} does not exist - " + "insertion before insertion " + "of members", + sgm.group_id); _prepare_sg_insupdate_statement(); neb::service_group sg; @@ -3479,12 +3480,12 @@ void stream::_process_service_group_member(const std::shared_ptr& d) { // Delete. else { // Log message. - SPDLOG_LOGGER_INFO(log_v2::sql(), - "SQL: disabling membership of service ({}, {}) to " - "service group {} on " - "instance {}", - sgm.host_id, sgm.service_id, sgm.group_id, - sgm.poller_id); + SPDLOG_LOGGER_INFO( + _logger_sql, + "unified_sql: disabling membership of service ({}, {}) to " + "service group {} on " + "instance {}", + sgm.host_id, sgm.service_id, sgm.group_id, sgm.poller_id); if (cache_ptr) { cache_ptr->remove_service_from_group(sgm.group_id, sgm.host_id, @@ -3529,7 +3530,7 @@ void stream::_process_pb_service_group_member( if (sgm.enabled()) { // Log message. SPDLOG_LOGGER_INFO( - log_v2::sql(), + _logger_sql, "SQL: enabling membership of service ({}, {}) to service group {} on " "instance {}", sgm.host_id(), sgm.service_id(), sgm.servicegroup_id(), @@ -3562,7 +3563,7 @@ void stream::_process_pb_service_group_member( if (_servicegroup_cache.find(sgm.servicegroup_id()) == _servicegroup_cache.end()) { SPDLOG_LOGGER_ERROR( - log_v2::sql(), + _logger_sql, "SQL: service group {} does not exist - insertion before insertion " "of members", sgm.servicegroup_id()); @@ -3589,7 +3590,7 @@ void stream::_process_pb_service_group_member( // Delete. else { // Log message. - SPDLOG_LOGGER_INFO(log_v2::sql(), + SPDLOG_LOGGER_INFO(_logger_sql, "SQL: disabling membership of service ({}, {}) to " "service group {} on " "instance {}", @@ -3635,8 +3636,8 @@ void stream::_process_service(const std::shared_ptr& d) { const neb::service& s(*static_cast(d.get())); if (!_host_instance_known(s.host_id)) { SPDLOG_LOGGER_WARN( - log_v2::sql(), - "SQL: service ({0}, {1}) thrown away because host {0} unknown", + _logger_sql, + "unified_sql: service ({0}, {1}) thrown away because host {0} unknown", s.host_id, s.service_id); return; } @@ -3646,10 +3647,11 @@ void stream::_process_service(const std::shared_ptr& d) { _mysql.choose_connection_by_instance(_cache_host_instance[s.host_id]); // Log message. - SPDLOG_LOGGER_INFO(log_v2::sql(), - "SQL: processing service event (host: {}, service: {}, " - "description: {})", - s.host_id, s.service_id, s.service_description); + SPDLOG_LOGGER_INFO( + _logger_sql, + "unified_sql: processing service event (host: {}, service: {}, " + "description: {})", + s.host_id, s.service_id, s.service_description); if (s.host_id && s.service_id) { if (cache_ptr) { @@ -3670,11 +3672,11 @@ void stream::_process_service(const std::shared_ptr& d) { database::mysql_error::store_service, conn); _add_action(conn, actions::services); } else - SPDLOG_LOGGER_TRACE( - log_v2::sql(), - "SQL: service '{}' has no host ID, service ID nor hostname, probably " - "bam fake service", - s.service_description); + SPDLOG_LOGGER_TRACE(_logger_sql, + "unified_sql: service '{}' has no host ID, service ID " + "nor hostname, probably " + "bam fake service", + s.service_description); } /** @@ -3691,17 +3693,17 @@ void stream::_process_pb_service(const std::shared_ptr& d) { // Processed object. auto svc{static_cast(d.get())}; auto& s = svc->obj(); - SPDLOG_LOGGER_DEBUG( - log_v2::sql(), - "SQL: processing pb service ({}, {}) state: {} state_type: {}", - s.host_id(), s.service_id(), s.state(), s.state_type()); - SPDLOG_LOGGER_TRACE(log_v2::sql(), "SQL: pb service output: <<{}>>", + SPDLOG_LOGGER_DEBUG(_logger_sql, + "unified_sql: processing pb service ({}, {}) state: {} " + "state_type: {}", + s.host_id(), s.service_id(), s.state(), s.state_type()); + SPDLOG_LOGGER_TRACE(_logger_sql, "unified_sql: pb service output: <<{}>>", s.output()); // Processed object. if (!_host_instance_known(s.host_id())) { SPDLOG_LOGGER_WARN( - log_v2::sql(), + _logger_sql, "pb service ({0}, {1}) thrown away because host {0} unknown", s.host_id(), s.service_id()); return; @@ -3713,10 +3715,11 @@ void stream::_process_pb_service(const std::shared_ptr& d) { _mysql.choose_connection_by_instance(_cache_host_instance[s.host_id()]); // Log message. - SPDLOG_LOGGER_INFO(log_v2::sql(), - "SQL: processing pb service event (host: {}, service: {}, " - "description: {})", - s.host_id(), s.service_id(), s.description()); + SPDLOG_LOGGER_INFO( + _logger_sql, + "unified_sql: processing pb service event (host: {}, service: {}, " + "description: {})", + s.host_id(), s.service_id(), s.description()); if (s.host_id() && s.service_id()) { // Prepare queries. @@ -3878,11 +3881,11 @@ void stream::_process_pb_service(const std::shared_ptr& d) { }); } } else - SPDLOG_LOGGER_TRACE( - log_v2::sql(), - "SQL: service '{}' has no host ID, service ID nor hostname, probably " - "bam fake service", - s.description()); + SPDLOG_LOGGER_TRACE(_logger_sql, + "unified_sql: service '{}' has no host ID, service ID " + "nor hostname, probably " + "bam fake service", + s.description()); } uint64_t stream::_process_pb_service_in_resources(const Service& s, @@ -3930,7 +3933,7 @@ uint64_t stream::_process_pb_service_in_resources(const Service& s, 12, _cache_host_instance[s.host_id()]); if (s.severity_id() > 0) { sid = _severity_cache[{s.severity_id(), 0}]; - SPDLOG_LOGGER_DEBUG(log_v2::sql(), + SPDLOG_LOGGER_DEBUG(_logger_sql, "service ({}, {}) with severity_id {} => uid = {}", s.host_id(), s.service_id(), s.severity_id(), sid); } @@ -3959,7 +3962,7 @@ uint64_t stream::_process_pb_service_in_resources(const Service& s, _resource_cache.insert({{s.service_id(), s.host_id()}, res_id}); } catch (const std::exception& e) { SPDLOG_LOGGER_CRITICAL( - log_v2::sql(), + _logger_sql, "SQL: unable to insert new service resource ({}, {}): {}", s.host_id(), s.service_id(), e.what()); @@ -3978,12 +3981,12 @@ uint64_t stream::_process_pb_service_in_resources(const Service& s, {{s.service_id(), s.host_id()}, res.value_as_u64(0)}); found = r.first; SPDLOG_LOGGER_DEBUG( - log_v2::sql(), + _logger_sql, "Service resource ({}, {}) found in database with id {}", s.host_id(), s.service_id(), found->second); } else { SPDLOG_LOGGER_CRITICAL( - log_v2::sql(), + _logger_sql, "Could not insert service resource in database and no " "service resource in database with id ({},{}): {}", s.host_id(), s.service_id(), e.what()); @@ -3991,7 +3994,7 @@ uint64_t stream::_process_pb_service_in_resources(const Service& s, } } catch (const std::exception& e) { SPDLOG_LOGGER_CRITICAL( - log_v2::sql(), + _logger_sql, "No service resource in database with id ({}, {}): {}", s.host_id(), s.service_id(), e.what()); return 0; @@ -4023,7 +4026,7 @@ uint64_t stream::_process_pb_service_in_resources(const Service& s, 10, _cache_host_instance[s.host_id()]); if (s.severity_id() > 0) { sid = _severity_cache[{s.severity_id(), 0}]; - SPDLOG_LOGGER_DEBUG(log_v2::sql(), + SPDLOG_LOGGER_DEBUG(_logger_sql, "service ({}, {}) with severity_id {} => uid = {}", s.host_id(), s.service_id(), s.severity_id(), sid); } @@ -4064,7 +4067,7 @@ uint64_t stream::_process_pb_service_in_resources(const Service& s, if (it_tags_cache == _tags_cache.end()) { SPDLOG_LOGGER_ERROR( - log_v2::sql(), + _logger_sql, "SQL: could not find in cache the tag ({}, {}) for service " "({},{}): trying to add it.", tag.id(), tag.type(), s.host_id(), s.service_id()); @@ -4083,7 +4086,7 @@ uint64_t stream::_process_pb_service_in_resources(const Service& s, it_tags_cache = _tags_cache.insert({{tag.id(), tag.type()}, tag_id}).first; } catch (const std::exception& e) { - SPDLOG_LOGGER_ERROR(log_v2::sql(), + SPDLOG_LOGGER_ERROR(_logger_sql, "SQL: unable to insert new tag ({},{}): {}", tag.id(), tag.type(), e.what()); } @@ -4093,7 +4096,7 @@ uint64_t stream::_process_pb_service_in_resources(const Service& s, _resources_tags_insert.bind_value_as_u64(0, it_tags_cache->second); _resources_tags_insert.bind_value_as_u64(1, res_id); SPDLOG_LOGGER_DEBUG( - log_v2::sql(), + _logger_sql, "SQL: new relation between service (resource_id: {}, ({}, " "{})) and tag ({},{})", res_id, s.host_id(), s.service_id(), tag.id(), tag.type()); @@ -4103,7 +4106,7 @@ uint64_t stream::_process_pb_service_in_resources(const Service& s, _add_action(conn, actions::resources_tags); } else { SPDLOG_LOGGER_ERROR( - log_v2::sql(), + _logger_sql, "SQL: could not find the tag ({}, {}) in cache for host '{}'", tag.id(), tag.type(), s.service_id()); } @@ -4118,7 +4121,7 @@ uint64_t stream::_process_pb_service_in_resources(const Service& s, _add_action(conn, actions::resources); } else { SPDLOG_LOGGER_INFO( - log_v2::sql(), + _logger_sql, "SQL: no need to remove service ({}, {}), it is not in " "database", s.host_id(), s.service_id()); @@ -4133,7 +4136,8 @@ uint64_t stream::_process_pb_service_in_resources(const Service& s, * */ void stream::_process_pb_adaptive_service(const std::shared_ptr& d) { - SPDLOG_LOGGER_DEBUG(log_v2::sql(), "SQL: processing pb adaptive service"); + SPDLOG_LOGGER_DEBUG(_logger_sql, + "unified_sql: processing pb adaptive service"); _finish_action(-1, actions::host_parents | actions::comments | actions::downtimes | actions::host_dependencies | actions::service_dependencies); @@ -4141,11 +4145,11 @@ void stream::_process_pb_adaptive_service(const std::shared_ptr& d) { auto s{static_cast(d.get())}; auto& as = s->obj(); if (!_host_instance_known(as.host_id())) { - SPDLOG_LOGGER_WARN( - log_v2::sql(), - "SQL: pb adaptive service on service ({0}, {1}) thrown away because " - "host {0} unknown", - as.host_id(), as.service_id()); + SPDLOG_LOGGER_WARN(_logger_sql, + "unified_sql: pb adaptive service on service ({0}, {1}) " + "thrown away because " + "host {0} unknown", + as.host_id(), as.service_id()); return; } int32_t conn = _mysql.choose_connection_by_instance( @@ -4207,7 +4211,7 @@ void stream::_process_pb_adaptive_service(const std::shared_ptr& d) { query.resize(query.size() - 1); query += fmt::format(" WHERE host_id={} AND service_id={}", as.host_id(), as.service_id()); - SPDLOG_LOGGER_TRACE(log_v2::sql(), "SQL: query <<{}>>", query); + SPDLOG_LOGGER_TRACE(_logger_sql, "unified_sql: query <<{}>>", query); _mysql.run_query(query, database::mysql_error::store_service, conn); _add_action(conn, actions::services); @@ -4231,7 +4235,8 @@ void stream::_process_pb_adaptive_service(const std::shared_ptr& d) { res_query.resize(res_query.size() - 1); res_query += fmt::format(" WHERE parent_id={} AND id={}", as.host_id(), as.service_id()); - SPDLOG_LOGGER_TRACE(log_v2::sql(), "SQL: query <<{}>>", res_query); + SPDLOG_LOGGER_TRACE(_logger_sql, "unified_sql: query <<{}>>", + res_query); _mysql.run_query(res_query, database::mysql_error::update_resources, conn); _add_action(conn, actions::resources); @@ -4264,7 +4269,7 @@ void stream::_check_and_update_index_cache(const Service& ss) { // Not found if (it_index_cache == _index_cache.end()) { - SPDLOG_LOGGER_DEBUG(log_v2::sql(), + SPDLOG_LOGGER_DEBUG(_logger_sql, "sql: index not found in cache for service ({}, {})", ss.host_id(), ss.service_id()); @@ -4288,9 +4293,8 @@ void stream::_check_and_update_index_cache(const Service& ss) { conn); index_id = future.get(); SPDLOG_LOGGER_DEBUG( - log_v2::sql(), - "sql: new index {} added for service ({}, {}), special {}", index_id, - ss.host_id(), ss.service_id(), special ? "1" : "0"); + _logger_sql, "sql: new index {} added for service ({}, {}), special {}", + index_id, ss.host_id(), ss.service_id(), special ? "1" : "0"); index_info info{ .index_id = index_id, .host_name = ss.host_name(), @@ -4301,7 +4305,7 @@ void stream::_check_and_update_index_cache(const Service& ss) { .locked = false, }; SPDLOG_LOGGER_DEBUG( - log_v2::sql(), + _logger_sql, "sql: loaded index {} of ({}, {}) with rrd_len={} and interval={}", index_id, ss.host_id(), ss.service_id(), info.rrd_retention, info.interval); @@ -4345,7 +4349,7 @@ void stream::_check_and_update_index_cache(const Service& ss) { it_index_cache->second.host_name = fmt::to_string(hv); it_index_cache->second.service_description = fmt::to_string(sv); it_index_cache->second.interval = ss.check_interval(); - SPDLOG_LOGGER_DEBUG(log_v2::sql(), + SPDLOG_LOGGER_DEBUG(_logger_sql, "Updating index_data for host_id={} and " "service_id={}: host_name={}, " "service_description={}, check_interval={}", @@ -4375,16 +4379,15 @@ void stream::_process_service_status(const std::shared_ptr& d) { neb::service_status const& ss{ *static_cast(d.get())}; - log_v2::perfdata()->info("SQL: service status output: <<{}>>", ss.output); - log_v2::perfdata()->info("SQL: service status perfdata: <<{}>>", - ss.perf_data); + _logger_sto->info("unified_sql: service status output: <<{}>>", ss.output); + _logger_sto->info("unified_sql: service status perfdata: <<{}>>", + ss.perf_data); if (!_host_instance_known(ss.host_id)) { - SPDLOG_LOGGER_WARN( - log_v2::sql(), - "SQL: service status ({0}, {1}) thrown away because host {0} is not " - "known by any poller", - ss.host_id, ss.service_id); + SPDLOG_LOGGER_WARN(_logger_sql, + "unified_sql: service status ({0}, {1}) thrown away " + "because host {0} is not known by any poller", + ss.host_id, ss.service_id); return; } time_t now = time(nullptr); @@ -4394,12 +4397,12 @@ void stream::_process_service_status(const std::shared_ptr& d) { || // - normal case ss.next_check >= now - 5 * 60 || !ss.next_check) { // - initial state // Apply to DB. - SPDLOG_LOGGER_INFO( - log_v2::sql(), - "SQL: processing service status event (host: {}, service: {}, last " - "check: {}, state ({}, {}))", - ss.host_id, ss.service_id, ss.last_check, ss.current_state, - ss.state_type); + SPDLOG_LOGGER_INFO(_logger_sql, + "unified_sql: processing service status event (host: " + "{}, service: {}, last " + "check: {}, state ({}, {}))", + ss.host_id, ss.service_id, ss.last_check, + ss.current_state, ss.state_type); // Prepare queries. if (!_service_status_update.prepared()) { @@ -4420,8 +4423,9 @@ void stream::_process_service_status(const std::shared_ptr& d) { } else // Do nothing. SPDLOG_LOGGER_INFO( - log_v2::sql(), - "SQL: not processing service status event (host: {}, service: {}, " + _logger_sql, + "unified_sql: not processing service status event (host: {}, service: " + "{}, " "check type: {}, last check: {}, next check: {}, now: {}, state ({}, " "{}))", ss.host_id, ss.service_id, ss.check_type, ss.last_check, ss.next_check, @@ -4445,22 +4449,18 @@ void stream::_process_pb_service_status(const std::shared_ptr& d) { auto s{static_cast(d.get())}; auto& sscr = s->obj(); - SPDLOG_LOGGER_DEBUG(log_v2::sql(), - "SQL: pb service ({}, {}) status {} type {} check " - "result output: <<{}>>", - sscr.host_id(), sscr.service_id(), sscr.state(), - sscr.state_type(), sscr.output()); SPDLOG_LOGGER_DEBUG( - log_v2::sql(), - "SQL: service ({}, {}) status check result perfdata: <<{}>>", - sscr.host_id(), sscr.service_id(), sscr.perfdata()); + _logger_sql, + "unified_sql: processing pb service status of ({}, {}) - " + "state {} - type {} check result output: <<{}>> perfdata: <<{}>>", + sscr.host_id(), sscr.service_id(), sscr.state(), sscr.state_type(), + sscr.output(), sscr.perfdata()); if (!_host_instance_known(sscr.host_id())) { - SPDLOG_LOGGER_WARN( - log_v2::sql(), - "SQL: pb service status ({}, {}) thrown away because host {} is not " - "known by any poller", - sscr.host_id(), sscr.service_id(), sscr.host_id()); + SPDLOG_LOGGER_WARN(_logger_sql, + "unified_sql: pb service status ({}, {}) thrown away " + "because host {} is not known by any poller", + sscr.host_id(), sscr.service_id(), sscr.host_id()); return; } time_t now = time(nullptr); @@ -4468,7 +4468,7 @@ void stream::_process_pb_service_status(const std::shared_ptr& d) { sscr.next_check() >= now - 5 * 60 || // usual case sscr.next_check() == 0) { // initial state // Apply to DB. - SPDLOG_LOGGER_INFO(log_v2::sql(), + SPDLOG_LOGGER_INFO(_logger_sql, "SQL: processing pb service status check result event " "proto (host: {}, " "service: {}, " @@ -4533,7 +4533,7 @@ void stream::_process_pb_service_status(const std::shared_ptr& d) { b->set_value_as_i32(28, sscr.host_id()); b->set_value_as_i32(29, sscr.service_id()); b->next_row(); - SPDLOG_LOGGER_TRACE(log_v2::sql(), + SPDLOG_LOGGER_TRACE(_logger_sql, "{} waiting updates for service status in services", b->current_row()); } else { @@ -4598,7 +4598,13 @@ void stream::_process_pb_service_status(const std::shared_ptr& d) { _cache_host_instance[static_cast(sscr.host_id())]); size_t output_size = misc::string::adjust_size_utf8( sscr.output(), get_resources_col_size(resources_output)); + _logger_sql->debug( + "unified_sql: pb service status ({}, {}) {} in resources", + sscr.host_id(), sscr.service_id(), sscr.state()); if (_bulk_prepared_statement) { + _logger_sql->debug( + "unified_sql: BULK pb service status ({}, {}) {} in resources", + sscr.host_id(), sscr.service_id(), sscr.state()); std::lock_guard lck(*_sscr_resources_bind); if (!_sscr_resources_bind->bind(conn)) _sscr_resources_bind->init_from_stmt(conn); @@ -4624,9 +4630,12 @@ void stream::_process_pb_service_status(const std::shared_ptr& d) { b->set_value_as_u64(12, sscr.host_id()); b->next_row(); SPDLOG_LOGGER_TRACE( - log_v2::sql(), "{} waiting updates for service status in resources", + _logger_sql, "{} waiting updates for service status in resources", b->current_row()); } else { + _logger_sql->debug( + "unified_sql: NOT BULK pb service status ({}, {}) {} in resources", + sscr.host_id(), sscr.service_id(), sscr.state()); _sscr_resources_update->bind_value_as_i32(0, sscr.state()); _sscr_resources_update->bind_value_as_i32( 1, svc_ordered_status[sscr.state()]); @@ -4656,8 +4665,9 @@ void stream::_process_pb_service_status(const std::shared_ptr& d) { } else // Do nothing. SPDLOG_LOGGER_INFO( - log_v2::sql(), - "SQL: not processing service status check result event (host: {}, " + _logger_sql, + "unified_sql: not processing service status check result event (host: " + "{}, " "service: {}, " "check type: {}, last check: {}, next check: {}, now: {}, " "state ({}, " @@ -4673,7 +4683,7 @@ void stream::_process_severity(const std::shared_ptr& d) { if (!_store_in_resources) return; - SPDLOG_LOGGER_DEBUG(log_v2::sql(), "SQL: processing severity"); + SPDLOG_LOGGER_DEBUG(_logger_sql, "unified_sql: processing severity"); _finish_action(-1, actions::resources); // Prepare queries. @@ -4689,18 +4699,20 @@ void stream::_process_severity(const std::shared_ptr& d) { // Processed object. auto s{static_cast(d.get())}; auto& sv = s->obj(); - SPDLOG_LOGGER_TRACE(log_v2::sql(), - "SQL: severity event with id={}, type={}, name={}, " - "level={}, icon_id={}", - sv.id(), sv.type(), sv.name(), sv.level(), sv.icon_id()); + SPDLOG_LOGGER_TRACE( + _logger_sql, + "unified_sql: severity event with id={}, type={}, name={}, " + "level={}, icon_id={}", + sv.id(), sv.type(), sv.name(), sv.level(), sv.icon_id()); uint64_t severity_id = _severity_cache[{sv.id(), sv.type()}]; int32_t conn = special_conn::severity % _mysql.connections_count(); switch (sv.action()) { case Severity_Action_ADD: _add_action(conn, actions::severities); if (severity_id) { - SPDLOG_LOGGER_TRACE(log_v2::sql(), - "SQL: add already existing severity {}", sv.id()); + SPDLOG_LOGGER_TRACE(_logger_sql, + "unified_sql: add already existing severity {}", + sv.id()); _severity_update.bind_value_as_u64(0, sv.id()); _severity_update.bind_value_as_u32(1, sv.type()); _severity_update.bind_value_as_str(2, sv.name()); @@ -4710,7 +4722,8 @@ void stream::_process_severity(const std::shared_ptr& d) { _mysql.run_statement(_severity_update, database::mysql_error::store_severity, conn); } else { - SPDLOG_LOGGER_TRACE(log_v2::sql(), "SQL: add severity {}", sv.id()); + SPDLOG_LOGGER_TRACE(_logger_sql, "unified_sql: add severity {}", + sv.id()); _severity_insert.bind_value_as_u64(0, sv.id()); _severity_insert.bind_value_as_u32(1, sv.type()); _severity_insert.bind_value_as_str(2, sv.name()); @@ -4726,7 +4739,7 @@ void stream::_process_severity(const std::shared_ptr& d) { _severity_cache[{sv.id(), sv.type()}] = severity_id; } catch (const std::exception& e) { SPDLOG_LOGGER_ERROR( - log_v2::sql(), + _logger_sql, "unified sql: unable to insert new severity ({},{}): {}", sv.id(), sv.type(), e.what()); } @@ -4734,7 +4747,8 @@ void stream::_process_severity(const std::shared_ptr& d) { break; case Severity_Action_MODIFY: _add_action(conn, actions::severities); - SPDLOG_LOGGER_TRACE(log_v2::sql(), "SQL: modify severity {}", sv.id()); + SPDLOG_LOGGER_TRACE(_logger_sql, "unified_sql: modify severity {}", + sv.id()); _severity_update.bind_value_as_u64(0, sv.id()); _severity_update.bind_value_as_u32(1, sv.type()); _severity_update.bind_value_as_str(2, sv.name()); @@ -4747,19 +4761,20 @@ void stream::_process_severity(const std::shared_ptr& d) { _add_action(conn, actions::severities); } else SPDLOG_LOGGER_ERROR( - log_v2::sql(), + _logger_sql, "unified sql: unable to modify severity ({}, {}): not in cache", sv.id(), sv.type()); break; case Severity_Action_DELETE: - SPDLOG_LOGGER_TRACE(log_v2::sql(), - "SQL: remove severity {}: not implemented", sv.id()); + SPDLOG_LOGGER_TRACE(_logger_sql, + "unified_sql: remove severity {}: not implemented", + sv.id()); // FIXME DBO: Delete should be implemented later. This case is difficult // particularly when several pollers are running and some of them can // be stopped... break; default: - SPDLOG_LOGGER_ERROR(log_v2::sql(), "Bad action in severity object"); + SPDLOG_LOGGER_ERROR(_logger_sql, "Bad action in severity object"); break; } } @@ -4768,7 +4783,7 @@ void stream::_process_tag(const std::shared_ptr& d) { if (!_store_in_resources) return; - SPDLOG_LOGGER_INFO(log_v2::sql(), "SQL: processing tag"); + SPDLOG_LOGGER_INFO(_logger_sql, "unified_sql: processing tag"); _finish_action(-1, actions::tags); auto cache_ptr = cache::global_cache::instance_ptr(); @@ -4792,8 +4807,7 @@ void stream::_process_tag(const std::shared_ptr& d) { if (cache_ptr) { cache_ptr->add_tag(tg.id(), tg.name(), tg.type(), tg.poller_id()); } - SPDLOG_LOGGER_TRACE(log_v2::sql(), "SQL: {} tag {}", debug_action, - tg.id()); + SPDLOG_LOGGER_TRACE(_logger_sql, "SQL: {} tag {}", debug_action, tg.id()); _tag_insert_update.bind_value_as_u64(0, tg.id()); _tag_insert_update.bind_value_as_u32(1, tg.type()); _tag_insert_update.bind_value_as_str(2, tg.name()); @@ -4805,11 +4819,11 @@ void stream::_process_tag(const std::shared_ptr& d) { try { uint64_t tag_id = future.get(); _tags_cache[{tg.id(), tg.type()}] = tag_id; - SPDLOG_LOGGER_TRACE(log_v2::sql(), "new tag ({}, {}, {}) {}", tag_id, + SPDLOG_LOGGER_TRACE(_logger_sql, "new tag ({}, {}, {}) {}", tag_id, tg.id(), tg.type(), tg.name()); } catch (const std::exception& e) { - SPDLOG_LOGGER_ERROR(log_v2::sql(), + SPDLOG_LOGGER_ERROR(_logger_sql, "unified sql: unable to {} tag ({},{}): {}", debug_action, tg.id(), tg.type(), e.what()); } @@ -4823,19 +4837,19 @@ void stream::_process_tag(const std::shared_ptr& d) { auto it = _tags_cache.find({tg.id(), tg.type()}); if (it != _tags_cache.end()) { uint64_t id = it->second; - SPDLOG_LOGGER_TRACE(log_v2::sql(), "SQL: delete tag {}", id); + SPDLOG_LOGGER_TRACE(_logger_sql, "unified_sql: delete tag {}", id); _tag_delete.bind_value_as_u64(0, tg.id()); _mysql.run_statement( _tag_delete, database::mysql_error::delete_resources_tags, conn); _tags_cache.erase(it); } else - SPDLOG_LOGGER_WARN( - log_v2::sql(), - "SQL: unable to delete tag ({}, {}): it does not exist in cache", - tg.id(), tg.type()); + SPDLOG_LOGGER_WARN(_logger_sql, + "unified_sql: unable to delete tag ({}, {}): it " + "does not exist in cache", + tg.id(), tg.type()); } break; default: - SPDLOG_LOGGER_ERROR(log_v2::sql(), "Bad action in tag object"); + SPDLOG_LOGGER_ERROR(_logger_sql, "Bad action in tag object"); break; } } diff --git a/broker/unified_sql/src/stream_storage.cc b/broker/unified_sql/src/stream_storage.cc index 7a56a921cdd..46ca5ccb972 100644 --- a/broker/unified_sql/src/stream_storage.cc +++ b/broker/unified_sql/src/stream_storage.cc @@ -16,6 +16,7 @@ * For more information : contact@centreon.com */ +#include #include #include @@ -29,7 +30,6 @@ #include "bbdo/storage/remove_graph.hh" #include "bbdo/storage/status.hh" #include "com/centreon/broker/cache/global_cache.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/misc.hh" #include "com/centreon/broker/misc/perfdata.hh" #include "com/centreon/broker/misc/shared_mutex.hh" @@ -82,13 +82,13 @@ void stream::_unified_sql_process_pb_service_status( uint64_t host_id = ss.host_id(), service_id = ss.service_id(); SPDLOG_LOGGER_DEBUG( - log_v2::perfdata(), + _logger_sto, "unified sql::_unified_sql service_status processing: host_id:{}, " "service_id:{}", host_id, service_id); auto it_index_cache = _index_cache.find({host_id, service_id}); if (it_index_cache == _index_cache.end()) { - log_v2::sql()->critical( + _logger_sql->critical( "sql: could not find index for service({}, {}) - maybe the poller with " "that service should be restarted", host_id, service_id); @@ -111,7 +111,7 @@ void stream::_unified_sql_process_pb_service_status( index_locked = it_index_cache->second.locked; uint32_t interval = it_index_cache->second.interval * _interval_length; SPDLOG_LOGGER_DEBUG( - log_v2::perfdata(), + _logger_sto, "unified sql: host_id:{}, service_id:{} - index already in cache " "- index_id {}, rrd_len {}, serv_interval {}, interval {}", host_id, service_id, index_id, rrd_len, it_index_cache->second.interval, @@ -120,7 +120,7 @@ void stream::_unified_sql_process_pb_service_status( if (index_id) { /* Generate status event */ SPDLOG_LOGGER_DEBUG( - log_v2::perfdata(), + _logger_sto, "unified sql: host_id:{}, service_id:{} - generating status event " "with index_id {}, rrd_len: {}", host_id, service_id, index_id, rrd_len); @@ -151,7 +151,7 @@ void stream::_unified_sql_process_pb_service_status( /* Parse perfdata. */ _finish_action(-1, actions::metrics); std::list pds{misc::parse_perfdata( - ss.host_id(), ss.service_id(), ss.perfdata().c_str())}; + ss.host_id(), ss.service_id(), ss.perfdata().c_str(), _logger_sto)}; std::deque> to_publish; for (auto& pd : pds) { @@ -164,7 +164,7 @@ void stream::_unified_sql_process_pb_service_status( if (it_index_cache == _metric_cache.end()) { rlck.unlock(); SPDLOG_LOGGER_DEBUG( - log_v2::perfdata(), + _logger_sto, "unified sql: no metrics corresponding to index {} and " "perfdata '{}' found in cache", index_id, pd.name()); @@ -198,7 +198,7 @@ void stream::_unified_sql_process_pb_service_status( metric_id = future.get(); // Insert metric in cache. - log_v2::perfdata()->info( + _logger_sto->info( "unified sql: new metric {} for index {} and perfdata " "'{}'", metric_id, index_id, pd.name()); @@ -221,7 +221,7 @@ void stream::_unified_sql_process_pb_service_status( std::lock_guard lock(_metric_cache_m); _metric_cache[{index_id, pd.name()}] = info; } catch (std::exception const& e) { - log_v2::perfdata()->error( + _logger_sto->error( "unified sql: failed to create metric {} with type {}, " "value {}, unit_name {}, warn {}, warn_low {}, warn_mode {}, " "crit {}, crit_low {}, crit_mode {}, min {} and max {}", @@ -247,7 +247,7 @@ void stream::_unified_sql_process_pb_service_status( it_index_cache->second.type)); SPDLOG_LOGGER_DEBUG( - log_v2::perfdata(), + _logger_sto, "unified sql: metric {} concerning index {}, perfdata " "'{}' found in cache", it_index_cache->second.metric_id, index_id, pd.name()); @@ -264,7 +264,7 @@ void stream::_unified_sql_process_pb_service_status( it_index_cache->second.crit_mode != pd.critical_mode() || !check_equality(it_index_cache->second.min, pd.min()) || !check_equality(it_index_cache->second.max, pd.max())) { - log_v2::perfdata()->info( + _logger_sto->info( "unified sql: updating metric {} of index {}, perfdata " "'{}' with unit: {}, warning: {}:{}, critical: {}:{}, min: " "{}, max: {}", @@ -287,8 +287,7 @@ void stream::_unified_sql_process_pb_service_status( _metrics[it_index_cache->second.metric_id] = it_index_cache->second; } - SPDLOG_LOGGER_DEBUG(log_v2::perfdata(), - "new metric with metric_id={}", + SPDLOG_LOGGER_DEBUG(_logger_sto, "new metric with metric_id={}", it_index_cache->second.metric_id); } } @@ -321,7 +320,7 @@ void stream::_unified_sql_process_pb_service_status( else b.set_value_as_f32(3, pd.value()); SPDLOG_LOGGER_TRACE( - log_v2::sql(), + _logger_sql, "New value {} inserted on metric {} with state {}", pd.value(), metric_id, ss.state()); b.next_row(); @@ -357,7 +356,7 @@ void stream::_unified_sql_process_pb_service_status( m.set_host_id(ss.host_id()); m.set_service_id(ss.service_id()); SPDLOG_LOGGER_DEBUG( - log_v2::perfdata(), + _logger_sto, "unified sql: generating perfdata event for metric {} " "(name '{}', time {}, value {}, rrd_len {}, data_type {})", m.metric_id(), pd.name(), m.time(), m.value(), rrd_len, @@ -365,7 +364,7 @@ void stream::_unified_sql_process_pb_service_status( to_publish.emplace_back(std::move(perf)); } else { SPDLOG_LOGGER_TRACE( - log_v2::perfdata(), + _logger_sto, "unified sql: index {} is locked, so metric {} event not sent " "to rrd", index_id, metric_id); @@ -390,7 +389,7 @@ void stream::_unified_sql_process_service_status( uint64_t host_id = ss.host_id, service_id = ss.service_id; SPDLOG_LOGGER_DEBUG( - log_v2::perfdata(), + _logger_sto, "unified sql::_unified_sql_process_service_status(): host_id:{}, " "service_id:{}", host_id, service_id); @@ -414,7 +413,7 @@ void stream::_unified_sql_process_service_status( } /* Insert index in cache. */ - log_v2::perfdata()->info( + _logger_sto->info( "unified sql: add_metric_in_cache: index {}, for host_id {} and " "service_id {}", index_id, host_id, service_id); @@ -431,7 +430,7 @@ void stream::_unified_sql_process_service_status( _index_cache[{host_id, service_id}] = std::move(info); rrd_len = _rrd_len; SPDLOG_LOGGER_DEBUG( - log_v2::perfdata(), + _logger_sto, "add metric in cache: (host: {}, service: {}, index: {}, returned " "rrd_len {}", ss.host_name, ss.service_description, index_id, rrd_len); @@ -447,7 +446,7 @@ void stream::_unified_sql_process_service_status( if (it_index_cache == _index_cache.end()) { _finish_action(-1, actions::index_data); SPDLOG_LOGGER_DEBUG( - log_v2::perfdata(), + _logger_sto, "unified sql::_unified_sql_process_service_status(): host_id:{}, " "service_id:{} - index not found in cache", host_id, service_id); @@ -481,7 +480,7 @@ void stream::_unified_sql_process_service_status( rrd_len = it_index_cache->second.rrd_retention; index_locked = it_index_cache->second.locked; SPDLOG_LOGGER_DEBUG( - log_v2::perfdata(), + _logger_sto, "unified sql: host_id:{}, service_id:{} - index already in cache " "- index_id {}, rrd_len {}", host_id, service_id, index_id, rrd_len); @@ -495,7 +494,7 @@ void stream::_unified_sql_process_service_status( /* Generate status event */ SPDLOG_LOGGER_DEBUG( - log_v2::perfdata(), + _logger_sto, "unified sql: host_id:{}, service_id:{} - generating status event " "with index_id {}, rrd_len: {}", host_id, service_id, index_id, rrd_len); @@ -521,7 +520,7 @@ void stream::_unified_sql_process_service_status( /* Parse perfdata. */ _finish_action(-1, actions::metrics); std::list pds{misc::parse_perfdata( - ss.host_id, ss.service_id, ss.perf_data.c_str())}; + ss.host_id, ss.service_id, ss.perf_data.c_str(), _logger_sto)}; std::deque> to_publish; for (auto& pd : pds) { @@ -534,7 +533,7 @@ void stream::_unified_sql_process_service_status( if (it_index_cache == _metric_cache.end()) { rlck.unlock(); SPDLOG_LOGGER_DEBUG( - log_v2::perfdata(), + _logger_sto, "unified sql: no metrics corresponding to index {} and " "perfdata '{}' found in cache", index_id, pd.name()); @@ -568,7 +567,7 @@ void stream::_unified_sql_process_service_status( metric_id = future.get(); // Insert metric in cache. - log_v2::perfdata()->info( + _logger_sto->info( "unified sql: new metric {} for index {} and perfdata " "'{}'", metric_id, index_id, pd.name()); @@ -591,7 +590,7 @@ void stream::_unified_sql_process_service_status( std::lock_guard lock(_metric_cache_m); _metric_cache[{index_id, pd.name()}] = info; } catch (std::exception const& e) { - log_v2::perfdata()->error( + _logger_sto->error( "unified sql: failed to create metric {} with type {}, " "value {}, unit_name {}, warn {}, warn_low {}, warn_mode {}, " "crit {}, crit_low {}, crit_mode {}, min {} and max {}", @@ -617,7 +616,7 @@ void stream::_unified_sql_process_service_status( it_index_cache->second.type)); SPDLOG_LOGGER_DEBUG( - log_v2::perfdata(), + _logger_sto, "unified sql: metric {} concerning index {}, perfdata " "'{}' found in cache", it_index_cache->second.metric_id, index_id, pd.name()); @@ -634,7 +633,7 @@ void stream::_unified_sql_process_service_status( it_index_cache->second.crit_mode != pd.critical_mode() || !check_equality(it_index_cache->second.min, pd.min()) || !check_equality(it_index_cache->second.max, pd.max())) { - log_v2::perfdata()->info( + _logger_sto->info( "unified sql: updating metric {} of index {}, perfdata " "'{}' with unit: {}, warning: {}:{}, critical: {}:{}, min: " "{}, max: {}", @@ -657,8 +656,7 @@ void stream::_unified_sql_process_service_status( _metrics[it_index_cache->second.metric_id] = it_index_cache->second; } - SPDLOG_LOGGER_DEBUG(log_v2::perfdata(), - "new metric with metric_id={}", + SPDLOG_LOGGER_DEBUG(_logger_sto, "new metric with metric_id={}", it_index_cache->second.metric_id); } } @@ -715,7 +713,7 @@ void stream::_unified_sql_process_service_status( false, metric_id, rrd_len, pd.value(), static_cast(pd.value_type()))}; SPDLOG_LOGGER_DEBUG( - log_v2::perfdata(), + _logger_sto, "unified sql: generating perfdata event for metric {} " "(name '{}', time {}, value {}, rrd_len {}, data_type {})", perf->metric_id, perf->name, perf->time, perf->value, rrd_len, @@ -781,7 +779,7 @@ void stream::_update_metrics() { fmt::join(m, ","))); int32_t conn = _mysql.choose_best_connection(-1); _finish_action(-1, actions::metrics); - SPDLOG_LOGGER_TRACE(log_v2::sql(), "Send query: {}", query); + SPDLOG_LOGGER_TRACE(_logger_sql, "Send query: {}", query); _mysql.run_query(query, database::mysql_error::update_metrics, conn); _add_action(conn, actions::metrics); } @@ -789,8 +787,8 @@ void stream::_update_metrics() { void stream::_check_queues(boost::system::error_code ec) { if (ec) - log_v2::sql()->error( - "unified_sql: the queues check encountered an error: {}", ec.message()); + _logger_sql->error("unified_sql: the queues check encountered an error: {}", + ec.message()); else { time_t now = time(nullptr); size_t sz_metrics; @@ -809,7 +807,7 @@ void stream::_check_queues(boost::system::error_code ec) { if (_store_in_hosts_services) { if (_hscr_bind) { SPDLOG_LOGGER_TRACE( - log_v2::sql(), + _logger_sql, "Check if some statements are ready, hscr_bind connections " "count " "= {}", @@ -818,7 +816,7 @@ void stream::_check_queues(boost::system::error_code ec) { conn++) { if (_hscr_bind->ready(conn)) { SPDLOG_LOGGER_DEBUG( - log_v2::sql(), + _logger_sql, "Sending {} hosts rows of host status on connection {}", _hscr_bind->size(conn), conn); // Setting the good bind to the stmt @@ -833,7 +831,7 @@ void stream::_check_queues(boost::system::error_code ec) { } if (_sscr_bind) { SPDLOG_LOGGER_TRACE( - log_v2::sql(), + _logger_sql, "Check if some statements are ready, sscr_bind connections " "count " "= {}", @@ -841,7 +839,7 @@ void stream::_check_queues(boost::system::error_code ec) { for (uint32_t conn = 0; conn < _sscr_bind->connections_count(); conn++) { if (_sscr_bind->ready(conn)) { - SPDLOG_LOGGER_DEBUG(log_v2::sql(), + SPDLOG_LOGGER_DEBUG(_logger_sql, "Sending {} services rows of service " "status on connection {}", _sscr_bind->size(conn), conn); @@ -862,7 +860,7 @@ void stream::_check_queues(boost::system::error_code ec) { conn < _hscr_resources_bind->connections_count(); conn++) { if (_hscr_resources_bind->ready(conn)) { SPDLOG_LOGGER_DEBUG( - log_v2::sql(), + _logger_sql, "Sending {} host rows of resource status on connection {}", _hscr_resources_bind->size(conn), conn); // Setting the good bind to the stmt @@ -879,7 +877,7 @@ void stream::_check_queues(boost::system::error_code ec) { for (uint32_t conn = 0; conn < _sscr_resources_bind->connections_count(); conn++) { if (_sscr_resources_bind->ready(conn)) { - SPDLOG_LOGGER_DEBUG(log_v2::sql(), + SPDLOG_LOGGER_DEBUG(_logger_sql, "Sending {} service rows of resource " "status on connection {}", _sscr_resources_bind->size(conn), conn); @@ -901,7 +899,7 @@ void stream::_check_queues(boost::system::error_code ec) { { std::lock_guard lck(*_perfdata_query); if (_perfdata_query->ready()) { - SPDLOG_LOGGER_DEBUG(log_v2::sql(), "{} new perfdata inserted", + SPDLOG_LOGGER_DEBUG(_logger_sql, "{} new perfdata inserted", _perfdata_query->row_count()); _perfdata_query->execute( _dedicated_connections ? *_dedicated_connections : _mysql); @@ -918,7 +916,7 @@ void stream::_check_queues(boost::system::error_code ec) { bool customvar_done = false; if (_cv.ready()) { - SPDLOG_LOGGER_DEBUG(log_v2::sql(), "{} new custom variables inserted", + SPDLOG_LOGGER_DEBUG(_logger_sql, "{} new custom variables inserted", _cv.size()); std::string query = _cv.get_query(); int32_t conn = @@ -930,9 +928,8 @@ void stream::_check_queues(boost::system::error_code ec) { } if (_cvs.ready()) { - SPDLOG_LOGGER_DEBUG(log_v2::sql(), - "{} new custom variable status inserted", - _cvs.size()); + SPDLOG_LOGGER_DEBUG( + _logger_sql, "{} new custom variable status inserted", _cvs.size()); std::string query = _cvs.get_query(); int32_t conn = special_conn::custom_variable % _mysql.connections_count(); @@ -946,7 +943,7 @@ void stream::_check_queues(boost::system::error_code ec) { { std::lock_guard lck(*_downtimes); if (_downtimes->ready()) { - SPDLOG_LOGGER_DEBUG(log_v2::sql(), "{} new downtimes inserted", + SPDLOG_LOGGER_DEBUG(_logger_sql, "{} new downtimes inserted", _downtimes->row_count()); _finish_action(-1, actions::hosts | actions::instances | actions::downtimes | actions::host_parents | @@ -964,7 +961,7 @@ void stream::_check_queues(boost::system::error_code ec) { { std::lock_guard lck(*_comments); if (_comments->ready()) { - SPDLOG_LOGGER_DEBUG(log_v2::sql(), "{} new comments inserted", + SPDLOG_LOGGER_DEBUG(_logger_sql, "{} new comments inserted", _comments->row_count()); int32_t conn = special_conn::comment % _mysql.connections_count(); _comments->execute(_mysql, database::mysql_error::store_downtime, @@ -978,7 +975,7 @@ void stream::_check_queues(boost::system::error_code ec) { { std::lock_guard lck(*_logs); if (_logs->ready()) { - SPDLOG_LOGGER_DEBUG(log_v2::sql(), "{} new logs inserted", + SPDLOG_LOGGER_DEBUG(_logger_sql, "{} new logs inserted", _logs->row_count()); if (_dedicated_connections) _logs->execute(*_dedicated_connections, @@ -991,7 +988,7 @@ void stream::_check_queues(boost::system::error_code ec) { } // End. - SPDLOG_LOGGER_DEBUG(log_v2::sql(), + SPDLOG_LOGGER_DEBUG(_logger_sql, "unified_sql:_check_queues - resources: {}, " "perfdata: {}, metrics: {}, customvar: " "{}, logs: {}, downtimes: {} comments: {}", @@ -1001,16 +998,18 @@ void stream::_check_queues(boost::system::error_code ec) { } catch (const std::exception& e) { SPDLOG_LOGGER_ERROR( - log_v2::sql(), "fail to store queued data in database: {}", e.what()); + _logger_sql, "fail to store queued data in database: {}", e.what()); } if (!_stop_check_queues) { - std::lock_guard l(_timer_m); + absl::MutexLock l(&_timer_m); _queues_timer.expires_after(std::chrono::seconds(5)); - _queues_timer.async_wait( - [this](const boost::system::error_code& err) { _check_queues(err); }); + _queues_timer.async_wait([this](const boost::system::error_code& err) { + absl::ReaderMutexLock lck(&_barrier_timer_m); + _check_queues(err); + }); } else { - SPDLOG_LOGGER_INFO(log_v2::sql(), + SPDLOG_LOGGER_INFO(_logger_sql, "SQL: check_queues correctly interrupted."); _check_queues_stopped = true; _queues_cond_var.notify_all(); @@ -1023,7 +1022,7 @@ void stream::_check_queues(boost::system::error_code ec) { */ void stream::_check_deleted_index() { // Info. - SPDLOG_LOGGER_INFO(log_v2::sql(), "unified_sql: starting DB cleanup"); + SPDLOG_LOGGER_INFO(_logger_sql, "unified_sql: starting DB cleanup"); std::promise promise; std::future future = promise.get_future(); @@ -1052,15 +1051,15 @@ void stream::_check_deleted_index() { metrics_to_delete.insert(res.value_as_u64(0)); } } catch (const std::exception& e) { - log_v2::sql()->error( + _logger_sql->error( "could not query index / metrics table(s) to get index to delete: " "{} ", e.what()); } - SPDLOG_LOGGER_INFO(log_v2::sql(), "Something to remove?"); + SPDLOG_LOGGER_INFO(_logger_sql, "Something to remove?"); if (!metrics_to_delete.empty() || !index_to_delete.empty()) { - SPDLOG_LOGGER_INFO(log_v2::sql(), "YES!!!"); + SPDLOG_LOGGER_INFO(_logger_sql, "YES!!!"); auto rg = std::make_shared(); auto& obj = rg->mut_obj(); for (auto& m : metrics_to_delete) @@ -1091,13 +1090,13 @@ void stream::_check_rebuild_index() { } } catch (const std::exception& e) { - log_v2::sql()->error( + _logger_sql->error( "could not query indexes table to get indexes to delete: {}", e.what()); } - SPDLOG_LOGGER_INFO(log_v2::sql(), "Something to rebuild?"); + SPDLOG_LOGGER_INFO(_logger_sql, "Something to rebuild?"); if (!index_to_rebuild.empty()) { - SPDLOG_LOGGER_INFO(log_v2::sql(), "YES!!!"); + SPDLOG_LOGGER_INFO(_logger_sql, "YES!!!"); auto rg = std::make_shared(); auto& obj = rg->mut_obj(); for (auto& i : index_to_rebuild) diff --git a/broker/unified_sql/test/rebuild_message.cc b/broker/unified_sql/test/rebuild_message.cc index fce15b3203c..0da54265b78 100644 --- a/broker/unified_sql/test/rebuild_message.cc +++ b/broker/unified_sql/test/rebuild_message.cc @@ -26,17 +26,18 @@ #include "com/centreon/broker/config/applier/init.hh" #include "com/centreon/broker/config/applier/modules.hh" #include "com/centreon/broker/io/raw.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/lua/macro_cache.hh" #include "com/centreon/broker/misc/string.hh" #include "com/centreon/broker/misc/variant.hh" #include "com/centreon/broker/neb/instance.hh" #include "com/centreon/broker/persistent_file.hh" #include "com/centreon/broker/unified_sql/internal.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::misc; using namespace google::protobuf::util; +using com::centreon::common::log_v2::log_v2; class into_memory : public io::stream { public: @@ -70,23 +71,27 @@ class into_memory : public io::stream { }; class UnifiedSqlRebuild2Test : public ::testing::Test { + protected: + std::shared_ptr _logger; + public: void SetUp() override { + _logger = log_v2::instance().get(log_v2::SQL); io::data::broker_id = 0; try { config::applier::init(0, "broker_test", 0); } catch (std::exception const& e) { (void)e; } - std::shared_ptr pcache( - std::make_shared("/tmp/broker_test_cache")); + std::shared_ptr pcache(std::make_shared( + "/tmp/broker_test_cache", log_v2::instance().get(log_v2::SQL))); } void TearDown() override { // The cache must be destroyed before the applier deinit() call. config::applier::deinit(); ::remove("/tmp/broker_test_cache"); - ::remove(log_v2::instance()->log_name().c_str()); + ::remove(log_v2::instance().filename().c_str()); } }; @@ -94,7 +99,7 @@ class UnifiedSqlRebuild2Test : public ::testing::Test { // and a vector of metric ids. // Then the receiver can deserialize it. TEST_F(UnifiedSqlRebuild2Test, WriteRebuildMessage_START) { - config::applier::modules modules; + config::applier::modules modules(_logger); modules.load_file("./broker/unified_sql/20-unified_sql.so"); std::shared_ptr r( @@ -136,7 +141,7 @@ TEST_F(UnifiedSqlRebuild2Test, WriteRebuildMessage_START) { // and a map contains data for each metric id. // Then the receiver can deserialize it. TEST_F(UnifiedSqlRebuild2Test, WriteRebuildMessage_DATA) { - config::applier::modules modules; + config::applier::modules modules(_logger); modules.load_file("./broker/unified_sql/20-unified_sql.so"); std::shared_ptr r( diff --git a/broker/unified_sql/test/status-entry.cc b/broker/unified_sql/test/status-entry.cc index da7122ca0fb..36f53e0d18f 100644 --- a/broker/unified_sql/test/status-entry.cc +++ b/broker/unified_sql/test/status-entry.cc @@ -1,21 +1,21 @@ /** - * * Copyright 2021 Centreon (https://www.centreon.com/) - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * * - * * For more information : contact@centreon.com - * * - * */ + * Copyright 2021-2024 Centreon (https://www.centreon.com/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include #include @@ -26,16 +26,17 @@ #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/io/protocols.hh" #include "com/centreon/broker/io/raw.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/lua/macro_cache.hh" #include "com/centreon/broker/misc/string.hh" #include "com/centreon/broker/misc/variant.hh" #include "com/centreon/broker/modules/handle.hh" #include "com/centreon/broker/neb/instance.hh" #include "com/centreon/broker/unified_sql/factory.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::misc; +using com::centreon::common::log_v2::log_v2; class into_memory : public io::stream { std::vector _memory; @@ -75,15 +76,15 @@ class UnifiedSqlEntryTest : public ::testing::Test { } catch (std::exception const& e) { (void)e; } - std::shared_ptr pcache( - std::make_shared("/tmp/broker_test_cache")); + std::shared_ptr pcache(std::make_shared( + "/tmp/broker_test_cache", log_v2::instance().get(log_v2::SQL))); } void TearDown() override { // The cache must be destroyed before the applier deinit() call. config::applier::deinit(); ::remove("/tmp/broker_test_cache"); - ::remove(log_v2::instance()->log_name().c_str()); + ::remove(log_v2::instance().filename().c_str()); } }; diff --git a/broker/victoria_metrics/inc/com/centreon/broker/victoria_metrics/connector.hh b/broker/victoria_metrics/inc/com/centreon/broker/victoria_metrics/connector.hh index 8caac999793..de84762fa6e 100644 --- a/broker/victoria_metrics/inc/com/centreon/broker/victoria_metrics/connector.hh +++ b/broker/victoria_metrics/inc/com/centreon/broker/victoria_metrics/connector.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_VICTORIA_METRICS_CONNECTOR_HH #define CCB_VICTORIA_METRICS_CONNECTOR_HH @@ -45,6 +45,6 @@ class connector : public io::endpoint { }; } // namespace victoria_metrics -} +} // namespace com::centreon::broker #endif // !CCB_VICTORIA_METRICS_CONNECTOR_HH diff --git a/broker/victoria_metrics/inc/com/centreon/broker/victoria_metrics/factory.hh b/broker/victoria_metrics/inc/com/centreon/broker/victoria_metrics/factory.hh index 1750cd56618..5e5a6a082d9 100644 --- a/broker/victoria_metrics/inc/com/centreon/broker/victoria_metrics/factory.hh +++ b/broker/victoria_metrics/inc/com/centreon/broker/victoria_metrics/factory.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_VICTORIA_METRICS_FACTORY_HH #define CCB_VICTORIA_METRICS_FACTORY_HH @@ -46,6 +46,6 @@ class factory : public http_tsdb::factory { }; } // namespace victoria_metrics -} +} // namespace com::centreon::broker #endif // !CCB_VICTORIA_METRICS_FACTORY_HH diff --git a/broker/victoria_metrics/inc/com/centreon/broker/victoria_metrics/request.hh b/broker/victoria_metrics/inc/com/centreon/broker/victoria_metrics/request.hh index b0633b96fae..44f234f8453 100644 --- a/broker/victoria_metrics/inc/com/centreon/broker/victoria_metrics/request.hh +++ b/broker/victoria_metrics/inc/com/centreon/broker/victoria_metrics/request.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCB_VICTORIA_METRICS_REQUEST_HH #define CCB_VICTORIA_METRICS_REQUEST_HH @@ -27,6 +27,7 @@ namespace com::centreon::broker { namespace victoria_metrics { class request : public http_tsdb::request { + std::shared_ptr _logger; const http_tsdb::line_protocol_query& _metric_formatter; const http_tsdb::line_protocol_query& _status_formatter; @@ -38,6 +39,7 @@ class request : public http_tsdb::request { request(boost::beast::http::verb method, const std::string& server_name, boost::beast::string_view target, + const std::shared_ptr& logger, unsigned size_to_reserve, const http_tsdb::line_protocol_query& metric_formatter, const http_tsdb::line_protocol_query& status_formatter, @@ -50,6 +52,6 @@ class request : public http_tsdb::request { } // namespace victoria_metrics -} +} // namespace com::centreon::broker #endif // !CCB_VICTORIA_METRICS_REQUEST_HH diff --git a/broker/victoria_metrics/inc/com/centreon/broker/victoria_metrics/stream.hh b/broker/victoria_metrics/inc/com/centreon/broker/victoria_metrics/stream.hh index e6c1b338310..c04097ba19d 100644 --- a/broker/victoria_metrics/inc/com/centreon/broker/victoria_metrics/stream.hh +++ b/broker/victoria_metrics/inc/com/centreon/broker/victoria_metrics/stream.hh @@ -1,11 +1,11 @@ /** - * Copyright 2024 Centreon (https://www.centreon.com/) + * Copyright 2022-2024 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -14,7 +14,6 @@ * limitations under the License. * * For more information : contact@centreon.com - * */ #ifndef CCB_VICTORIA_METRICS_STREAM_HH diff --git a/broker/victoria_metrics/precomp_inc/precomp.hh b/broker/victoria_metrics/precomp_inc/precomp.hh index 4b9b4297ffd..d95703a2c93 100644 --- a/broker/victoria_metrics/precomp_inc/precomp.hh +++ b/broker/victoria_metrics/precomp_inc/precomp.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CC_VICTORIA_METRICS_PRECOMP_HH #define CC_VICTORIA_METRICS_PRECOMP_HH @@ -52,5 +52,4 @@ using duration = system_clock::duration; namespace asio = boost::asio; - #endif // CC_VICTORIA_METRICS_PRECOMP_HH diff --git a/broker/victoria_metrics/src/connector.cc b/broker/victoria_metrics/src/connector.cc index a9c06069dab..796ff02f740 100644 --- a/broker/victoria_metrics/src/connector.cc +++ b/broker/victoria_metrics/src/connector.cc @@ -1,5 +1,5 @@ /** - * Copyright 2024 Centreon (https://www.centreon.com/) + * Copyright 2022-2024 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,21 +18,26 @@ */ #include "com/centreon/broker/victoria_metrics/connector.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/victoria_metrics/stream.hh" #include "com/centreon/common/http/https_connection.hh" #include "com/centreon/common/pool.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::victoria_metrics; +using com::centreon::common::log_v2::log_v2; + static constexpr multiplexing::muxer_filter _victoria_stream_filter = { storage::metric::static_type(), storage::status::static_type(), storage::pb_metric::static_type(), storage::pb_status::static_type()}; +static constexpr multiplexing::muxer_filter _victoria_forbidden_filter = + multiplexing::muxer_filter(_victoria_stream_filter).reverse(); + connector::connector(const std::shared_ptr& conf, const std::string& account_id) - : io::endpoint(false, _victoria_stream_filter), + : io::endpoint(false, _victoria_stream_filter, _victoria_forbidden_filter), _conf(conf), _account_id(account_id) {} @@ -42,15 +47,17 @@ std::shared_ptr connector::open() { _account_id, [conf = _conf]() { return http::http_connection::load( com::centreon::common::pool::io_context_ptr(), - log_v2::victoria_metrics(), conf); + log_v2::instance().get(log_v2::VICTORIA_METRICS), + conf); }); } else { return stream::load(com::centreon::common::pool::io_context_ptr(), _conf, _account_id, [conf = _conf]() { return http::https_connection::load( com::centreon::common::pool::io_context_ptr(), - log_v2::victoria_metrics(), conf, + log_v2::instance().get(log_v2::VICTORIA_METRICS), + conf, http::https_connection::load_client_certificate); }); } -} \ No newline at end of file +} diff --git a/broker/victoria_metrics/src/factory.cc b/broker/victoria_metrics/src/factory.cc index 79f3aaa3d37..42484381aab 100644 --- a/broker/victoria_metrics/src/factory.cc +++ b/broker/victoria_metrics/src/factory.cc @@ -1,5 +1,5 @@ /** - * Copyright 2022 Centreon + * Copyright 2022-2024 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -82,4 +82,4 @@ io::endpoint* factory::new_endpoint( } return new connector(conf, account_id); -} \ No newline at end of file +} diff --git a/broker/victoria_metrics/src/main.cc b/broker/victoria_metrics/src/main.cc index aad5d1ebb3b..0b051276fcd 100644 --- a/broker/victoria_metrics/src/main.cc +++ b/broker/victoria_metrics/src/main.cc @@ -1,5 +1,5 @@ /** - * Copyright 2022 Centreon + * Copyright 2022-2024 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,10 +28,11 @@ #include "com/centreon/broker/http_tsdb/internal.hh" #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/io/protocols.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/victoria_metrics/factory.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; +using log_v2 = com::centreon::common::log_v2::log_v2; // Load count. static uint32_t instances(0); @@ -71,10 +72,11 @@ bool broker_module_deinit() { void broker_module_init(void const* arg) { (void)arg; + auto logger = log_v2::instance().get(log_v2::VICTORIA_METRICS); // Increment instance number. if (!instances++) { // RRD module. - SPDLOG_LOGGER_INFO(log_v2::victoria_metrics(), + SPDLOG_LOGGER_INFO(logger, "victoria_metrics: module for Centreon Broker {}", CENTREON_BROKER_VERSION); diff --git a/broker/victoria_metrics/src/request.cc b/broker/victoria_metrics/src/request.cc index 37a0fa38276..0994528a0b3 100644 --- a/broker/victoria_metrics/src/request.cc +++ b/broker/victoria_metrics/src/request.cc @@ -1,26 +1,25 @@ /** -* Copyright 2022 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/victoria_metrics/request.hh" #include "bbdo/storage/metric.hh" #include "bbdo/storage/status.hh" #include "com/centreon/broker/cache/global_cache.hh" -#include "com/centreon/broker/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::victoria_metrics; @@ -55,11 +54,13 @@ static std::string string_filter(const string_class& to_filter) { request::request(boost::beast::http::verb method, const std::string& server_name, boost::beast::string_view target, + const std::shared_ptr& logger, unsigned size_to_reserve, const http_tsdb::line_protocol_query& metric_formatter, const http_tsdb::line_protocol_query& status_formatter, const std::string& authorization) : http_tsdb::request(method, server_name, target), + _logger{logger}, _metric_formatter(metric_formatter), _status_formatter(status_formatter) { body().reserve(size_to_reserve); @@ -96,8 +97,7 @@ void request::add_status(const storage::pb_status& status) { if (status_obj.state() < 0 || status_obj.state() > 2) { if (status_obj.state() != 3) { // we don't write unknown but it's not an error - SPDLOG_LOGGER_ERROR(log_v2::victoria_metrics(), "unknown state: {}", - status_obj.state()); + SPDLOG_LOGGER_ERROR(_logger, "unknown state: {}", status_obj.state()); } ++_nb_status; return; diff --git a/broker/victoria_metrics/src/stream.cc b/broker/victoria_metrics/src/stream.cc index afe84157706..7ed5b55096f 100644 --- a/broker/victoria_metrics/src/stream.cc +++ b/broker/victoria_metrics/src/stream.cc @@ -1,5 +1,5 @@ /** - * Copyright 2024 Centreon (https://www.centreon.com/) + * Copyright 2022-2024 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,12 +20,13 @@ #include "com/centreon/broker/victoria_metrics/stream.hh" #include "bbdo/storage/metric.hh" #include "bbdo/storage/status.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/string.hh" #include "com/centreon/broker/victoria_metrics/request.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::victoria_metrics; +using log_v2 = com::centreon::common::log_v2::log_v2; const std::string stream::allowed_macros = "$INSTANCE$,$INSTANCEID$,$HOST$,$SERVICE$,$HOSTGROUP$,$SERVICE_GROUP$," @@ -40,17 +41,17 @@ stream::stream(const std::shared_ptr& io_context, http::connection_creator conn_creator) : http_tsdb::stream("victoria_metrics", io_context, - log_v2::victoria_metrics(), + log_v2::instance().get(log_v2::VICTORIA_METRICS), conf, conn_creator), _metric_formatter(allowed_macros, conf->get_metric_columns(), http_tsdb::line_protocol_query::data_type::metric, - log_v2::victoria_metrics()), + _logger), _status_formatter(allowed_macros, conf->get_status_columns(), http_tsdb::line_protocol_query::data_type::status, - log_v2::victoria_metrics()), + _logger), _account_id(account_id) { // in order to avoid reallocation of request body _body_size_to_reserve = conf->get_max_queries_per_transaction() * @@ -75,8 +76,8 @@ std::shared_ptr stream::load( http_tsdb::request::pointer stream::create_request() const { auto ret = std::make_shared( boost::beast::http::verb::post, _conf->get_server_name(), - _conf->get_http_target(), _body_size_to_reserve, _metric_formatter, - _status_formatter, _authorization); + _conf->get_http_target(), _logger, _body_size_to_reserve, + _metric_formatter, _status_formatter, _authorization); ret->set(boost::beast::http::field::content_type, "text/plain"); ret->set(boost::beast::http::field::accept, "application/json"); diff --git a/broker/victoria_metrics/test/request_test.cc b/broker/victoria_metrics/test/request_test.cc index c8c4f38df7b..fea88349e2b 100644 --- a/broker/victoria_metrics/test/request_test.cc +++ b/broker/victoria_metrics/test/request_test.cc @@ -32,22 +32,25 @@ using duration = system_clock::duration; #include "com/centreon/broker/cache/global_cache.hh" #include "com/centreon/broker/file/disk_accessor.hh" #include "com/centreon/broker/io/protocols.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/victoria_metrics/factory.hh" #include "com/centreon/broker/victoria_metrics/request.hh" #include "com/centreon/broker/victoria_metrics/stream.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::http_tsdb; ; using namespace nlohmann; +using log_v2 = com::centreon::common::log_v2::log_v2; class victoria_request_test : public ::testing::Test { + protected: + std::shared_ptr _logger; + public: static void SetUpTestSuite() { - log_v2::victoria_metrics()->set_level(spdlog::level::debug); file::disk_accessor::load(1000); io::protocols::load(); io::events::load(); @@ -62,6 +65,10 @@ class victoria_request_test : public ::testing::Test { e.register_event(make_type(io::storage, storage::de_pb_status), "pb_status", &storage::pb_status::operations); } + void SetUp() override { + _logger = log_v2::instance().get(log_v2::VICTORIA_METRICS); + _logger->set_level(spdlog::level::debug); + } }; TEST_F(victoria_request_test, request_body_test) { @@ -93,7 +100,7 @@ TEST_F(victoria_request_test, request_body_test) { http_tsdb::line_protocol_query dummy; victoria_metrics::request req(boost::beast::http::verb::post, "localhost", - "/", 0, dummy, dummy, "toto"); + "/", _logger, 0, dummy, dummy, "toto"); Metric metric; metric.set_metric_id(123); @@ -163,18 +170,17 @@ TEST_F(victoria_request_test, request_body_test_default_victoria_extra_column) { victoria_metrics::stream::allowed_macros, http_tsdb::factory::get_columns( victoria_metrics::factory::default_extra_metric_column), - http_tsdb::line_protocol_query::data_type::status, - log_v2::victoria_metrics()); + http_tsdb::line_protocol_query::data_type::status, _logger); http_tsdb::line_protocol_query status_columns( victoria_metrics::stream::allowed_macros, http_tsdb::factory::get_columns( victoria_metrics::factory::default_extra_status_column), - http_tsdb::line_protocol_query::data_type::status, - log_v2::victoria_metrics()); + http_tsdb::line_protocol_query::data_type::status, _logger); victoria_metrics::request req(boost::beast::http::verb::post, "localhost", - "/", 0, metric_columns, status_columns, "toto"); + "/", _logger, 0, metric_columns, status_columns, + "toto"); Metric metric; metric.set_metric_id(123); @@ -264,17 +270,16 @@ TEST_F(victoria_request_test, request_body_test_victoria_extra_column) { http_tsdb::line_protocol_query metric_columns( victoria_metrics::stream::allowed_macros, http_tsdb::factory::get_columns(column), - http_tsdb::line_protocol_query::data_type::status, - log_v2::victoria_metrics()); + http_tsdb::line_protocol_query::data_type::status, _logger); http_tsdb::line_protocol_query status_columns( victoria_metrics::stream::allowed_macros, http_tsdb::factory::get_columns(column), - http_tsdb::line_protocol_query::data_type::status, - log_v2::victoria_metrics()); + http_tsdb::line_protocol_query::data_type::status, _logger); victoria_metrics::request req(boost::beast::http::verb::post, "localhost", - "/", 0, metric_columns, status_columns, "toto"); + "/", _logger, 0, metric_columns, status_columns, + "toto"); Metric metric; metric.set_metric_id(123); diff --git a/broker/victoria_metrics/test/stream_test.cc b/broker/victoria_metrics/test/stream_test.cc index 76c431167ba..d04b13cfb0f 100644 --- a/broker/victoria_metrics/test/stream_test.cc +++ b/broker/victoria_metrics/test/stream_test.cc @@ -31,9 +31,9 @@ using duration = system_clock::duration; #include "com/centreon/broker/config/applier/state.hh" #include "com/centreon/broker/file/disk_accessor.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/victoria_metrics/stream.hh" #include "com/centreon/common/pool.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::common; @@ -61,7 +61,8 @@ TEST_F(victoria_stream_test, Authorization) { stream::load(g_io_context, cfg, "my_account", [cfg]() { return http::http_connection::load( com::centreon::common::pool::io_context_ptr(), - log_v2::victoria_metrics(), cfg); + log_v2::log_v2::instance().get(log_v2::log_v2::VICTORIA_METRICS), + cfg); }); ASSERT_EQ(s->get_authorization(), "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="); } diff --git a/cmake-vcpkg.sh b/cmake-vcpkg.sh index 7744dba9b27..f160be00773 100755 --- a/cmake-vcpkg.sh +++ b/cmake-vcpkg.sh @@ -54,7 +54,7 @@ do ;; -r|--release) echo "Release build" - BUILD_TYPE="Release" + BUILD_TYPE="RelWithDebInfo" shift ;; -clang) diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt index 5c3de9473bc..23ba03d80b4 100644 --- a/common/CMakeLists.txt +++ b/common/CMakeLists.txt @@ -1,5 +1,5 @@ # -# Copyright 2023 Centreon +# Copyright 2023-2024 Centreon # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of @@ -19,11 +19,13 @@ # Global options. project("Centreon common" C CXX) +add_subdirectory(log_v2) + # Set directories. set(INCLUDE_DIR "${PROJECT_SOURCE_DIR}/inc/com/centreon/common") set (HTTP_INCLUDE_DIR "${PROJECT_SOURCE_DIR}/http/inc/com/centreon/common/http") set(SRC_DIR "${PROJECT_SOURCE_DIR}/src") -set(TEST_DIR "${PROJECT_SOURCE_DIR}/test") +set(TEST_DIR "${PROJECT_SOURCE_DIR}/tests") add_custom_command( DEPENDS ${SRC_DIR}/process_stat.proto @@ -31,9 +33,8 @@ add_custom_command( OUTPUT ${SRC_DIR}/process_stat.grpc.pb.cc ${SRC_DIR}/process_stat.grpc.pb.h COMMAND ${Protobuf_PROTOC_EXECUTABLE} ARGS - --plugin=protoc-gen-grpc=${GRPC_CPP_PLUGIN} - --proto_path=${SRC_DIR} --grpc_out="${SRC_DIR}" - ${SRC_DIR}/process_stat.proto + --plugin=protoc-gen-grpc=${GRPC_CPP_PLUGIN} --proto_path=${SRC_DIR} + --grpc_out="${SRC_DIR}" ${SRC_DIR}/process_stat.proto DEPENDS ${SRC_DIR}/process_stat.proto COMMENT "Generating interface files of the proto file (protobuf)" OUTPUT ${SRC_DIR}/process_stat.pb.cc ${SRC_DIR}/process_stat.pb.h @@ -67,5 +68,5 @@ target_precompile_headers(centreon_common PRIVATE precomp_inc/precomp.hh) add_subdirectory(http) if(WITH_TESTING) - add_subdirectory(test) + add_subdirectory(tests) endif() diff --git a/common/http/test/http_client_test.cc b/common/http/test/http_client_test.cc index 280d03f3571..b668262ca67 100644 --- a/common/http/test/http_client_test.cc +++ b/common/http/test/http_client_test.cc @@ -25,12 +25,12 @@ using system_clock = std::chrono::system_clock; using time_point = system_clock::time_point; using duration = system_clock::duration; +using com::centreon::common::log_v2::log_v2; #include "http_client.hh" using namespace com::centreon::common; using namespace com::centreon::common::http; - extern std::shared_ptr g_io_context; const asio::ip::tcp::endpoint test_endpoint(asio::ip::make_address("127.0.0.1"), @@ -40,6 +40,9 @@ static std::shared_ptr logger = spdlog::stdout_color_mt("http_client_test"); class http_client_test : public ::testing::Test { + protected: + static std::shared_ptr _logger; + public: static void SetUpTestSuite() { srand(time(nullptr)); @@ -47,6 +50,8 @@ class http_client_test : public ::testing::Test { }; }; +std::shared_ptr http_client_test::_logger; + class connection_ok : public connection_base { unsigned _connect_counter; unsigned _request_counter; @@ -75,7 +80,8 @@ class connection_ok : public connection_base { [me = shared_from_this(), cb = std::move(callback)]() { cb({}, {}); }); } - void send(request_ptr request, send_callback_type&& callback) override { + void send(request_ptr request [[maybe_unused]], + send_callback_type&& callback) override { if (_state != e_idle) { _io_context->post([cb = std::move(callback)]() { cb(std::make_error_code(std::errc::invalid_argument), "bad state", {}); @@ -238,7 +244,8 @@ class connection_bagot : public connection_base { } } - void send(request_ptr request, send_callback_type&& callback) override { + void send(request_ptr request [[maybe_unused]], + send_callback_type&& callback) override { if (_state != e_idle) { _io_context->post([cb = std::move(callback)]() { cb(std::make_error_code(std::errc::invalid_argument), "bad state", {}); diff --git a/common/http/test/http_connection_test.cc b/common/http/test/http_connection_test.cc index fdcb820e9bd..2407f3871f5 100644 --- a/common/http/test/http_connection_test.cc +++ b/common/http/test/http_connection_test.cc @@ -24,6 +24,7 @@ using system_clock = std::chrono::system_clock; using time_point = system_clock::time_point; using duration = system_clock::duration; +using com::centreon::common::log_v2::log_v2; #include "http_connection.hh" #include "http_server.hh" @@ -216,6 +217,7 @@ class dummy_connection : public connection_base { }; TEST(http_keepalive_test, ConnectionClose) { + auto logger = log_v2::instance().get(log_v2::TCP); dummy_connection conn( g_io_context, logger, std::make_shared(test_endpoint, "localhost")); @@ -227,6 +229,7 @@ TEST(http_keepalive_test, ConnectionClose) { } TEST(http_keepalive_test, KeepAliveWithoutTimeout) { + auto logger = log_v2::instance().get(log_v2::TCP); auto conf = std::make_shared(test_endpoint, "localhost"); dummy_connection conn(g_io_context, logger, conf); response_ptr resp(std::make_shared()); @@ -243,6 +246,7 @@ TEST(http_keepalive_test, KeepAliveWithoutTimeout) { } TEST(http_keepalive_test, KeepAliveWithTimeout) { + auto logger = log_v2::instance().get(log_v2::TCP); auto conf = std::make_shared(test_endpoint, "localhost"); dummy_connection conn(g_io_context, logger, conf); response_ptr resp(std::make_shared()); diff --git a/common/log_v2/CMakeLists.txt b/common/log_v2/CMakeLists.txt new file mode 100644 index 00000000000..9ac562a369f --- /dev/null +++ b/common/log_v2/CMakeLists.txt @@ -0,0 +1,31 @@ +# +# Copyright 2023 Centreon +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may not +# use this file except in compliance with the License. You may obtain a copy of +# the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations under +# the License. +# +# For more information : contact@centreon.com +# + +include_directories(${CMAKE_CURRENT_SOURCE_DIR}) +add_definitions(-DSPDLOG_ACTIVE_LEVEL=SPDLOG_LEVEL_TRACE) +add_definitions(${spdlog_DEFINITIONS}) + +add_library( + log_v2 STATIC + # Sources. + log_v2.cc log_v2.hh config.hh) + +#set_target_properties(log_v2 PROPERTIES CXX_VISIBILITY_PRESET hidden) + +target_link_libraries(log_v2 spdlog::spdlog stdc++fs gRPC::gpr + absl::raw_hash_set) diff --git a/common/log_v2/config.hh b/common/log_v2/config.hh new file mode 100644 index 00000000000..0610580e799 --- /dev/null +++ b/common/log_v2/config.hh @@ -0,0 +1,136 @@ +/** + * Copyright 2023 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ +#ifndef CCC_LOG_V2_CONFIG_HH +#define CCC_LOG_V2_CONFIG_HH +#include +#include +#include +#include "spdlog/spdlog.h" + +#include +#include + +namespace com::centreon::common::log_v2 { +class config { + public: + enum class logger_type { + LOGGER_STDOUT = 0, + LOGGER_FILE = 1, + LOGGER_SYSLOG = 2, + }; + + private: + const std::string _name; + /* This is a little hack to avoid to replace the log file set by centengine */ + bool _only_atomic_changes = false; + logger_type _log_type; + std::string _dirname; + std::string _filename; + std::size_t _max_size; + uint32_t _flush_interval; + bool _log_pid; + bool _log_source; + /* logger name => level */ + absl::flat_hash_map _loggers; + + /* custom sinks needed by some loggers */ + std::vector _custom_sinks; + /* which loggers need custom sinks */ + absl::flat_hash_set _loggers_with_custom_sinks; + + public: + config(const std::string& name, + logger_type log_type, + uint32_t flush_interval, + bool log_pid, + bool log_source) + : _log_type{log_type}, + _flush_interval{flush_interval}, + _log_pid{log_pid}, + _log_source{log_source} { + std::filesystem::path path{name}; + _dirname = path.parent_path(); + _filename = path.filename(); + } + + config(const config& other) + : _log_type{other._log_type}, + _dirname{other._dirname}, + _filename{other._filename}, + _max_size{other._max_size}, + _flush_interval{other._flush_interval}, + _log_pid{other._log_pid}, + _log_source{other._log_source} {} + std::string log_path() const { + return _dirname.empty() ? _filename + : fmt::format("{}/{}", _dirname, _filename); + } + + logger_type log_type() const { return _log_type; } + + /** + * @brief Set the file name to write into. The name must be the full path of + * the file, including the parent directories. + * + * @param full_path The file to log into. + */ + void set_log_path(const std::string& full_path) { + std::filesystem::path p{full_path}; + _dirname = p.parent_path(); + _filename = p.filename(); + } + + size_t max_size() const { return _max_size; } + uint32_t flush_interval() const { return _flush_interval; } + void set_flush_interval(uint32_t flush_interval) { + _flush_interval = flush_interval; + } + bool log_pid() const { return _log_pid; } + void set_log_pid(bool log_pid) { _log_pid = log_pid; } + bool log_source() const { return _log_source; } + void set_log_source(bool log_source) { _log_source = log_source; } + const std::string& dirname() const { return _dirname; } + void set_dirname(const std::string& dirname) { _dirname = dirname; } + void set_level(const std::string& name, const std::string& level) { + _loggers[name] = level; + } + absl::flat_hash_map& loggers() { return _loggers; } + const absl::flat_hash_map& loggers() const { + return _loggers; + } + const std::string& filename() const { return _filename; } + void set_filename(const std::string& filename) { _filename = filename; } + void set_max_size(const std::size_t max_size) { _max_size = max_size; } + void add_custom_sink(const spdlog::sink_ptr& sink) { + _custom_sinks.push_back(sink); + } + const std::vector& custom_sinks() const { + return _custom_sinks; + } + void apply_custom_sinks(std::initializer_list ilist) { + _loggers_with_custom_sinks = ilist; + } + const absl::flat_hash_set& loggers_with_custom_sinks() const { + return _loggers_with_custom_sinks; + } + // const std::string& name() const { return _name; } + void allow_only_atomic_changes(bool slave) { _only_atomic_changes = slave; } + bool only_atomic_changes() const { return _only_atomic_changes; } +}; +} // namespace com::centreon::common::log_v2 +#endif diff --git a/common/log_v2/log_v2.cc b/common/log_v2/log_v2.cc new file mode 100644 index 00000000000..a243adb9d55 --- /dev/null +++ b/common/log_v2/log_v2.cc @@ -0,0 +1,428 @@ +/** + * Copyright 2022-2023 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#include "common/log_v2/log_v2.hh" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +using namespace com::centreon::common::log_v2; +using namespace spdlog; + +log_v2* log_v2::_instance = nullptr; + +const std::array log_v2::_logger_name = { + "core", + "config", + "bam", + "bbdo", + "lua", + "influxdb", + "graphite", + "rrd", + "stats", + "perfdata", + "processing", + "sql", + "neb", + "tcp", + "tls", + "grpc", + "victoria_metrics", + "process", + "functions", + "events", + "checks", + "notifications", + "eventbroker", + "external_command", + "commands", + "downtimes", + "comments", + "macros", + "runtime"}; + +/** + * @brief this function is passed to grpc in order to log grpc layer's events to + * logv2 + * + * @param args grpc logging params + */ +static void grpc_logger(gpr_log_func_args* args) { + auto logger = log_v2::instance().get(log_v2::GRPC); + if (logger) { + spdlog::level::level_enum grpc_level = logger->level(); + const char* start; + if (grpc_level == spdlog::level::off) + return; + else if (grpc_level > spdlog::level::debug) { + start = strstr(args->message, "}: "); + if (!start) + return; + start += 3; + } else + start = args->message; + switch (args->severity) { + case GPR_LOG_SEVERITY_DEBUG: + if (grpc_level == spdlog::level::trace || + grpc_level == spdlog::level::debug) { + SPDLOG_LOGGER_DEBUG(logger, "{} ({}:{})", start, args->file, + args->line); + } + break; + case GPR_LOG_SEVERITY_INFO: + if (grpc_level == spdlog::level::trace || + grpc_level == spdlog::level::debug || + grpc_level == spdlog::level::info) { + if (start) + SPDLOG_LOGGER_INFO(logger, "{}", start); + } + break; + case GPR_LOG_SEVERITY_ERROR: + SPDLOG_LOGGER_ERROR(logger, "{}", start); + break; + } + } +} + +/** + * @brief Initialization of the log_v2 instance. Initialized loggers are given + * in ilist. + * + * @param name The name of the logger. + * @param ilist The list of loggers to initialize. + */ +void log_v2::load(std::string name) { + if (!_instance) + _instance = new log_v2(std::move(name)); +} + +/** + * @brief Destruction of the log_v2 instance. No more call to log_v2 is + * possible. + */ +void log_v2::unload() { + if (_instance) { + delete _instance; + _instance = nullptr; + spdlog::drop_all(); + spdlog::shutdown(); + } +} + +/** + * @brief Constructor of the log_v2 class. This constructor is not public since + * it is called through the load() function. + * + * @param name Name of the logger. + * @param ilist List of loggers to initialize. + */ +log_v2::log_v2(std::string name) : _log_name{std::move(name)} { + create_loggers(config::logger_type::LOGGER_STDOUT); +} + +/** + * @brief Static method to get the current log_v2 running instance. + * + * @return A reference to the log_v2 instance. + */ +log_v2& log_v2::instance() { + assert(_instance); + return *_instance; +} + +/** + * @brief Accessor to the flush interval current value. + * + * @return An std::chrono::seconds value. + */ +std::chrono::seconds log_v2::flush_interval() { + return _flush_interval; +} + +void log_v2::set_flush_interval(uint32_t second_flush_interval) { + _flush_interval = std::chrono::seconds(second_flush_interval); + if (second_flush_interval == 0) { + for (auto& l : _loggers) { + if (l && l->level() != level::off) + l->flush_on(l->level()); + } + } else { + for (auto& l : _loggers) { + if (l && l->level() != level::off) + l->flush_on(level::warn); + } + } + spdlog::flush_every(_flush_interval); +} + +/** + * @brief Accessor to the logger id by its name. If the name does not match any + * logger, LOGGER_SIZE is returned. This method is used essentially during the + * configuration because the final user is not aware of internal enums. + * @param name The logger name. + * + * @return A log_v2::logger_id corresponding to the wanted logger or LOGGER_SIZE + * if not found. + */ +log_v2::logger_id log_v2::get_id(const std::string& name) const noexcept { + uint32_t retval; + for (retval = 0; retval < _logger_name.size(); retval++) { + if (_logger_name[retval] == name) + return static_cast(retval); + } + return LOGGER_SIZE; +} + +/** + * @brief Create all the loggers in log_v2. By default they are writing into + * stdout. Broker. + * + * @param typ The log type, to log in syslog, a file, in stdout. + * @param length The max length of the log receiver (only used for files). + */ +void log_v2::create_loggers(config::logger_type typ, size_t length) { + _not_threadsafe_configuration = true; + sink_ptr my_sink; + + for (int32_t id = 0; id < LOGGER_SIZE; id++) + assert(!_loggers[id]); + + switch (typ) { + case config::logger_type::LOGGER_FILE: { + if (length) + my_sink = std::make_shared( + _file_path, _current_max_size, 99); + else + my_sink = std::make_shared(_file_path); + } break; + case config::logger_type::LOGGER_SYSLOG: + my_sink = std::make_shared(_log_name, 0, 0, true); + break; + case config::logger_type::LOGGER_STDOUT: + my_sink = std::make_shared(); + break; + } + + for (int32_t id = 0; id < LOGGER_SIZE; id++) { + std::shared_ptr logger; + logger = std::make_shared(_logger_name[id], my_sink); + if (_log_pid) { + if (_log_source) + logger->set_pattern( + "[%Y-%m-%dT%H:%M:%S.%e%z] [%n] [%l] [%s:%#] [%P] %v"); + else + logger->set_pattern("[%Y-%m-%dT%H:%M:%S.%e%z] [%n] [%l] [%P] %v"); + } else { + if (_log_source) + logger->set_pattern("[%Y-%m-%dT%H:%M:%S.%e%z] [%n] [%l] [%s:%#] %v"); + else + logger->set_pattern("[%Y-%m-%dT%H:%M:%S.%e%z] [%n] [%l] %v"); + } + logger->set_level(level::level_enum::info); + spdlog::register_logger(logger); + _loggers[id] = std::move(logger); + + /* Hook for gRPC, not beautiful, but no idea how to do better. */ + if (id == GRPC) + gpr_set_log_function(grpc_logger); + } + _not_threadsafe_configuration = false; +} + +/** + * @brief Accessor to the logger of given ID. + * + * @param idx The ID of the logger to get. + * + * @return A shared pointer to the logger. + */ +std::shared_ptr log_v2::get(log_v2::logger_id idx) { + return _loggers[idx]; +} + +/** + * @brief Create the loggers configuration from the given log_conf object. + * New loggers are created with the good configuration. + * This function should also be called when no logs are emitted. + * + * Two changes for a logger are possible: + * * its level: change the level of a logger is easy since it is atomic. + * * its sinks: In that case, things are more complicated. We have to build + * a new logger and replace the existing one. + * + * @param log_conf The configuration to apply + */ +void log_v2::apply(const config& log_conf) { + spdlog::sink_ptr my_sink; + + /* This part is about sinks so it is reserved for masters */ + if (!log_conf.only_atomic_changes()) { + _not_threadsafe_configuration = true; + _file_path = log_conf.log_path(); + switch (log_conf.log_type()) { + case config::logger_type::LOGGER_FILE: { + if (log_conf.max_size()) + my_sink = std::make_shared( + _file_path, log_conf.max_size(), 99); + else + my_sink = std::make_shared(_file_path); + } break; + case config::logger_type::LOGGER_SYSLOG: + my_sink = + std::make_shared(_file_path, 0, 0, true); + break; + case config::logger_type::LOGGER_STDOUT: + my_sink = std::make_shared(); + break; + } + + for (int32_t id = 0; id < LOGGER_SIZE; id++) { + std::vector sinks; + + /* Little hack to include the broker sink to engine loggers. */ + auto& name = _logger_name[id]; + if (log_conf.loggers_with_custom_sinks().contains(name)) + sinks = log_conf.custom_sinks(); + + sinks.push_back(my_sink); + auto logger = _loggers[id]; + logger->sinks() = sinks; + if (log_conf.log_pid()) { + if (log_conf.log_source()) + logger->set_pattern( + "[%Y-%m-%dT%H:%M:%S.%e%z] [%n] [%l] [%s:%#] [%P] %v"); + else + logger->set_pattern("[%Y-%m-%dT%H:%M:%S.%e%z] [%n] [%l] [%P] %v"); + } else { + if (log_conf.log_source()) + logger->set_pattern("[%Y-%m-%dT%H:%M:%S.%e%z] [%n] [%l] [%s:%#] %v"); + else + logger->set_pattern("[%Y-%m-%dT%H:%M:%S.%e%z] [%n] [%l] %v"); + } + + if (name == "grpc" && log_conf.loggers().contains(name)) { + level::level_enum lvl = level::from_str(log_conf.loggers().at(name)); + switch (lvl) { + case level::level_enum::trace: + case level::level_enum::debug: + gpr_set_log_verbosity(GPR_LOG_SEVERITY_DEBUG); + break; + case level::level_enum::info: + case level::level_enum::warn: + gpr_set_log_verbosity(GPR_LOG_SEVERITY_INFO); + break; + default: + gpr_set_log_verbosity(GPR_LOG_SEVERITY_ERROR); + break; + } + } + } + _not_threadsafe_configuration = false; + } + + _flush_interval = std::chrono::seconds( + log_conf.flush_interval() > 0 ? log_conf.flush_interval() : 0); + spdlog::flush_every(_flush_interval); + /* This is for all loggers, a slave will overwrite the master configuration */ + for (int32_t id = 0; id < LOGGER_SIZE; id++) { + auto& name = _logger_name[id]; + if (log_conf.loggers().contains(name)) { + auto logger = _loggers[id]; + level::level_enum lvl = level::from_str(log_conf.loggers().at(name)); + logger->set_level(lvl); + if (log_conf.flush_interval() > 0) + logger->flush_on(level::warn); + else + logger->flush_on(lvl); + } + } +} + +/** + * @brief Check if the given logger makes part of our loggers + * + * @param logger A logger name + * + * @return a boolean. + */ +bool log_v2::contains_logger(std::string_view logger) const { + absl::flat_hash_set loggers; + for (auto& n : _logger_name) + loggers.insert(n); + return loggers.contains(logger); +} + +/** + * @brief Check if the given level makes part of the available levels. + * + * @param level A level as a string + * + * @return A boolean. + */ +bool log_v2::contains_level(const std::string& level) const { + /* spdlog wants 'off' to disable a log but we tolerate 'disabled' */ + if (level == "disabled" || level == "off") + return true; + + level::level_enum l = level::from_str(level); + return l != level::off; +} + +std::vector> log_v2::levels() + const { + std::vector> retval; + retval.reserve(_loggers.size()); + for (auto& l : _loggers) { + if (l) { + auto level = l->level(); + retval.emplace_back(l->name(), level); + } + } + return retval; +} + +const std::string& log_v2::log_name() const { + return _log_name; +} + +void log_v2::disable() { + for (auto& l : _loggers) + /* Loggers can be not defined in case of legacy logger enabled. */ + if (l) + l->set_level(spdlog::level::level_enum::off); +} + +void log_v2::disable(std::initializer_list ilist) { + for (logger_id id : ilist) { + /* Loggers can be not defined in case of legacy logger enabled. */ + if (_loggers[id]) + _loggers[id]->set_level(spdlog::level::level_enum::off); + } +} diff --git a/common/log_v2/log_v2.hh b/common/log_v2/log_v2.hh new file mode 100644 index 00000000000..3fe6b0f4ad4 --- /dev/null +++ b/common/log_v2/log_v2.hh @@ -0,0 +1,128 @@ +/** + * Copyright 2023-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ +#ifndef CCC_LOG_V2_HH +#define CCC_LOG_V2_HH + +#include + +#include +#include +#include +#include + +#include "config.hh" + +namespace com::centreon::common::log_v2 { + +constexpr uint32_t log_v2_core = 0; +constexpr uint32_t log_v2_config = 1; +constexpr uint32_t log_v2_process = 2; +constexpr uint32_t log_v2_configuration = 3; + +/** + * @brief Unified log module for broker and engine. + * + * To instance a logger with a name, we call the static internal function + * create_logger(name). It creates the logger and returns an ID useful to + * get back the logger. We know that spdlog is able to return the logger from + * its name, but by this way it gets the logger in a hashtable protected by + * a mutex which is more expensive. + * + * With the ID, we can get the logger with the static internal function get(ID). + * During a reload, only atomic changes are allowed. So we cannot change the + * log file, but we can change levels. + * + */ +class log_v2 { + std::atomic_bool _not_threadsafe_configuration = false; + + public: + enum logger_id { + CORE = 0, + CONFIG = 1, + BAM = 2, + BBDO = 3, + LUA = 4, + INFLUXDB = 5, + GRAPHITE = 6, + RRD = 7, + STATS = 8, + PERFDATA = 9, + PROCESSING = 10, + SQL = 11, + NEB = 12, + TCP = 13, + TLS = 14, + GRPC = 15, + VICTORIA_METRICS = 16, + PROCESS = 17, + FUNCTIONS = 18, + EVENTS = 19, + CHECKS = 20, + NOTIFICATIONS = 21, + EVENTBROKER = 22, + EXTERNAL_COMMAND = 23, + COMMANDS = 24, + DOWNTIMES = 25, + COMMENTS = 26, + MACROS = 27, + RUNTIME = 28, + LOGGER_SIZE + }; + + private: + static log_v2* _instance; + std::string _log_name; + std::chrono::seconds _flush_interval; + std::string _file_path; + const static std::array _logger_name; + std::array, LOGGER_SIZE> _loggers; + std::atomic _current_log_type; + size_t _current_max_size = 0U; + bool _log_pid = false; + bool _log_source = false; + + public: + static void load(std::string name); + static void unload(); + static log_v2& instance(); + log_v2(std::string name); + log_v2(const log_v2&) = delete; + log_v2& operator=(const log_v2&) = delete; + ~log_v2() noexcept = default; + logger_id get_id(const std::string& name) const noexcept; + + std::chrono::seconds flush_interval(); + void set_flush_interval(uint32_t second_flush_interval); + void create_loggers(config::logger_type typ, size_t length = 0); + std::shared_ptr create_logger(const logger_id id); + std::shared_ptr get(const logger_id idx); + void apply(const config& conf); + bool contains_logger(std::string_view logger) const; + bool contains_level(const std::string& level) const; + const std::string& filename() const { return _file_path; } + std::vector> levels() const; + const std::string& log_name() const; + void disable(); + void disable(std::initializer_list ilist); + bool not_threadsafe_configuration() const { + return _not_threadsafe_configuration; + } +}; +} // namespace com::centreon::common::log_v2 +#endif /* !CCC_LOG_V2_HH */ diff --git a/common/test/CMakeLists.txt b/common/tests/CMakeLists.txt similarity index 63% rename from common/test/CMakeLists.txt rename to common/tests/CMakeLists.txt index 08b61a4a9be..1a4a782fb35 100644 --- a/common/test/CMakeLists.txt +++ b/common/tests/CMakeLists.txt @@ -1,59 +1,66 @@ -# -# Copyright 2023 Centreon -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may not -# use this file except in compliance with the License. You may obtain a copy of -# the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations under -# the License. -# -# For more information : contact@centreon.com -# - - - -add_executable(ut_common - process_stat_test.cc - hex_dump_test.cc - node_allocator_test.cc - rapidjson_helper_test.cc - test_main.cc - ${TESTS_SOURCES}) - -add_test(NAME tests COMMAND ut_common) - -target_link_libraries(ut_common PRIVATE - centreon_common - centreon_http - crypto - ssl - GTest::gtest - GTest::gtest_main - GTest::gmock - GTest::gmock_main - absl::any - absl::log - absl::base - absl::bits - fmt::fmt pthread) - -add_dependencies(ut_common centreon_common centreon_http) - -set_property(TARGET ut_common PROPERTY POSITION_INDEPENDENT_CODE ON) - -target_precompile_headers(ut_common PRIVATE ${PROJECT_SOURCE_DIR}/precomp_inc/precomp.hh) - -set_target_properties( - ut_common - PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/tests - RUNTIME_OUTPUT_DIRECTORY_DEBUG ${CMAKE_BINARY_DIR}/tests - RUNTIME_OUTPUT_DIRECTORY_RELEASE ${CMAKE_BINARY_DIR}/tests - RUNTIME_OUTPUT_DIRECTORY_RELWITHDEBINFO ${CMAKE_BINARY_DIR}/tests - RUNTIME_OUTPUT_DIRECTORY_MINSIZEREL ${CMAKE_BINARY_DIR}/tests) - +# +# Copyright 2023-2024 Centreon +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may not +# use this file except in compliance with the License. You may obtain a copy of +# the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations under +# the License. +# +# For more information : contact@centreon.com +# + +add_executable(ut_common + process_stat_test.cc + hex_dump_test.cc + log_v2/log_v2.cc + node_allocator_test.cc + rapidjson_helper_test.cc +) + +set_target_properties( + ut_common + PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/tests + RUNTIME_OUTPUT_DIRECTORY_DEBUG ${CMAKE_BINARY_DIR}/tests + RUNTIME_OUTPUT_DIRECTORY_RELEASE ${CMAKE_BINARY_DIR}/tests + RUNTIME_OUTPUT_DIRECTORY_RELWITHDEBINFO ${CMAKE_BINARY_DIR}/tests + RUNTIME_OUTPUT_DIRECTORY_MINSIZEREL ${CMAKE_BINARY_DIR}/tests) + +if(WITH_COVERAGE) + set(COVERAGE_EXCLUDES '${PROJECT_SOURCE_DIR}/test/*' '/usr/include/*') + setup_target_for_coverage(NAME clib-test-coverage EXECUTABLE ut_clib + DEPENDENCIES ut_clib) + set(GCOV gcov) +endif() + +add_test(NAME tests COMMAND ut_common) + +target_link_libraries( + ut_common + PRIVATE centreon_common + crypto + ssl + re2::re2 + log_v2 + GTest::gtest + GTest::gtest_main + GTest::gmock + GTest::gmock_main + absl::any + absl::log + absl::base + absl::bits + fmt::fmt + pthread) + +add_dependencies(ut_common centreon_common) + +set_property(TARGET ut_common PROPERTY POSITION_INDEPENDENT_CODE ON) + +target_precompile_headers(ut_common PRIVATE ${PROJECT_SOURCE_DIR}/precomp_inc/precomp.hh) diff --git a/common/test/hex_dump_test.cc b/common/tests/hex_dump_test.cc similarity index 57% rename from common/test/hex_dump_test.cc rename to common/tests/hex_dump_test.cc index 0b6be680b5a..f3e2b5c9d03 100644 --- a/common/test/hex_dump_test.cc +++ b/common/tests/hex_dump_test.cc @@ -1,20 +1,20 @@ /** -* Copyright 2023 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2023 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include diff --git a/common/tests/log_v2/log_v2.cc b/common/tests/log_v2/log_v2.cc new file mode 100644 index 00000000000..66ab44d67be --- /dev/null +++ b/common/tests/log_v2/log_v2.cc @@ -0,0 +1,154 @@ +/** + * Copyright 2023 Centreon (https://www.centreon.com/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ +#include "common/log_v2/log_v2.hh" +#include +#include +#include +#include + +using log_v2 = com::centreon::common::log_v2::log_v2; +using config = com::centreon::common::log_v2::config; + +class TestLogV2 : public ::testing::Test { + public: + // void SetUp() override {} + void TearDown() override { log_v2::unload(); } +}; + +static std::string read_file(const std::string& name) { + std::ifstream is(name); + if (is) { + std::stringstream buffer; + buffer << is.rdbuf(); + is.close(); + return buffer.str(); + } + return {}; +} + +// When the log_v2 is loaded, we can access all its loggers. +TEST_F(TestLogV2, load) { + log_v2::load("ut_common"); + ASSERT_EQ(log_v2::instance().get(log_v2::CORE)->name(), + std::string_view("core")); + ASSERT_EQ(log_v2::instance().get(log_v2::CONFIG)->name(), + std::string_view("config")); +} + +// Given a log_v2 loaded. +// When the level of a logger is info +// Then a log of level debug is not displayed +// When the level of a logger is debug +// Then a log of level debug is also displayed +TEST_F(TestLogV2, LoggerUpdated) { + log_v2::load("ut_common"); + const auto& core_logger = log_v2::instance().get(log_v2::CORE); + ASSERT_EQ(core_logger->level(), spdlog::level::info); + testing::internal::CaptureStdout(); + core_logger->info("First log"); + core_logger->debug("First debug log"); + config cfg("/tmp/test.log", config::logger_type::LOGGER_STDOUT, 0, false, + false); + cfg.set_level("core", "debug"); + log_v2::instance().apply(cfg); + ASSERT_EQ(core_logger->level(), spdlog::level::debug); + core_logger->info("Second log"); + core_logger->debug("Second debug log"); + std::string output = testing::internal::GetCapturedStdout(); + std::cout << "Captured stdout:\n" << output << std::endl; + /* To match the output, we use regex because of the colored output. */ + + std::vector lines = absl::StrSplit(output, "\n"); + ASSERT_GE(lines.size(), 3U) << "We should have at least three lines of log"; + ASSERT_TRUE( + RE2::PartialMatch(lines[0], "\\[core\\] \\[.*info.*\\] First log")) + << "The first log should be of type 'info'"; + ASSERT_TRUE( + RE2::PartialMatch(lines[1], "\\[core\\] \\[.*info.*\\] Second log")) + << "The second log should be of type 'info'"; + ASSERT_TRUE(RE2::PartialMatch(lines[2], + "\\[core\\] \\[.*debug.*\\] Second debug log")) + << "The third log should be of type 'debug'"; + std::remove("/tmp/test.log"); +} + +TEST_F(TestLogV2, Flush) { + /* We remove the file if it exists */ + struct stat buffer; + if (stat("/tmp/test.log", &buffer) == 0) + std::remove("/tmp/test.log"); + + log_v2::load("ut_common"); + config cfg("/tmp/test.log", config::logger_type::LOGGER_FILE, 3, false, + false); + cfg.set_level("core", "debug"); + log_v2::instance().apply(cfg); + auto logger = log_v2::instance().get(log_v2::CORE); + + logger->debug("log 1"); + std::string content = read_file("/tmp/test.log"); + ASSERT_TRUE(content.empty()) + << "Log flush is run every 3s, we should not have any file for now." + << std::endl; + + std::this_thread::sleep_for(std::chrono::seconds(1)); + logger->debug("log 2"); + content = read_file("/tmp/test.log"); + ASSERT_TRUE(content.empty()) + << "Log flush is run every 3s, we should not have any file for now." + << std::endl; + + logger->debug("log 3"); + std::this_thread::sleep_for(std::chrono::seconds(3)); + content = read_file("/tmp/test.log"); + auto spl = absl::StrSplit(content, '\n'); + auto it = spl.begin(); + for (int i = 1; i <= 3; i++) { + std::string str(fmt::format("log {}", i)); + ASSERT_TRUE(it != spl.end()) + << "We should at least have three lines of log" << std::endl; + ASSERT_TRUE(it->find(str) != std::string::npos) + << "The line '" << *it << "' should contain '" << str << "'" + << std::endl; + ++it; + } + + std::remove("/tmp/test.log"); + + /* The flush is disabled */ + cfg.set_flush_interval(0); + log_v2::instance().apply(cfg); + + logger->debug("log 1"); + logger->debug("log 2"); + logger->debug("log 3"); + std::this_thread::sleep_for(std::chrono::seconds(1)); + content = read_file("/tmp/test.log"); + ASSERT_TRUE(content.find("log 1") != std::string::npos) + << "Log flush is disabled, we should not have all the logs, here 'log 1'." + << std::endl; + ASSERT_TRUE(content.find("log 2") != std::string::npos) + << "Log flush is disabled, we should not have all the logs, here 'log 2'." + << std::endl; + ASSERT_TRUE(content.find("log 3") != std::string::npos) + << "Log flush is disabled, we should not have all the logs, here 'log 3'." + << std::endl; + + std::remove("/tmp/test.log"); +} diff --git a/common/test/node_allocator_test.cc b/common/tests/node_allocator_test.cc similarity index 77% rename from common/test/node_allocator_test.cc rename to common/tests/node_allocator_test.cc index ce182aef8f1..3052ca8bac6 100644 --- a/common/test/node_allocator_test.cc +++ b/common/tests/node_allocator_test.cc @@ -1,20 +1,20 @@ /** -* Copyright 2023 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2023 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include #include diff --git a/common/test/process_stat_test.cc b/common/tests/process_stat_test.cc similarity index 95% rename from common/test/process_stat_test.cc rename to common/tests/process_stat_test.cc index 401ccf777c5..f188176b7e0 100644 --- a/common/test/process_stat_test.cc +++ b/common/tests/process_stat_test.cc @@ -1,5 +1,5 @@ /** - * Copyright 2024 Centreon (https://www.centreon.com/) + * Copyright 2023-2024 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/common/test/rapidjson_helper_test.cc b/common/tests/rapidjson_helper_test.cc similarity index 100% rename from common/test/rapidjson_helper_test.cc rename to common/tests/rapidjson_helper_test.cc diff --git a/engine/CMakeLists.txt b/engine/CMakeLists.txt index a4aa5ef8d30..5203a17f4c4 100644 --- a/engine/CMakeLists.txt +++ b/engine/CMakeLists.txt @@ -1,5 +1,5 @@ # -# Copyright 2011-2023 Centreon +# Copyright 2011-2024 Centreon # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of @@ -47,8 +47,7 @@ set(PRECOMP_HEADER "${PROJECT_SOURCE_DIR}/precomp_inc/precomp.hh") set(ENGINE_MODULES_DIR "${CMAKE_INSTALL_PREFIX}/lib64/centreon-engine/") -include_directories("${INC_DIR}" -"${INC_DIR}/compatibility") +include_directories("${INC_DIR}" "${INC_DIR}/compatibility") link_directories(${CMAKE_SOURCE_DIR}/build/centreon-clib/) @@ -148,9 +147,6 @@ set(CREATE_FILES "${WITH_CREATE_FILES}") set(PREFIX_ENGINE_CONF "${CMAKE_INSTALL_FULL_SYSCONFDIR}/centreon-engine") -# # Library directory. if (WITH_PREFIX_LIB_ENGINE) set(PREFIX_LIB -# "${WITH_PREFIX_LIB_ENGINE}") else () set(PREFIX_LIB -# "${CMAKE_INSTALL_PREFIX}/lib/centreon-engine") endif () # # User used to run Centreon Engine. @@ -498,10 +494,6 @@ include_directories(enginerpc ${CMAKE_SOURCE_DIR}/common/inc) # Library engine target. -add_library(enginelog STATIC src/log_v2.cc) -target_precompile_headers(enginelog PRIVATE ${PRECOMP_HEADER}) -set_target_properties(enginelog PROPERTIES COMPILE_FLAGS "-fPIC") -target_link_libraries(enginelog spdlog::spdlog) add_library(cce_core ${LIBRARY_TYPE} ${FILES}) add_dependencies(cce_core engine_rpc) @@ -521,8 +513,8 @@ target_link_libraries( spdlog::spdlog) # centengine target. -add_executable("centengine" "${SRC_DIR}/main.cc") -set_property(TARGET "centengine" PROPERTY ENABLE_EXPORTS "1") +add_executable(centengine "${SRC_DIR}/main.cc") +set_property(TARGET centengine PROPERTY ENABLE_EXPORTS "1") add_dependencies(centengine centreon_clib) # Link centengine with required libraries. @@ -531,15 +523,22 @@ target_link_libraries( -L${PROTOBUF_LIB_DIR} "-rdynamic" centreon_clib - enginelog + log_v2 "-Wl,-whole-archive" enginerpc cce_core gRPC::grpc++ "-Wl,--no-whole-archive" - gRPC::gpr gRPC::grpc gRPC::grpc++ gRPC::grpc++_alts - absl::any absl::log absl::base absl::bits - crypto ssl + gRPC::gpr + gRPC::grpc + gRPC::grpc++ + gRPC::grpc++_alts + absl::any + absl::log + absl::base + absl::bits + crypto + ssl ${c-ares_LIBS} z ryml::ryml diff --git a/engine/enginerpc/engine.proto b/engine/enginerpc/engine.proto index dec6a227889..f11b867dda0 100644 --- a/engine/enginerpc/engine.proto +++ b/engine/enginerpc/engine.proto @@ -28,7 +28,8 @@ import "process_stat.proto"; package com.centreon.engine; service Engine { - rpc GetProcessStats(google.protobuf.Empty) returns (com.centreon.common.pb_process_stat) {} + rpc GetProcessStats(google.protobuf.Empty) + returns (com.centreon.common.pb_process_stat) {} rpc GetVersion(google.protobuf.Empty) returns (Version) {} rpc GetStats(GenericString) returns (Stats) {} rpc GetHost(HostIdentifier) returns (EngineHost) {} @@ -139,7 +140,6 @@ service Engine { */ rpc SetLogFlushPeriod(LogFlushPeriod) returns (google.protobuf.Empty) {} - /** * @brief Send a Bench Message. * @@ -147,7 +147,7 @@ service Engine { * * @return nothing. */ - rpc SendBench(BenchParam) returns (google.protobuf.Empty) {} + rpc SendBench(BenchParam) returns (google.protobuf.Empty) {} } message GenericString { @@ -580,13 +580,10 @@ message ChangeObjectCustomVar { } message LogInfo { - message LoggerInfo { - string log_name = 1; - string log_file = 2; - uint32 log_flush_period = 3; - map level = 4; - } - repeated LoggerInfo loggers = 1; + string log_name = 1; + string log_file = 2; + uint32 log_flush_period = 3; + map level = 4; } message LogFlushPeriod { @@ -609,5 +606,5 @@ message LogLevel { message BenchParam { uint32 id = 1; - google.protobuf.Timestamp ts=2; + google.protobuf.Timestamp ts = 2; } diff --git a/engine/enginerpc/engine_impl.cc b/engine/enginerpc/engine_impl.cc index b8d5f7b2144..0476f9dc9d0 100644 --- a/engine/enginerpc/engine_impl.cc +++ b/engine/enginerpc/engine_impl.cc @@ -55,18 +55,20 @@ namespace asio = boost::asio; #include "com/centreon/engine/globals.hh" #include "com/centreon/engine/hostdependency.hh" #include "com/centreon/engine/hostgroup.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/service.hh" #include "com/centreon/engine/servicedependency.hh" #include "com/centreon/engine/servicegroup.hh" #include "com/centreon/engine/statistics.hh" #include "com/centreon/engine/statusdata.hh" #include "com/centreon/engine/version.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::engine; using namespace com::centreon::engine::logging; using namespace com::centreon::engine::downtimes; +using com::centreon::common::log_v2::log_v2; + namespace com::centreon::engine { std::ostream& operator<<(std::ostream& str, const HostIdentifier& host_id) { @@ -89,7 +91,7 @@ std::ostream& operator<<(std::ostream& str, const ServiceIdentifier& serv_id) { str << "host name=" << serv_id.names().host_name() << " serv name=" << serv_id.names().service_name(); break; - case HostIdentifier::kId: + case ServiceIdentifier::kIds: str << "host id=" << serv_id.ids().host_id() << " serv id=" << serv_id.ids().service_id(); break; @@ -129,9 +131,9 @@ grpc::Status engine_impl::GetVersion( } grpc::Status engine_impl::GetStats(grpc::ServerContext* context - __attribute__((unused)), + [[maybe_unused]], const GenericString* request - __attribute__((unused)), + [[maybe_unused]], Stats* response) { auto fn = std::packaged_task( std::bind(&command_manager::get_stats, &command_manager::instance(), @@ -146,10 +148,10 @@ grpc::Status engine_impl::GetStats(grpc::ServerContext* context } grpc::Status engine_impl::ProcessServiceCheckResult(grpc::ServerContext* context - __attribute__((unused)), + [[maybe_unused]], const Check* request, CommandSuccess* response - __attribute__((unused))) { + [[maybe_unused]]) { std::string const& host_name = request->host_name(); if (host_name.empty()) return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, @@ -172,10 +174,10 @@ grpc::Status engine_impl::ProcessServiceCheckResult(grpc::ServerContext* context } grpc::Status engine_impl::ProcessHostCheckResult(grpc::ServerContext* context - __attribute__((unused)), + [[maybe_unused]], const Check* request, CommandSuccess* response - __attribute__((unused))) { + [[maybe_unused]]) { std::string const& host_name = request->host_name(); if (host_name.empty()) return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, @@ -206,10 +208,10 @@ grpc::Status engine_impl::ProcessHostCheckResult(grpc::ServerContext* context * @return A grpc::Status::OK if the file is well read, an error otherwise. */ grpc::Status engine_impl::NewThresholdsFile(grpc::ServerContext* context - __attribute__((unused)), + [[maybe_unused]], const ThresholdsFile* request, CommandSuccess* response - __attribute__((unused))) { + [[maybe_unused]]) { const std::string& filename = request->filename(); auto fn = std::packaged_task( std::bind(&anomalydetection::update_thresholds, filename)); @@ -226,10 +228,9 @@ grpc::Status engine_impl::NewThresholdsFile(grpc::ServerContext* context * *@return Status::OK */ -grpc::Status engine_impl::GetHost(grpc::ServerContext* context - __attribute__((unused)), +grpc::Status engine_impl::GetHost(grpc::ServerContext* context [[maybe_unused]], const HostIdentifier* request - __attribute__((unused)), + [[maybe_unused]], EngineHost* response) { std::string err; auto fn = std::packaged_task( @@ -269,7 +270,7 @@ grpc::Status engine_impl::GetHost(grpc::ServerContext* context * @return Status::OK **/ grpc::Status engine_impl::GetContact(grpc::ServerContext* context - __attribute__((unused)), + [[maybe_unused]], const ContactIdentifier* request, EngineContact* response) { std::string err; @@ -309,7 +310,7 @@ grpc::Status engine_impl::GetContact(grpc::ServerContext* context *@return Status::OK */ grpc::Status engine_impl::GetService(grpc::ServerContext* context - __attribute__((unused)), + [[maybe_unused]], const ServiceIdentifier* request, EngineService* response) { std::string err; @@ -351,9 +352,9 @@ grpc::Status engine_impl::GetService(grpc::ServerContext* context *@return Status::OK */ grpc::Status engine_impl::GetHostsCount(grpc::ServerContext* context - __attribute__((unused)), + [[maybe_unused]], const ::google::protobuf::Empty* request - __attribute__((unused)), + [[maybe_unused]], GenericValue* response) { auto fn = std::packaged_task( []() -> int32_t { return host::hosts.size(); }); @@ -377,8 +378,8 @@ grpc::Status engine_impl::GetHostsCount(grpc::ServerContext* context */ grpc::Status engine_impl::GetContactsCount( - grpc::ServerContext* context __attribute__((unused)), - const ::google::protobuf::Empty* request __attribute__((unused)), + grpc::ServerContext* context [[maybe_unused]], + const ::google::protobuf::Empty* request [[maybe_unused]], GenericValue* response) { auto fn = std::packaged_task( []() -> int32_t { return contact::contacts.size(); }); @@ -401,8 +402,8 @@ grpc::Status engine_impl::GetContactsCount( * @return Status::OK */ grpc::Status engine_impl::GetServicesCount( - grpc::ServerContext* context __attribute__((unused)), - const ::google::protobuf::Empty* request __attribute__((unused)), + grpc::ServerContext* context [[maybe_unused]], + const ::google::protobuf::Empty* request [[maybe_unused]], GenericValue* response) { auto fn = std::packaged_task( []() -> int32_t { return service::services.size(); }); @@ -424,8 +425,8 @@ grpc::Status engine_impl::GetServicesCount( *@return Status::OK */ grpc::Status engine_impl::GetServiceGroupsCount( - grpc::ServerContext* context __attribute__((unused)), - const ::google::protobuf::Empty* request __attribute__((unused)), + grpc::ServerContext* context [[maybe_unused]], + const ::google::protobuf::Empty* request [[maybe_unused]], GenericValue* response) { auto fn = std::packaged_task( []() -> int32_t { return servicegroup::servicegroups.size(); }); @@ -446,8 +447,8 @@ grpc::Status engine_impl::GetServiceGroupsCount( * @return Status::OK */ grpc::Status engine_impl::GetContactGroupsCount( - grpc::ServerContext* context __attribute__((unused)), - const ::google::protobuf::Empty* request __attribute__((unused)), + grpc::ServerContext* context [[maybe_unused]], + const ::google::protobuf::Empty* request [[maybe_unused]], GenericValue* response) { auto fn = std::packaged_task( []() -> int32_t { return contactgroup::contactgroups.size(); }); @@ -468,8 +469,8 @@ grpc::Status engine_impl::GetContactGroupsCount( * @return Status::OK */ grpc::Status engine_impl::GetHostGroupsCount( - grpc::ServerContext* context __attribute__((unused)), - const ::google::protobuf::Empty* request __attribute__((unused)), + grpc::ServerContext* context [[maybe_unused]], + const ::google::protobuf::Empty* request [[maybe_unused]], GenericValue* response) { auto fn = std::packaged_task( []() -> int32_t { return hostgroup::hostgroups.size(); }); @@ -3045,28 +3046,26 @@ grpc::Status engine_impl::ShutdownProgram( return grpc::Status::OK; } -#define HOST_METHOD_BEGIN \ - SPDLOG_LOGGER_DEBUG(log_v2::external_command(), "{}({})", __FUNCTION__, \ - *request); \ - auto host_info = get_host(*request); \ - if (!host_info.second.empty()) { \ - SPDLOG_LOGGER_ERROR(log_v2::external_command(), \ - "{}({}) : unknown host {}", __FUNCTION__, *request, \ - host_info.second); \ - return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, \ - host_info.second); \ +#define HOST_METHOD_BEGIN \ + SPDLOG_LOGGER_DEBUG(external_command_logger, "{}({})", __FUNCTION__, \ + *request); \ + auto host_info = get_host(*request); \ + if (!host_info.second.empty()) { \ + SPDLOG_LOGGER_ERROR(external_command_logger, "{}({}) : unknown host {}", \ + __FUNCTION__, *request, host_info.second); \ + return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, \ + host_info.second); \ } -#define SERV_METHOD_BEGIN \ - SPDLOG_LOGGER_DEBUG(log_v2::external_command(), "{}({})", __FUNCTION__, \ - *request); \ - auto serv_info = get_serv(*request); \ - if (!serv_info.second.empty()) { \ - SPDLOG_LOGGER_ERROR(log_v2::external_command(), \ - "{}({}) : unknown serv {}", __FUNCTION__, *request, \ - serv_info.second); \ - return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, \ - serv_info.second); \ +#define SERV_METHOD_BEGIN \ + SPDLOG_LOGGER_DEBUG(external_command_logger, "{}({})", __FUNCTION__, \ + *request); \ + auto serv_info = get_serv(*request); \ + if (!serv_info.second.empty()) { \ + SPDLOG_LOGGER_ERROR(external_command_logger, "{}({}) : unknown serv {}", \ + __FUNCTION__, *request, serv_info.second); \ + return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, \ + serv_info.second); \ } ::grpc::Status engine_impl::EnableHostAndChildNotifications( @@ -3145,17 +3144,17 @@ ::grpc::Status engine_impl::ChangeAnomalyDetectionSensitivity( ::grpc::ServerContext* context, const ::com::centreon::engine::ChangeServiceNumber* serv_and_value, ::com::centreon::engine::CommandSuccess* response) { - SPDLOG_LOGGER_DEBUG(log_v2::external_command(), "{}({})", __FUNCTION__, + SPDLOG_LOGGER_DEBUG(external_command_logger, "{}({})", __FUNCTION__, serv_and_value->serv()); auto serv_info = get_serv(serv_and_value->serv()); if (!serv_info.second.empty()) { - SPDLOG_LOGGER_ERROR(log_v2::external_command(), "{}({}) : unknown serv {}", + SPDLOG_LOGGER_ERROR(external_command_logger, "{}({}) : unknown serv {}", __FUNCTION__, serv_and_value->serv(), serv_info.second); return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, serv_info.second); } if (serv_info.first->get_service_type() != service_type::ANOMALY_DETECTION) { - SPDLOG_LOGGER_ERROR(log_v2::external_command(), + SPDLOG_LOGGER_ERROR(external_command_logger, "{}({}) : {} is not an anomalydetection", __FUNCTION__, serv_and_value->serv(), serv_info.second); return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, serv_info.second); @@ -3173,7 +3172,7 @@ ::grpc::Status engine_impl::ChangeAnomalyDetectionSensitivity( ano->set_sensitivity(serv_and_value->intval()); return grpc::Status::OK; } - SPDLOG_LOGGER_ERROR(log_v2::external_command(), "{}({}) : no value provided", + SPDLOG_LOGGER_ERROR(external_command_logger, "{}({}) : no value provided", __FUNCTION__, serv_and_value->serv()); return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, "no value provided"); @@ -3273,35 +3272,21 @@ engine_impl::get_serv( * @return ::grpc::Status */ ::grpc::Status engine_impl::GetLogInfo( - ::grpc::ServerContext* context, - const ::google::protobuf::Empty* request, + ::grpc::ServerContext* context [[maybe_unused]], + const ::google::protobuf::Empty* request [[maybe_unused]], ::com::centreon::engine::LogInfo* response) { - using logger_by_log = - std::map>>; + std::vector> loggers; - logger_by_log summary; - - spdlog::apply_all( - [&summary](const std::shared_ptr& logger_base) { - std::shared_ptr logger = - std::dynamic_pointer_cast(logger_base); - if (logger) { - summary[logger->get_parent()].push_back(logger); - } - }); + spdlog::apply_all([&loggers](const std::shared_ptr& logger) { + loggers.push_back(logger); + }); - for (const auto& by_parent_loggers : summary) { - LogInfo_LoggerInfo* loggers = response->add_loggers(); - loggers->set_log_name(by_parent_loggers.first->log_name()); - loggers->set_log_file(by_parent_loggers.first->file_path()); - loggers->set_log_flush_period( - by_parent_loggers.first->get_flush_interval().count()); - auto& levels = *loggers->mutable_level(); - for (const std::shared_ptr& logger : - by_parent_loggers.second) { - auto level = spdlog::level::to_string_view(logger->level()); - levels[logger->name()] = std::string(level.data(), level.size()); - } + response->set_log_file(log_v2::instance().filename()); + response->set_log_flush_period(log_v2::instance().flush_interval().count()); + auto levels = response->mutable_level(); + for (const auto& logger : loggers) { + auto level = spdlog::level::to_string_view(logger->level()); + (*levels)[logger->name()] = std::string(level.data(), level.size()); } return grpc::Status::OK; } @@ -3315,7 +3300,7 @@ grpc::Status engine_impl::SetLogLevel(grpc::ServerContext* context if (!logger) { std::string err_detail = fmt::format("The '{}' logger does not exist", logger_name); - SPDLOG_LOGGER_ERROR(log_v2::external_command(), err_detail); + SPDLOG_LOGGER_ERROR(external_command_logger, err_detail); return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, err_detail); } else { logger->set_level(spdlog::level::level_enum(request->level())); @@ -3328,18 +3313,7 @@ grpc::Status engine_impl::SetLogFlushPeriod(grpc::ServerContext* context const LogFlushPeriod* request, ::google::protobuf::Empty*) { // first get all log_v2 objects - std::set loggers; - spdlog::apply_all([&](const std::shared_ptr logger) { - std::shared_ptr logger_base = - std::dynamic_pointer_cast(logger); - if (logger_base) { - loggers.insert(logger_base->get_parent()); - } - }); - - for (log_v2_base* to_update : loggers) { - to_update->set_flush_interval(request->period()); - } + log_v2::instance().set_flush_interval(request->period()); return grpc::Status::OK; } @@ -3352,15 +3326,14 @@ grpc::Status engine_impl::SetLogFlushPeriod(grpc::ServerContext* context * @return grpc::Status */ grpc::Status engine_impl::GetProcessStats( - grpc::ServerContext* context, + grpc::ServerContext* context [[maybe_unused]], const google::protobuf::Empty*, com::centreon::common::pb_process_stat* response) { try { com::centreon::common::process_stat stat(getpid()); stat.to_protobuff(*response); } catch (const boost::exception& e) { - SPDLOG_LOGGER_ERROR(log_v2::external_command(), - "fail to get process info: {}", + SPDLOG_LOGGER_ERROR(external_command_logger, "fail to get process info: {}", boost::diagnostic_information(e)); return grpc::Status(grpc::StatusCode::INTERNAL, @@ -3390,4 +3363,4 @@ grpc::Status engine_impl::SendBench( broker_bench(request->id(), client_ts); return grpc::Status::OK; -} \ No newline at end of file +} diff --git a/engine/inc/com/centreon/engine/configuration/applier/state.hh b/engine/inc/com/centreon/engine/configuration/applier/state.hh index 153a7eb8915..888f89eecd5 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/state.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/state.hh @@ -1,21 +1,21 @@ -/* -** Copyright 2011-2019 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ +/** + * Copyright 2011-2024 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #ifndef CCE_CONFIGURATION_APPLIER_STATE_HH #define CCE_CONFIGURATION_APPLIER_STATE_HH @@ -49,6 +49,7 @@ class state { public: void apply(configuration::state& new_cfg); void apply(configuration::state& new_cfg, retention::state& state); + void apply_log_config(configuration::state& new_cfg); static state& instance(); void clear(); @@ -105,6 +106,6 @@ class state { } // namespace applier } // namespace configuration -} +} // namespace com::centreon::engine #endif // !CCE_CONFIGURATION_APPLIER_STATE_HH diff --git a/engine/inc/com/centreon/engine/configuration/state.hh b/engine/inc/com/centreon/engine/configuration/state.hh index 09b37a4512d..e0b3cc2d9ab 100644 --- a/engine/inc/com/centreon/engine/configuration/state.hh +++ b/engine/inc/com/centreon/engine/configuration/state.hh @@ -36,11 +36,12 @@ #include "com/centreon/engine/configuration/severity.hh" #include "com/centreon/engine/configuration/tag.hh" #include "com/centreon/engine/configuration/timeperiod.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" namespace com::centreon::engine::configuration { +class state; + class setter_base { protected: const std::string_view _field_name; diff --git a/engine/inc/com/centreon/engine/configuration/whitelist.hh b/engine/inc/com/centreon/engine/configuration/whitelist.hh index 3b2b8b662c1..37f3fbed5c7 100644 --- a/engine/inc/com/centreon/engine/configuration/whitelist.hh +++ b/engine/inc/com/centreon/engine/configuration/whitelist.hh @@ -19,7 +19,7 @@ #ifndef CCE_CONFIGURATION_WHITELIST_HH #define CCE_CONFIGURATION_WHITELIST_HH -#include "com/centreon/engine/log_v2.hh" +#include "com/centreon/engine/globals.hh" namespace com::centreon::engine::configuration { @@ -93,12 +93,12 @@ whitelist::whitelist(string_iter dir_path_begin, string_iter dir_path_end) { switch (res) { case e_refresh_result::no_directory: SPDLOG_LOGGER_INFO( - log_v2::config(), + config_logger, "no whitelist directory found, all commands are accepted"); break; case e_refresh_result::empty_directory: case e_refresh_result::no_rule: - SPDLOG_LOGGER_INFO(log_v2::config(), + SPDLOG_LOGGER_INFO(config_logger, "whitelist directory found, but no restrictions, " "all commands are accepted"); break; diff --git a/engine/inc/com/centreon/engine/diagnostic.hh b/engine/inc/com/centreon/engine/diagnostic.hh index 6c8036bf6d6..ede466623c6 100644 --- a/engine/inc/com/centreon/engine/diagnostic.hh +++ b/engine/inc/com/centreon/engine/diagnostic.hh @@ -1,21 +1,21 @@ -/* -** Copyright 2013 Merethis -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ +/** + * Copyright 2013 Merethis + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #ifndef CCE_DIAGNOSTIC_HH #define CCE_DIAGNOSTIC_HH @@ -45,6 +45,6 @@ class diagnostic { void _exec_cp(std::string const& src, std::string const& dst); }; -} +} // namespace com::centreon::engine #endif // !CCE_DIAGNOSTIC_HH diff --git a/engine/inc/com/centreon/engine/globals.hh b/engine/inc/com/centreon/engine/globals.hh index 6a696ae344d..1dc0bfb56ab 100644 --- a/engine/inc/com/centreon/engine/globals.hh +++ b/engine/inc/com/centreon/engine/globals.hh @@ -31,10 +31,7 @@ #include "com/centreon/engine/nebmods.hh" #include "com/centreon/engine/restart_stats.hh" #include "com/centreon/engine/utils.hh" - -#ifdef __cplusplus -extern "C" { -#endif /* C++ */ +#include "common/log_v2/log_v2.hh" extern int config_errors; extern int config_warnings; @@ -42,6 +39,19 @@ extern int config_warnings; /* Start/Restart statistics */ extern com::centreon::engine::restart_stats restart_apply_stats; +extern std::shared_ptr checks_logger; +extern std::shared_ptr commands_logger; +extern std::shared_ptr config_logger; +extern std::shared_ptr downtimes_logger; +extern std::shared_ptr eventbroker_logger; +extern std::shared_ptr events_logger; +extern std::shared_ptr external_command_logger; +extern std::shared_ptr functions_logger; +extern std::shared_ptr macros_logger; +extern std::shared_ptr notifications_logger; +extern std::shared_ptr process_logger; +extern std::shared_ptr runtime_logger; + extern com::centreon::engine::configuration::state* config; extern char* config_file; @@ -130,8 +140,6 @@ extern char* illegal_output_chars; extern unsigned int use_large_installation_tweaks; extern uint32_t instance_heartbeat_interval; -#ifdef __cplusplus -} -#endif /* C++ */ +void init_loggers(); #endif /* !CCE_GLOBALS_HH */ diff --git a/engine/inc/com/centreon/engine/log_v2.hh b/engine/inc/com/centreon/engine/log_v2.hh deleted file mode 100644 index 8423065635c..00000000000 --- a/engine/inc/com/centreon/engine/log_v2.hh +++ /dev/null @@ -1,125 +0,0 @@ -/* -** Copyright 2021-2023 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ -#ifndef CCE_LOG_V2_HH -#define CCE_LOG_V2_HH - -#include "log_v2_base.hh" - -namespace com::centreon::engine { -namespace configuration { -class state; -} - -class log_v2 : public log_v2_base { - std::array, 13> _log; - std::atomic_bool _running; - asio::system_timer _flush_timer; - std::mutex _flush_timer_m; - bool _flush_timer_active; - std::shared_ptr _io_context; - - static std::shared_ptr _instance; - - enum logger { - log_config, - log_functions, - log_events, - log_checks, - log_notifications, - log_eventbroker, - log_external_command, - log_commands, - log_downtimes, - log_comments, - log_macros, - log_process, - log_runtime, - }; - - log_v2(const std::shared_ptr& io_context); - - std::shared_ptr get_logger(logger log_type, - const char* log_str); - - void start_flush_timer(spdlog::sink_ptr sink); - - public: - ~log_v2() noexcept; - - void stop_flush_timer(); - void apply(const configuration::state& config); - void set_flush_interval(unsigned second_flush_interval); - static bool contains_level(const std::string& level_name); - static void load(const std::shared_ptr& io_context); - static std::shared_ptr instance(); - static inline std::shared_ptr functions() { - return _instance->get_logger(log_v2::log_functions, "functions"); - } - - static inline std::shared_ptr config() { - return _instance->get_logger(log_v2::log_config, "configuration"); - } - - static inline std::shared_ptr events() { - return _instance->get_logger(log_v2::log_events, "events"); - } - - static inline std::shared_ptr checks() { - return _instance->get_logger(log_v2::log_checks, "checks"); - } - - static inline std::shared_ptr notifications() { - return _instance->get_logger(log_v2::log_notifications, "notifications"); - } - - static inline std::shared_ptr eventbroker() { - return _instance->get_logger(log_v2::log_eventbroker, "eventbroker"); - } - - static inline std::shared_ptr external_command() { - return _instance->get_logger(log_v2::log_external_command, - "external_command"); - } - - static inline std::shared_ptr commands() { - return _instance->get_logger(log_v2::log_commands, "commands"); - } - - static inline std::shared_ptr downtimes() { - return _instance->get_logger(log_v2::log_downtimes, "downtimes"); - } - - static inline std::shared_ptr comments() { - return _instance->get_logger(log_v2::log_comments, "comments"); - } - - static inline std::shared_ptr macros() { - return _instance->get_logger(log_v2::log_macros, "macros"); - } - - static inline std::shared_ptr process() { - return _instance->get_logger(log_v2::log_process, "process"); - } - - static inline std::shared_ptr runtime() { - return _instance->get_logger(log_v2::log_runtime, "runtime"); - } -}; -} // namespace com::centreon::engine - -#endif /* !CCE_LOG_V2_HH */ diff --git a/engine/inc/com/centreon/engine/log_v2_base.hh b/engine/inc/com/centreon/engine/log_v2_base.hh deleted file mode 100644 index 76bb86f4572..00000000000 --- a/engine/inc/com/centreon/engine/log_v2_base.hh +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Copyright 2022-2023 Centreon - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * For more information : contact@centreon.com - */ -#ifndef CCE_LOG_V2_BASE_HH -#define CCE_LOG_V2_BASE_HH - -#include -#include -#include - -namespace com::centreon::engine { - -class log_v2_base { - protected: - std::string _log_name; - std::chrono::seconds _flush_interval; - std::string _file_path; - - public: - log_v2_base(const std::string& logger_name) : _log_name(logger_name) {} - virtual ~log_v2_base() noexcept = default; - - const std::string& log_name() const { return _log_name; } - const std::string& file_path() const { return _file_path; } - - std::chrono::seconds get_flush_interval() const { return _flush_interval; } - void set_flush_interval(uint32_t second_flush_interval) { - _flush_interval = std::chrono::seconds(second_flush_interval); - } -}; - -class log_v2_logger : public spdlog::logger { - log_v2_base* _parent; - - public: - template - log_v2_logger(std::string name, log_v2_base* parent, sink_iter begin, - sink_iter end) - : spdlog::logger(name, begin, end), _parent(parent) {} - - log_v2_logger(std::string name, log_v2_base* parent, spdlog::sink_ptr sink) - : spdlog::logger(name, sink), _parent(parent) {} - - log_v2_base* get_parent() { return _parent; } -}; - -} // namespace com::centreon::engine - -#endif diff --git a/engine/modules/external_commands/src/main.cc b/engine/modules/external_commands/src/main.cc index ebb3d612588..3c3c7e4ff71 100644 --- a/engine/modules/external_commands/src/main.cc +++ b/engine/modules/external_commands/src/main.cc @@ -1,26 +1,26 @@ /** -* Copyright 2022 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2022 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/commands/commands.hh" #include "com/centreon/engine/exceptions/error.hh" -#include "com/centreon/engine/log_v2.hh" +#include "com/centreon/engine/globals.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/modules/external_commands/utils.hh" #include "com/centreon/engine/nebcallbacks.hh" @@ -30,12 +30,6 @@ using namespace com::centreon::engine::logging; using namespace com::centreon::engine; -/************************************** - * * - * Global Objects * - * * - **************************************/ - // Specify the event broker API version. NEB_API_VERSION(CURRENT_NEB_API_VERSION) @@ -107,11 +101,11 @@ extern "C" int nebmodule_deinit(int flags, int reason) { } catch (std::exception const& e) { engine_logger(log_runtime_error, basic) << "external command runtime error `" << e.what() << "'."; - log_v2::runtime()->error("external command runtime error '{}'.", e.what()); + runtime_logger->error("external command runtime error '{}'.", e.what()); } catch (...) { engine_logger(log_runtime_error, basic) << "external command runtime error `unknown'"; - log_v2::runtime()->error("external command runtime error `unknown'"); + runtime_logger->error("external command runtime error `unknown'"); } return (0); } @@ -156,7 +150,7 @@ extern "C" int nebmodule_init(int flags, char const* args, void* handle) { << "Bailing out due to errors encountered while trying to " << "initialize the external command file ... " << "(PID=" << getpid() << ")"; - log_v2::process()->info( + process_logger->info( "Bailing out due to errors encountered while trying to initialize " "the external command file ... (PID={})", getpid()); @@ -171,16 +165,16 @@ extern "C" int nebmodule_init(int flags, char const* args, void* handle) { } catch (std::exception const& e) { engine_logger(log_runtime_error, basic) << "external command runtime error `" << e.what() << "'."; - log_v2::runtime()->error("external command runtime error '{}'.", e.what()); + runtime_logger->error("external command runtime error '{}'.", e.what()); return (1); } catch (...) { engine_logger(log_runtime_error, basic) << "external command runtime error `unknown'."; - log_v2::runtime()->error("external command runtime error `unknown'."); + runtime_logger->error("external command runtime error `unknown'."); return (1); } - return (0); + return 0; } /** diff --git a/engine/modules/external_commands/src/utils.cc b/engine/modules/external_commands/src/utils.cc index 2cb685145df..db249d10003 100644 --- a/engine/modules/external_commands/src/utils.cc +++ b/engine/modules/external_commands/src/utils.cc @@ -1,28 +1,27 @@ /** -* Copyright 2011-2013 Merethis -* Copyright 2020-2021 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2013 Merethis + * Copyright 2020-2021 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/modules/external_commands/utils.hh" #include "com/centreon/engine/commands/processing.hh" #include "com/centreon/engine/common.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/string.hh" #include "nagios.h" @@ -67,7 +66,7 @@ int open_command_file(void) { "you are sure that another copy of Centreon Engine is not " "running, " "you should delete this file."; - log_v2::runtime()->error( + runtime_logger->error( "Error: Could not create external command file '{}' as named pipe: " "({}) -> {}. If this file already exists and " "you are sure that another copy of Centreon Engine is not " @@ -87,7 +86,7 @@ int open_command_file(void) { << "Error: Could not open external command file for reading " "via open(): (" << errno << ") -> " << strerror(errno); - log_v2::runtime()->error( + runtime_logger->error( "Error: Could not open external command file for reading " "via open(): ({}) -> {}", errno, strerror(errno)); @@ -103,7 +102,7 @@ int open_command_file(void) { << "Error: Could not get file descriptor flags on external " "command via fcntl(): (" << errno << ") -> " << strerror(errno); - log_v2::runtime()->error( + runtime_logger->error( "Error: Could not get file descriptor flags on external " "command via fcntl(): ({}) -> {}", errno, strerror(errno)); @@ -115,7 +114,7 @@ int open_command_file(void) { << "Error: Could not set close-on-exec flag on external " "command via fcntl(): (" << errno << ") -> " << strerror(errno); - log_v2::runtime()->error( + runtime_logger->error( "Error: Could not set close-on-exec flag on external " "command via fcntl(): ({}) -> {}", errno, strerror(errno)); @@ -129,7 +128,7 @@ int open_command_file(void) { << "Error: Could not open external command file for " "reading via fdopen(): (" << errno << ") -> " << strerror(errno); - log_v2::runtime()->error( + runtime_logger->error( "Error: Could not open external command file for " "reading via fdopen(): ({}) -> {}", errno, strerror(errno)); @@ -140,7 +139,7 @@ int open_command_file(void) { if (init_command_file_worker_thread() == ERROR) { engine_logger(log_runtime_error, basic) << "Error: Could not initialize command file worker thread."; - log_v2::runtime()->error( + runtime_logger->error( "Error: Could not initialize command file worker thread."); /* close the command file */ fclose(command_file_fp); @@ -178,7 +177,7 @@ int close_command_file(void) { /* worker thread - artificially increases buffer of named pipe */ static void command_file_worker_thread() { - log_v2::external_command()->info("start command_file_worker_thread"); + external_command_logger->info("start command_file_worker_thread"); char input_buffer[MAX_EXTERNAL_COMMAND_LENGTH]; struct pollfd pfd; @@ -208,21 +207,21 @@ static void command_file_worker_thread() { case EBADF: engine_logger(logging_options, basic) << "command_file_worker_thread(): poll(): EBADF"; - log_v2::external_command()->info( + external_command_logger->info( "command_file_worker_thread(): poll(): EBADF"); break; case ENOMEM: engine_logger(logging_options, basic) << "command_file_worker_thread(): poll(): ENOMEM"; - log_v2::external_command()->info( + external_command_logger->info( "command_file_worker_thread(): poll(): ENOMEM"); break; case EFAULT: engine_logger(logging_options, basic) << "command_file_worker_thread(): poll(): EFAULT"; - log_v2::external_command()->info( + external_command_logger->info( "command_file_worker_thread(): poll(): EFAULT"); break; @@ -237,7 +236,7 @@ static void command_file_worker_thread() { default: engine_logger(logging_options, basic) << "command_file_worker_thread(): poll(): Unknown errno value."; - log_v2::external_command()->info( + external_command_logger->info( "command_file_worker_thread(): poll(): Unknown errno value."); break; } @@ -272,7 +271,7 @@ static void command_file_worker_thread() { command_file_fp) != nullptr) { // Check if command is thread-safe (for immediate execution). if (commands::processing::is_thread_safe(input_buffer)) { - log_v2::external_command()->debug("direct execute {}", input_buffer); + external_command_logger->debug("direct execute {}", input_buffer); commands::processing::execute(input_buffer); } // Submit the external command for processing @@ -284,7 +283,7 @@ static void command_file_worker_thread() { tv.tv_usec = 250000; select(0, nullptr, nullptr, nullptr, &tv); } - log_v2::external_command()->debug("push execute {}", input_buffer); + external_command_logger->debug("push execute {}", input_buffer); external_command_buffer.push(input_buffer); // Bail if the circular buffer is full. if (external_command_buffer.full()) @@ -293,7 +292,7 @@ static void command_file_worker_thread() { } } } - log_v2::external_command()->info("end command_file_worker_thread"); + external_command_logger->info("end command_file_worker_thread"); } /* initializes command file worker thread */ diff --git a/engine/src/anomalydetection.cc b/engine/src/anomalydetection.cc index be9813a0153..08dcaadcd50 100644 --- a/engine/src/anomalydetection.cc +++ b/engine/src/anomalydetection.cc @@ -23,7 +23,6 @@ #include "com/centreon/engine/checks/checker.hh" #include "com/centreon/engine/globals.hh" #include "com/centreon/engine/host.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/macros.hh" @@ -198,12 +197,12 @@ uint64_t cancellable_command::run( } else if (_original_command) { uint64_t id = _original_command->run(processed_cmd, macros, timeout, to_push_to_checker, caller); - log_v2::checks()->debug( + checks_logger->debug( "cancellable_command::run command launched id={} cmd {}", id, _original_command); return id; } else { - log_v2::checks()->debug("cancellable_command::run no original command"); + checks_logger->debug("cancellable_command::run no original command"); return 0; } } @@ -226,7 +225,7 @@ const std::string& cancellable_command::get_command_line() const noexcept { if (_original_command) { return _original_command->get_command_line(); } else { - log_v2::commands()->error( + commands_logger->error( "cancellable_command::get_command_line: original command no set"); return _empty; } @@ -237,7 +236,7 @@ void cancellable_command::set_command_line( if (_original_command) { _original_command->set_command_line(command_line); } else { - log_v2::commands()->error( + commands_logger->error( "cancellable_command::set_command_line: original command no set"); } } @@ -621,15 +620,14 @@ com::centreon::engine::anomalydetection* add_anomalydetection( << "Error: Service comes from a database, therefore its service id " << "must not be null"; SPDLOG_LOGGER_ERROR( - log_v2::config(), + config_logger, "Error: Service comes from a database, therefore its service id must " "not be null"); return nullptr; } else if (description.empty()) { engine_logger(log_config_error, basic) << "Error: Service description is not set"; - SPDLOG_LOGGER_ERROR(log_v2::config(), - "Error: Service description is not set"); + SPDLOG_LOGGER_ERROR(config_logger, "Error: Service description is not set"); return nullptr; } else if (!host_name.empty()) { uint64_t hid = get_host_id(host_name); @@ -641,7 +639,7 @@ com::centreon::engine::anomalydetection* add_anomalydetection( "id (" << hid << ")"; SPDLOG_LOGGER_ERROR( - log_v2::config(), + config_logger, "Error: host id ({}) of host ('{}') of anomaly detection service " "'{}' has a conflict between config does not match with the config " "id ({})", @@ -654,7 +652,7 @@ com::centreon::engine::anomalydetection* add_anomalydetection( engine_logger(log_config_error, basic) << "Error: The internal_id in the anomaly detection configuration is " "mandatory"; - SPDLOG_LOGGER_ERROR(log_v2::config(), + SPDLOG_LOGGER_ERROR(config_logger, "Error: The internal_id in the anomaly detection " "configuration is mandatory"); return nullptr; @@ -665,7 +663,7 @@ com::centreon::engine::anomalydetection* add_anomalydetection( << "Error: Dependent service " << dependent_service_id << " does not exist (anomaly detection " << service_id << ")"; SPDLOG_LOGGER_ERROR( - log_v2::config(), + config_logger, "Error: Dependent service {} does not exist (anomaly detection {})", dependent_service_id, service_id); return nullptr; @@ -678,7 +676,7 @@ com::centreon::engine::anomalydetection* add_anomalydetection( "service (host_id:" << host_id << ", service_id:" << service_id << ")"; SPDLOG_LOGGER_ERROR( - log_v2::config(), + config_logger, "Error: metric name must be provided for an anomaly detection " "service (host_id:{}, service_id:{})", host_id, service_id); @@ -691,7 +689,7 @@ com::centreon::engine::anomalydetection* add_anomalydetection( "service (host_id:" << host_id << ", service_id:" << service_id << ")"; SPDLOG_LOGGER_ERROR( - log_v2::config(), + config_logger, "Error: thresholds file must be provided for an anomaly detection " "service (host_id:{}, service_id:{})", host_id, service_id); @@ -706,7 +704,7 @@ com::centreon::engine::anomalydetection* add_anomalydetection( ", or notification_interval value for service '" << description << "' on host '" << host_name << "'"; SPDLOG_LOGGER_ERROR( - log_v2::config(), + config_logger, "Error: Invalid max_attempts, check_interval, retry_interval" ", or notification_interval value for service '{}' on host '{}'", description, host_name); @@ -719,7 +717,7 @@ com::centreon::engine::anomalydetection* add_anomalydetection( << "Error: Service '" << description << "' on host '" << host_name << "' has already been defined"; SPDLOG_LOGGER_ERROR( - log_v2::config(), + config_logger, "Error: Service '{}' on host '{}' has already been defined", description, host_name); return nullptr; @@ -835,7 +833,7 @@ int anomalydetection::run_async_check(int check_options, << ", reschedule_check=" << reschedule_check; SPDLOG_LOGGER_TRACE( - log_v2::functions(), + functions_logger, "anomalydetection::run_async_check, check_options={}, latency={}, " "scheduled_check={}, reschedule_check={}", check_options, latency, scheduled_check, reschedule_check); @@ -845,7 +843,7 @@ int anomalydetection::run_async_check(int check_options, << "' on host '" << get_hostname() << "'..."; SPDLOG_LOGGER_TRACE( - log_v2::checks(), + checks_logger, "** Running async check of anomalydetection '{} ' on host '{}'...", description(), get_hostname()); @@ -885,11 +883,11 @@ int anomalydetection::run_async_check(int check_options, service_state::state_unknown, "failed to calc check_result from perf_data"); if (!parse_perfdata(dependent_perf_data, time(nullptr), *fake_res)) { - SPDLOG_LOGGER_ERROR(log_v2::checks(), + SPDLOG_LOGGER_ERROR(checks_logger, "parse_perfdata failed => unknown state"); } else { SPDLOG_LOGGER_TRACE( - log_v2::checks(), + checks_logger, "** Running async check of anomalydetection '{} ' on host '{}'... " "without check", description(), get_hostname()); @@ -898,13 +896,13 @@ int anomalydetection::run_async_check(int check_options, } else { if (!my_check_command->get_original_command()) { SPDLOG_LOGGER_ERROR( - log_v2::checks(), + checks_logger, "anomaly: no original commands for host {} => do nothing", get_hostname()); return ERROR; } SPDLOG_LOGGER_TRACE( - log_v2::checks(), + checks_logger, "** Running async check of anomalydetection '{} ' on host '{}'... with " "check", description(), get_hostname()); @@ -962,7 +960,7 @@ bool anomalydetection::parse_perfdata(std::string const& perfdata, engine_logger(log_info_message, basic) << "The thresholds file is not viable " "(not available or not readable)."; - SPDLOG_LOGGER_ERROR(log_v2::checks(), + SPDLOG_LOGGER_ERROR(checks_logger, "The thresholds file is not viable " "(not available or not readable)."); oss << "The thresholds file is not viable for metric " << _metric_name @@ -980,8 +978,7 @@ bool anomalydetection::parse_perfdata(std::string const& perfdata, if (pos == std::string::npos) { engine_logger(log_runtime_error, basic) << "Error: Unable to parse perfdata '" << without_thresholds << "'"; - SPDLOG_LOGGER_ERROR(log_v2::runtime(), - "Error: Unable to parse perfdata '{}'", + SPDLOG_LOGGER_ERROR(runtime_logger, "Error: Unable to parse perfdata '{}'", without_thresholds); oss << "UNKNOWN: Unknown activity, " << _metric_name << " did not return any values" @@ -1012,7 +1009,7 @@ bool anomalydetection::parse_perfdata(std::string const& perfdata, << "Error: the thresholds file is too old " "compared to the check timestamp " << check_time; - SPDLOG_LOGGER_ERROR(log_v2::runtime(), + SPDLOG_LOGGER_ERROR(runtime_logger, "Error: the thresholds file is too old " "compared to the check timestamp {}", check_time); @@ -1033,7 +1030,7 @@ bool anomalydetection::parse_perfdata(std::string const& perfdata, << "Error: timestamp " << check_time << " too old compared with the thresholds file"; SPDLOG_LOGGER_ERROR( - log_v2::runtime(), + runtime_logger, "Error: timestamp {} too old compared with the thresholds file", check_time); oss << "timestamp " << check_time @@ -1113,7 +1110,7 @@ void anomalydetection::init_thresholds() { engine_logger(dbg_config, most) << "Trying to read thresholds file '" << _thresholds_file << "'"; - SPDLOG_LOGGER_DEBUG(log_v2::config(), "Trying to read thresholds file '{}'", + SPDLOG_LOGGER_DEBUG(config_logger, "Trying to read thresholds file '{}'", _thresholds_file); std::ifstream t; t.exceptions(t.exceptions() | std::ios::failbit); @@ -1121,14 +1118,13 @@ void anomalydetection::init_thresholds() { t.open(_thresholds_file); } catch (const std::system_error& e) { if (!verify_config) { - SPDLOG_LOGGER_ERROR(log_v2::config(), + SPDLOG_LOGGER_ERROR(config_logger, "Fail to read thresholds file '{}' : {}", _thresholds_file, e.code().message()); } return; } catch (const std::exception& e) { - SPDLOG_LOGGER_ERROR(log_v2::config(), - "Fail to read thresholds file '{}' : {}", + SPDLOG_LOGGER_ERROR(config_logger, "Fail to read thresholds file '{}' : {}", _thresholds_file, e.what()); return; } @@ -1143,7 +1139,7 @@ void anomalydetection::init_thresholds() { engine_logger(log_config_error, basic) << "Error: the file '" << _thresholds_file << "' contains errors: " << e.what(); - SPDLOG_LOGGER_ERROR(log_v2::config(), + SPDLOG_LOGGER_ERROR(config_logger, "Error: the file '{}' contains errors: {}", _thresholds_file, e.what()); return; @@ -1153,7 +1149,7 @@ void anomalydetection::init_thresholds() { << "Error: the file '" << _thresholds_file << "' is not a thresholds file. Its global structure is not an array."; SPDLOG_LOGGER_ERROR( - log_v2::config(), + config_logger, "Error: the file '{}' is not a thresholds file. Its global structure " "is not an array.", _thresholds_file); @@ -1182,7 +1178,7 @@ void anomalydetection::init_thresholds() { "service_id must " "be strings containing integers: " << e.what(); - SPDLOG_LOGGER_ERROR(log_v2::config(), + SPDLOG_LOGGER_ERROR(config_logger, "Error: metric_name and predict are mandatory and " "host_id and service_id must " "be strings containing integers: {}", @@ -1193,7 +1189,7 @@ void anomalydetection::init_thresholds() { metric_name == _metric_name) { set_thresholds_no_lock(_thresholds_file, sensitivity, predict); if (!_thresholds_file_viable) { - SPDLOG_LOGGER_ERROR(log_v2::config(), + SPDLOG_LOGGER_ERROR(config_logger, "{} don't contain at least 2 thresholds datas for " "host_id {} and service_id {}", _thresholds_file, this->host_id(), @@ -1205,7 +1201,7 @@ void anomalydetection::init_thresholds() { } if (!found) { SPDLOG_LOGGER_ERROR( - log_v2::config(), + config_logger, "{} don't contain datas for host_id {} and service_id {}", _thresholds_file, host_id(), this->service_id()); } @@ -1222,22 +1218,19 @@ void anomalydetection::init_thresholds() { int anomalydetection::update_thresholds(const std::string& filename) { engine_logger(log_info_message, most) << "Reading thresholds file '" << filename << "'."; - SPDLOG_LOGGER_INFO(log_v2::checks(), "Reading thresholds file '{}'.", - filename); + SPDLOG_LOGGER_INFO(checks_logger, "Reading thresholds file '{}'.", filename); std::ifstream t; t.exceptions(t.exceptions() | std::ios::failbit); try { t.open(filename); } catch (const std::system_error& e) { - SPDLOG_LOGGER_ERROR(log_v2::config(), - "Fail to read thresholds file '{}' : {}", filename, - e.code().message()); + SPDLOG_LOGGER_ERROR(config_logger, "Fail to read thresholds file '{}' : {}", + filename, e.code().message()); return -1; } catch (const std::exception& e) { - SPDLOG_LOGGER_ERROR(log_v2::config(), - "Fail to read thresholds file '{}' : {}", filename, - e.what()); + SPDLOG_LOGGER_ERROR(config_logger, "Fail to read thresholds file '{}' : {}", + filename, e.what()); return -1; } @@ -1251,7 +1244,7 @@ int anomalydetection::update_thresholds(const std::string& filename) { << "Error: The thresholds file '" << filename << "' should be a json file: " << e.what(); SPDLOG_LOGGER_ERROR( - log_v2::config(), + config_logger, "Error: The thresholds file '{}' should be a json file: {}", filename, e.what()); return -2; @@ -1262,7 +1255,7 @@ int anomalydetection::update_thresholds(const std::string& filename) { << "Error: the file '" << filename << "' is not a thresholds file. Its global structure is not an array."; SPDLOG_LOGGER_ERROR( - log_v2::config(), + config_logger, "Error: the file '{}' is not a thresholds file. Its global structure " "is not an array.", filename); @@ -1290,7 +1283,7 @@ int anomalydetection::update_thresholds(const std::string& filename) { "service_id must " "be strings containing integers: " << e.what(); - SPDLOG_LOGGER_ERROR(log_v2::config(), + SPDLOG_LOGGER_ERROR(config_logger, "Error: metric_name and predict are mandatory, " "host_id and service_id must " "be strings containing integers: {}", @@ -1304,7 +1297,7 @@ int anomalydetection::update_thresholds(const std::string& filename) { "detection service (host_id: " << host_id << ", service_id: " << svc_id << ") that does not exist"; SPDLOG_LOGGER_ERROR( - log_v2::config(), + config_logger, "Error: The thresholds file contains thresholds for the anomaly " "detection service (host_id: {}, service_id: {}) that does not exist", host_id, svc_id); @@ -1312,7 +1305,7 @@ int anomalydetection::update_thresholds(const std::string& filename) { } if (found->second->get_service_type() != service_type::ANOMALY_DETECTION) { SPDLOG_LOGGER_ERROR( - log_v2::config(), + config_logger, "host_id: {}, service_id: {} is not an anomaly detection service", host_id, svc_id); continue; @@ -1329,7 +1322,7 @@ int anomalydetection::update_thresholds(const std::string& filename) { << "' whereas the configured metric name is '" << ad->get_metric_name() << "'"; SPDLOG_LOGGER_ERROR( - log_v2::config(), + config_logger, "Error: The thresholds file contains thresholds for the anomaly " "detection service (host_id: {}, service_id: {}) with " "metric_name='{}' whereas the configured metric name is '{}'", @@ -1341,7 +1334,7 @@ int anomalydetection::update_thresholds(const std::string& filename) { << ", service_id: " << ad->service_id() << ", metric: " << ad->get_metric_name() << ")"; SPDLOG_LOGGER_INFO( - log_v2::checks(), + checks_logger, "Filling thresholds in anomaly detection (host_id: {}, service_id: {}, " "metric: {})", ad->host_id(), ad->service_id(), ad->get_metric_name()); @@ -1387,13 +1380,13 @@ void anomalydetection::set_thresholds_no_lock( _thresholds.end(), timepoint, threshold_point(timepoint, sensitivity, threshold_obj)); } catch (const nlohmann::json::exception& e) { - SPDLOG_LOGGER_ERROR(log_v2::config(), "fail to parse predict:{} cause:{}", + SPDLOG_LOGGER_ERROR(config_logger, "fail to parse predict:{} cause:{}", threshold_obj.dump(), e.what()); } catch (const std::exception& e) { - SPDLOG_LOGGER_ERROR(log_v2::config(), "fail to parse predict:{} cause {}", + SPDLOG_LOGGER_ERROR(config_logger, "fail to parse predict:{} cause {}", threshold_obj.dump(), e.what()); } catch (...) { - SPDLOG_LOGGER_ERROR(log_v2::config(), "unknown exception {}", + SPDLOG_LOGGER_ERROR(config_logger, "unknown exception {}", threshold_obj.dump()); } } @@ -1401,7 +1394,7 @@ void anomalydetection::set_thresholds_no_lock( engine_logger(dbg_config, most) << "host_id=" << host_id() << " serv_id=" << service_id() << " Number of rows in memory: " << _thresholds.size(); - SPDLOG_LOGGER_DEBUG(log_v2::config(), + SPDLOG_LOGGER_DEBUG(config_logger, "host_id={} serv_id={} Number of rows in memory: {}", host_id(), service_id(), _thresholds.size()); _thresholds_file_viable = true; @@ -1409,7 +1402,7 @@ void anomalydetection::set_thresholds_no_lock( engine_logger(dbg_config, most) << "Nothing in memory " << _thresholds.size() << " for host_id=" << host_id() << " serv_id=" << service_id(); - SPDLOG_LOGGER_ERROR(log_v2::config(), + SPDLOG_LOGGER_ERROR(config_logger, "Nothing in memory {} for host_id={} servid={}", _thresholds.size(), host_id(), service_id()); _thresholds_file_viable = false; diff --git a/engine/src/broker/handle.cc b/engine/src/broker/handle.cc index aba7e42f7ee..bdcc8f0f592 100644 --- a/engine/src/broker/handle.cc +++ b/engine/src/broker/handle.cc @@ -1,26 +1,26 @@ /** -* Copyright 2011-2013,2016, 2021 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2013,2016, 2021-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include "com/centreon/engine/broker/handle.hh" #include "com/centreon/engine/common.hh" #include "com/centreon/engine/exceptions/error.hh" -#include "com/centreon/engine/log_v2.hh" +#include "com/centreon/engine/globals.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/nebmodules.hh" @@ -80,7 +80,7 @@ void handle::close() { engine_logger(log_info_message, basic) << "Cannot resolve symbole 'nebmodule_deinit' in module '" << _filename << "'."; - log_v2::process()->error( + process_logger->error( "Cannot resolve symbole 'nebmodule_deinit' in module '{}'.", _filename); } else @@ -207,7 +207,7 @@ void handle::open() { "returned an error"); } catch (std::exception const& e) { - log_v2::process()->error("fail to load broker module {}", e.what()); + process_logger->error("fail to load broker module {}", e.what()); close(); throw; } diff --git a/engine/src/broker/loader.cc b/engine/src/broker/loader.cc index 1e83db7271c..a16b499002f 100644 --- a/engine/src/broker/loader.cc +++ b/engine/src/broker/loader.cc @@ -1,26 +1,27 @@ /** -* Copyright 2011-2013 Merethis -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2013 Merethis + * Copyright 2017-2024 Centreon (https://www.centreon.com/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include "com/centreon/engine/broker/loader.hh" #include "com/centreon/engine/broker/handle.hh" #include "com/centreon/engine/exceptions/error.hh" -#include "com/centreon/engine/log_v2.hh" +#include "com/centreon/engine/globals.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/io/directory_entry.hh" #include "com/centreon/io/file_stream.hh" @@ -118,16 +119,16 @@ unsigned int loader::load_directory(std::string const& dir) { engine_logger(log_info_message, basic) << "Event broker module '" << f.file_name() << "' initialized successfully."; - log_v2::events()->info( - "Event broker module '{}' initialized successfully.", f.file_name()); + events_logger->info("Event broker module '{}' initialized successfully.", + f.file_name()); ++loaded; } catch (error const& e) { del_module(module); engine_logger(log_runtime_error, basic) << "Error: Could not load module '" << f.file_name() << "' -> " << e.what(); - log_v2::runtime()->error("Error: Could not load module '{}' -> {}", - f.file_name(), e.what()); + runtime_logger->error("Error: Could not load module '{}' -> {}", + f.file_name(), e.what()); } } return loaded; @@ -146,18 +147,12 @@ void loader::unload_modules() { } engine_logger(dbg_eventbroker, basic) << "Module '" << (*it)->get_filename() << "' unloaded successfully."; - log_v2::eventbroker()->trace("Module '{}' unloaded successfully.", - (*it)->get_filename()); + eventbroker_logger->trace("Module '{}' unloaded successfully.", + (*it)->get_filename()); } _modules.clear(); } -/************************************** - * * - * Private Methods * - * * - **************************************/ - /** * Default constructor. */ diff --git a/engine/src/checkable.cc b/engine/src/checkable.cc index 3d502a31ad1..d6ebaf973b7 100644 --- a/engine/src/checkable.cc +++ b/engine/src/checkable.cc @@ -1,5 +1,5 @@ /** - * Copyright 2011-2019,2022 Centreon + * Copyright 2011-2019,2022-2024 Centreon * * This file is part of Centreon Engine. * @@ -19,7 +19,7 @@ #include "com/centreon/engine/checkable.hh" #include "com/centreon/engine/exceptions/error.hh" -#include "com/centreon/engine/log_v2.hh" +#include "com/centreon/engine/globals.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/configuration/whitelist.hh" @@ -114,7 +114,7 @@ checkable::checkable(const std::string& name, oss << "Invalid freshness_threshold: value should be positive or 0"; } engine_logger(log_config_error, basic) << oss.str(); - log_v2::config()->error(oss.str()); + config_logger->error(oss.str()); throw engine_error() << "Could not register checkable '" << display_name << "'"; } diff --git a/engine/src/checks/checker.cc b/engine/src/checks/checker.cc index 52e43e62a3f..381df663ed1 100644 --- a/engine/src/checks/checker.cc +++ b/engine/src/checks/checker.cc @@ -1,6 +1,6 @@ /** * Copyright 1999-2010 Ethan Galstad - * Copyright 2011-2019 Centreon + * Copyright 2011-2024 Centreon * * This file is part of Centreon Engine. * @@ -20,8 +20,6 @@ #include "com/centreon/engine/checks/checker.hh" -#include "com/centreon/engine/log_v2.hh" - #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/configuration/whitelist.hh" #include "com/centreon/engine/exceptions/error.hh" @@ -86,10 +84,10 @@ void checker::clear() noexcept { */ void checker::reap() { engine_logger(dbg_functions, basic) << "checker::reap"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), "checker::reap()"); + SPDLOG_LOGGER_TRACE(functions_logger, "checker::reap()"); engine_logger(dbg_checks, basic) << "Starting to reap check results."; - SPDLOG_LOGGER_TRACE(log_v2::checks(), "Starting to reap check results."); + SPDLOG_LOGGER_TRACE(checks_logger, "Starting to reap check results."); // Time to start reaping. time_t reaper_start_time; @@ -128,7 +126,7 @@ void checker::reap() { ++reaped_checks; engine_logger(dbg_checks, basic) << "Found a check result (#" << reaped_checks << ") to handle..."; - SPDLOG_LOGGER_TRACE(log_v2::checks(), + SPDLOG_LOGGER_TRACE(checks_logger, "Found a check result (#{}) to handle...", reaped_checks); check_result::pointer result = _to_reap.front(); @@ -142,7 +140,7 @@ void checker::reap() { engine_logger(dbg_checks, more) << "Handling check result for service " << svc->host_id() << "/" << svc->service_id() << "..."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "Handling check result for service {}/{}...", svc->host_id(), svc->service_id()); svc->handle_async_check_result(*result); @@ -150,7 +148,7 @@ void checker::reap() { engine_logger(log_runtime_warning, basic) << "Check result queue errors for service " << svc->host_id() << "/" << svc->service_id() << " : " << e.what(); - SPDLOG_LOGGER_WARN(log_v2::runtime(), + SPDLOG_LOGGER_WARN(runtime_logger, "Check result queue errors for service {}/{} : {}", svc->host_id(), svc->service_id(), e.what()); } @@ -162,7 +160,7 @@ void checker::reap() { // Process the check result-> engine_logger(dbg_checks, more) << "Handling check result for host " << hst->host_id() << "..."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "Handling check result for host {}...", hst->host_id()); hst->handle_async_check_result_3x(*result); @@ -170,8 +168,8 @@ void checker::reap() { engine_logger(log_runtime_error, basic) << "Check result queue errors for " << "host " << hst->host_id() << " : " << e.what(); - log_v2::runtime()->error("Check result queue errors for host {} : {}", - hst->host_id(), e.what()); + runtime_logger->error("Check result queue errors for host {} : {}", + hst->host_id(), e.what()); } } @@ -184,7 +182,7 @@ void checker::reap() { << "Breaking out of check result reaper: " << "max reaper time exceeded"; SPDLOG_LOGGER_TRACE( - log_v2::checks(), + checks_logger, "Breaking out of check result reaper: max reaper time exceeded"); break; } @@ -194,7 +192,7 @@ void checker::reap() { engine_logger(dbg_checks, basic) << "Breaking out of check result reaper: signal encountered"; SPDLOG_LOGGER_TRACE( - log_v2::checks(), + checks_logger, "Breaking out of check result reaper: signal encountered"); break; } @@ -204,7 +202,7 @@ void checker::reap() { // Reaping finished. engine_logger(dbg_checks, basic) << "Finished reaping " << reaped_checks << " check results"; - SPDLOG_LOGGER_TRACE(log_v2::checks(), "Finished reaping {} check results", + SPDLOG_LOGGER_TRACE(checks_logger, "Finished reaping {} check results", reaped_checks); } @@ -226,7 +224,7 @@ void checker::run_sync(host* hst, << "checker::run: hst=" << hst << ", check_options=" << check_options << ", use_cached_result=" << use_cached_result << ", check_timestamp_horizon=" << check_timestamp_horizon; - SPDLOG_LOGGER_TRACE(log_v2::functions(), + SPDLOG_LOGGER_TRACE(functions_logger, "checker::run: hst={:p}, check_options={}" ", use_cached_result={}" ", check_timestamp_horizon={}", @@ -242,7 +240,7 @@ void checker::run_sync(host* hst, engine_logger(dbg_checks, basic) << "** Run sync check of host '" << hst->name() << "'..."; - SPDLOG_LOGGER_TRACE(log_v2::checks(), "** Run sync check of host '{}'...", + SPDLOG_LOGGER_TRACE(checks_logger, "** Run sync check of host '{}'...", hst->name()); // Check if the host is viable now. @@ -250,8 +248,7 @@ void checker::run_sync(host* hst, if (check_result_code) *check_result_code = hst->get_current_state(); engine_logger(dbg_checks, basic) << "Host check is not viable at this time"; - SPDLOG_LOGGER_TRACE(log_v2::checks(), - "Host check is not viable at this time"); + SPDLOG_LOGGER_TRACE(checks_logger, "Host check is not viable at this time"); return; } @@ -270,7 +267,7 @@ void checker::run_sync(host* hst, *check_result_code = hst->get_current_state(); engine_logger(dbg_checks, more) << "* Using cached host state: " << hst->get_current_state(); - SPDLOG_LOGGER_DEBUG(log_v2::checks(), "* Using cached host state: {}", + SPDLOG_LOGGER_DEBUG(checks_logger, "* Using cached host state: {}", static_cast(hst->get_current_state())); // Update statistics. @@ -283,7 +280,7 @@ void checker::run_sync(host* hst, // Checking starts. engine_logger(dbg_checks, more) << "* Running actual host check: old state=" << hst->get_current_state(); - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "* Running actual host check: old state={}", static_cast(hst->get_current_state())); @@ -334,7 +331,7 @@ void checker::run_sync(host* hst, // Synchronous check is done. engine_logger(dbg_checks, more) << "* Sync host check done: new state=" << hst->get_current_state(); - SPDLOG_LOGGER_DEBUG(log_v2::checks(), "* Sync host check done: new state={}", + SPDLOG_LOGGER_DEBUG(checks_logger, "* Sync host check done: new state={}", static_cast(hst->get_current_state())); // Send event broker. @@ -372,7 +369,7 @@ checker::~checker() noexcept { void checker::finished(commands::result const& res) noexcept { // Debug message. engine_logger(dbg_functions, basic) << "checker::finished: res=" << &res; - SPDLOG_LOGGER_TRACE(log_v2::functions(), "checker::finished: res={:p}", + SPDLOG_LOGGER_TRACE(functions_logger, "checker::finished: res={:p}", (void*)&res); std::unique_lock lock(_mut_reap); @@ -380,7 +377,7 @@ void checker::finished(commands::result const& res) noexcept { if (it_id == _waiting_check_result.end()) { engine_logger(log_runtime_warning, basic) << "command ID '" << res.command_id << "' not found"; - SPDLOG_LOGGER_WARN(log_v2::runtime(), "command ID '{}' not found", + SPDLOG_LOGGER_WARN(runtime_logger, "command ID '{}' not found", res.command_id); return; } @@ -452,7 +449,7 @@ void checker::wait_completion(e_completion_filter filter) { */ com::centreon::engine::host::host_state checker::_execute_sync(host* hst) { engine_logger(dbg_functions, basic) << "checker::_execute_sync: hst=" << hst; - SPDLOG_LOGGER_TRACE(log_v2::functions(), "checker::_execute_sync: hst={:p}", + SPDLOG_LOGGER_TRACE(functions_logger, "checker::_execute_sync: hst={:p}", (void*)hst); // Preamble. @@ -464,8 +461,8 @@ com::centreon::engine::host::host_state checker::_execute_sync(host* hst) { engine_logger(dbg_checks, basic) << "** Executing sync check of host '" << hst->name() << "'..."; - SPDLOG_LOGGER_TRACE(log_v2::checks(), - "** Executing sync check of host '{}'...", hst->name()); + SPDLOG_LOGGER_TRACE(checks_logger, "** Executing sync check of host '{}'...", + hst->name()); // Send broker event. timeval start_time{0, 0}; @@ -504,12 +501,12 @@ com::centreon::engine::host::host_state checker::_execute_sync(host* hst) { engine_logger(dbg_commands, more) << "Raw host check command: " << hst->get_check_command_ptr()->get_command_line(); - SPDLOG_LOGGER_TRACE(log_v2::commands(), "Raw host check command: {}", + SPDLOG_LOGGER_TRACE(commands_logger, "Raw host check command: {}", hst->get_check_command_ptr()->get_command_line()); engine_logger(dbg_commands, more) << "Processed host check command: " << processed_cmd; - SPDLOG_LOGGER_TRACE(log_v2::commands(), "Processed host check command: {}", + SPDLOG_LOGGER_TRACE(commands_logger, "Processed host check command: {}", processed_cmd); // Cleanup. @@ -539,12 +536,12 @@ com::centreon::engine::host::host_state checker::_execute_sync(host* hst) { }; if (!hst->is_whitelist_allowed(processed_cmd)) { - SPDLOG_LOGGER_ERROR(log_v2::commands(), + SPDLOG_LOGGER_ERROR(commands_logger, "host {}: this command cannot be executed because of " "security restrictions on the poller. A whitelist has " "been defined, and it does not include this command.", hst->name()); - SPDLOG_LOGGER_DEBUG(log_v2::commands(), + SPDLOG_LOGGER_DEBUG(commands_logger, "host {}: command not allowed by whitelist {}", hst->name(), processed_cmd); run_failure(configuration::command_blacklist_output); @@ -559,7 +556,7 @@ com::centreon::engine::host::host_state checker::_execute_sync(host* hst) { << "Error: Synchronous host check command execution failed: " << e.what(); SPDLOG_LOGGER_WARN( - log_v2::runtime(), + runtime_logger, "Error: Synchronous host check command execution failed: {}", e.what()); } @@ -594,7 +591,7 @@ com::centreon::engine::host::host_state checker::_execute_sync(host* hst) { << hst->name() << "' timed out after " << config->host_check_timeout() << " seconds"; SPDLOG_LOGGER_WARN( - log_v2::runtime(), + runtime_logger, "Warning: Host check command '{}' for host '{}' timed out after {} " "seconds", processed_cmd, hst->name(), config->host_check_timeout()); @@ -650,7 +647,7 @@ com::centreon::engine::host::host_state checker::_execute_sync(host* hst) { // Termination. engine_logger(dbg_checks, basic) << "** Sync host check done: state=" << return_result; - SPDLOG_LOGGER_TRACE(log_v2::checks(), "** Sync host check done: state={}", + SPDLOG_LOGGER_TRACE(checks_logger, "** Sync host check done: state={}", static_cast(return_result)); return return_result; } diff --git a/engine/src/command_manager.cc b/engine/src/command_manager.cc index 95ecaac777b..1718b63442e 100644 --- a/engine/src/command_manager.cc +++ b/engine/src/command_manager.cc @@ -27,7 +27,6 @@ #include "com/centreon/engine/comment.hh" #include "com/centreon/engine/downtimes/downtime_manager.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" using namespace com::centreon::engine; @@ -112,7 +111,7 @@ int command_manager::process_passive_service_check( << "Warning: Passive check result was received for service '" << svc_description << "' on host '" << host_name << "', but the host could not be found!"; - log_v2::runtime()->warn( + runtime_logger->warn( "Warning: Passive check result was received for service '{}' on host " "'{}', but the host could not be found!", svc_description, host_name); @@ -127,7 +126,7 @@ int command_manager::process_passive_service_check( << "Warning: Passive check result was received for service '" << svc_description << "' on host '" << host_name << "', but the service could not be found!"; - log_v2::runtime()->warn( + runtime_logger->warn( "Warning: Passive check result was received for service '{}' on host " "'{}', but the service could not be found!", svc_description, host_name); @@ -196,7 +195,7 @@ int command_manager::process_passive_host_check(time_t check_time, engine_logger(log_runtime_warning, basic) << "Warning: Passive check result was received for host '" << host_name << "', but the host could not be found!"; - log_v2::runtime()->warn( + runtime_logger->warn( "Warning: Passive check result was received for host '{}', but the " "host could not be found!", host_name); diff --git a/engine/src/commands/command.cc b/engine/src/commands/command.cc index 0a8949f4c31..32ed393ead5 100644 --- a/engine/src/commands/command.cc +++ b/engine/src/commands/command.cc @@ -22,7 +22,6 @@ #include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/macros/grab.hh" @@ -193,8 +192,8 @@ bool commands::command::gest_call_interval( checks::checker::instance().add_check_result(command_id, to_push_to_checker); if (_listener && result_to_reuse) { _listener->finished(*result_to_reuse); - SPDLOG_LOGGER_TRACE(log_v2::commands(), - "command::run: id={} , reuse result", command_id); + SPDLOG_LOGGER_TRACE(commands_logger, "command::run: id={} , reuse result", + command_id); return false; } return true; @@ -217,4 +216,4 @@ std::ostream& operator<<(std::ostream& s, const commands::command& cmd) { return s; } -} // namespace com::centreon::engine::commands \ No newline at end of file +} // namespace com::centreon::engine::commands diff --git a/engine/src/commands/commands.cc b/engine/src/commands/commands.cc index 15d87ba58f1..ec6e7d53d1a 100644 --- a/engine/src/commands/commands.cc +++ b/engine/src/commands/commands.cc @@ -1,22 +1,22 @@ /** -* Copyright 1999-2008 Ethan Galstad -* Copyright 2011-2013,2015-2022 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 1999-2008 Ethan Galstad + * Copyright 2011-2013,2015-2022 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/commands/commands.hh" #include "com/centreon/engine/commands/processing.hh" @@ -34,7 +34,6 @@ #include "com/centreon/engine/events/loop.hh" #include "com/centreon/engine/flapping.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/statusdata.hh" #include "com/centreon/engine/string.hh" @@ -54,7 +53,7 @@ using namespace com::centreon::engine::logging; int check_for_external_commands() { engine_logger(dbg_functions, basic) << "check_for_external_commands()"; - log_v2::functions()->trace("check_for_external_commands()"); + functions_logger->trace("check_for_external_commands()"); /* bail out if we shouldn't be checking for external commands */ if (!config->check_external_commands()) @@ -98,7 +97,7 @@ int process_external_commands_from_file(char const* file, int delete_file) { engine_logger(dbg_functions, basic) << "process_external_commands_from_file()"; - log_v2::functions()->trace("process_external_commands_from_file()"); + functions_logger->trace("process_external_commands_from_file()"); if (!file) return ERROR; @@ -107,7 +106,7 @@ int process_external_commands_from_file(char const* file, int delete_file) { << "Processing commands from file '" << file << "'. File will " << (delete_file ? "be" : "NOT be") << " deleted after processing."; - log_v2::external_command()->debug( + external_command_logger->debug( "Processing commands from file '{}'. File will {} deleted after " "processing.", file, delete_file ? "be" : "NOT be"); @@ -118,7 +117,7 @@ int process_external_commands_from_file(char const* file, int delete_file) { engine_logger(log_info_message, basic) << "Error: Cannot open file '" << file << "' to process external commands!"; - log_v2::config()->info( + config_logger->info( "Error: Cannot open file '{}' to process external commands!", file); return ERROR; } @@ -203,7 +202,7 @@ int cmd_add_comment(int cmd, time_t entry_time, char* args) { return ERROR; if (!absl::SimpleAtob(temp_ptr, &persistent)) { - log_v2::external_command()->error( + external_command_logger->error( "Error: could not {} : persistent '{}' must be 1 or 0", command_name, temp_ptr); return ERROR; @@ -224,9 +223,8 @@ int cmd_add_comment(int cmd, time_t entry_time, char* args) { comment_data, persistent, comment::external, false, (time_t)0); uint64_t comment_id = com->get_comment_id(); comment::comments.insert({comment_id, com}); - log_v2::external_command()->trace("{}, comment_id: {}, data: {}", - command_name, comment_id, - com->get_comment_data()); + external_command_logger->trace("{}, comment_id: {}, data: {}", command_name, + comment_id, com->get_comment_data()); return OK; } @@ -235,7 +233,7 @@ int cmd_delete_comment(int cmd [[maybe_unused]], char* args) { uint64_t comment_id{0}; /* get the comment id we should delete */ if (!absl::SimpleAtoi(args, &comment_id)) { - log_v2::external_command()->error( + external_command_logger->error( "Error: could not delete comment : comment_id '{}' must be an " "integer >= 0", args); @@ -326,7 +324,7 @@ int cmd_delay_notification(int cmd, char* args) { if ((temp_ptr = my_strtok(nullptr, "\n")) == nullptr) return ERROR; if (!absl::SimpleAtoi(temp_ptr, &delay_time)) { - log_v2::external_command()->error( + external_command_logger->error( "Error: could not delay notification : delay_time '{}' must be " "an integer", temp_ptr); @@ -381,7 +379,7 @@ int cmd_schedule_check(int cmd, char* args) { if ((temp_ptr = my_strtok(nullptr, "\n")) == nullptr) return ERROR; if (!absl::SimpleAtoi(temp_ptr, &delay_time)) { - log_v2::external_command()->error( + external_command_logger->error( "Error: could not schedule check : delay_time '{}' must be " "an integer", temp_ptr); @@ -442,7 +440,7 @@ int cmd_schedule_host_service_checks(int cmd, char* args, int force) { if ((temp_ptr = my_strtok(nullptr, "\n")) == nullptr) return ERROR; if (!absl::SimpleAtoi(temp_ptr, &delay_time)) { - log_v2::external_command()->error( + external_command_logger->error( "Error: could not schedule host service checks : delay_time '{}' " "must be an integer", temp_ptr); @@ -471,7 +469,7 @@ void cmd_signal_process(int cmd, char* args) { if ((temp_ptr = my_strtok(args, "\n")) == nullptr) scheduled_time = 0L; else if (!absl::SimpleAtoi(temp_ptr, &scheduled_time)) { - log_v2::external_command()->error( + external_command_logger->error( "Error: could not signal process : scheduled_time '{}' " "must be an integer", temp_ptr); @@ -539,7 +537,7 @@ int cmd_process_service_check_result(int cmd [[maybe_unused]], << "Warning: Passive check result was received for service '" << svc_description << "' on host '" << real_host_name << "', but the host could not be found!"; - log_v2::runtime()->warn( + runtime_logger->warn( "Warning: Passive check result was received for service '{}' on host " "'{}', but the host could not be found!", fmt::string_view(svc_description.data(), svc_description.size()), @@ -555,7 +553,7 @@ int cmd_process_service_check_result(int cmd [[maybe_unused]], << "Warning: Passive check result was received for service '" << svc_description << "' on host '" << real_host_name << "', but the service could not be found!"; - log_v2::runtime()->warn( + runtime_logger->warn( "Warning: Passive check result was received for service '{}' on " "host " "'{}', but the service could not be found!", @@ -640,7 +638,7 @@ int process_passive_service_check(time_t check_time, << "Warning: Passive check result was received for service '" << svc_description << "' on host '" << host_name << "', but the host could not be found!"; - log_v2::runtime()->warn( + runtime_logger->warn( "Warning: Passive check result was received for service '{}' on " "host " "'{}', but the host could not be found!", @@ -656,7 +654,7 @@ int process_passive_service_check(time_t check_time, << "Warning: Passive check result was received for service '" << svc_description << "' on host '" << host_name << "', but the service could not be found!"; - log_v2::runtime()->warn( + runtime_logger->warn( "Warning: Passive check result was received for service '{}' on " "host " "'{}', but the service could not be found!", @@ -772,7 +770,7 @@ int process_passive_host_check(time_t check_time, engine_logger(log_runtime_warning, basic) << "Warning: Passive check result was received for host '" << host_name << "', but the host could not be found!"; - log_v2::runtime()->warn( + runtime_logger->warn( "Warning: Passive check result was received for host '{}', but the " "host could not be found!", host_name); @@ -844,7 +842,7 @@ int cmd_acknowledge_problem(int cmd, char* args) { /* get the type */ if (!arg.extract(';', type)) return ERROR; - log_v2::external_command()->trace("New acknowledgement with type {}", type); + external_command_logger->trace("New acknowledgement with type {}", type); /* get the notification option */ int ival; @@ -980,7 +978,7 @@ int cmd_schedule_downtime(int cmd, time_t entry_time, char* args) { if (ait == a.end()) return ERROR; if (!absl::SimpleAtoi(*ait, &start_time)) { - log_v2::external_command()->error( + external_command_logger->error( "Error: could not schedule downtime : start_time '{}' must be " "an integer", *ait); @@ -992,7 +990,7 @@ int cmd_schedule_downtime(int cmd, time_t entry_time, char* args) { if (ait == a.end()) return ERROR; if (!absl::SimpleAtoi(*ait, &end_time)) { - log_v2::external_command()->error( + external_command_logger->error( "Error: could not schedule downtime : end_time '{}' must be " "an integer", *ait); @@ -1004,7 +1002,7 @@ int cmd_schedule_downtime(int cmd, time_t entry_time, char* args) { if (ait == a.end()) return ERROR; if (!absl::SimpleAtob(*ait, &fixed)) { - log_v2::external_command()->error( + external_command_logger->error( "Error: could not schedule downtime : fixed '{}' must be 1 or 0", *ait); return ERROR; } @@ -1014,7 +1012,7 @@ int cmd_schedule_downtime(int cmd, time_t entry_time, char* args) { if (ait == a.end()) return ERROR; if (!absl::SimpleAtoi(*ait, &triggered_by)) { - log_v2::external_command()->error( + external_command_logger->error( "Error: could not schedule downtime : triggered_by '{}' must be an " "integer >= 0", *ait); @@ -1027,7 +1025,7 @@ int cmd_schedule_downtime(int cmd, time_t entry_time, char* args) { return ERROR; if (!ait->empty()) { if (!absl::SimpleAtoi(*ait, &duration)) { - log_v2::external_command()->error( + external_command_logger->error( "Error: could not schedule downtime : duration '{}' must be an " "integer " ">= 0", @@ -1055,7 +1053,7 @@ int cmd_schedule_downtime(int cmd, time_t entry_time, char* args) { ** duration>0 is needed. */ if (!fixed && !duration) { - SPDLOG_LOGGER_ERROR(log_v2::external_command(), + SPDLOG_LOGGER_ERROR(external_command_logger, "no duration defined for a fixed downtime"); return ERROR; } @@ -1198,7 +1196,7 @@ int cmd_delete_downtime(int cmd, char* args) { return ERROR; if (!absl::SimpleAtoi(temp_ptr, &downtime_id)) { - log_v2::external_command()->error( + external_command_logger->error( "Error: could not delete downtime : downtime_id '{}' must be an " "integer >= 0", temp_ptr); @@ -1218,7 +1216,7 @@ int cmd_delete_downtime(int cmd, char* args) { * @param[in] args Command arguments. */ int cmd_delete_downtime_full(int cmd, char* args) { - log_v2::functions()->trace("cmd_delete_downtime_full() args = {}", args); + functions_logger->trace("cmd_delete_downtime_full() args = {}", args); downtime_finder::criteria_set criterias; auto a{absl::StrSplit(args, ';')}; diff --git a/engine/src/commands/connector.cc b/engine/src/commands/connector.cc index caefca2889c..a017fe32ecb 100644 --- a/engine/src/commands/connector.cc +++ b/engine/src/commands/connector.cc @@ -20,7 +20,6 @@ #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/my_lock.hh" #include "com/centreon/engine/version.hh" @@ -79,7 +78,7 @@ connector::connector(const std::string& connector_name, if (config->enable_environment_macros()) { engine_logger(log_runtime_warning, basic) << "Warning: Connector does not enable environment macros"; - log_v2::runtime()->warn( + runtime_logger->warn( "Warning: Connector does not enable environment macros"); } } @@ -94,8 +93,8 @@ connector::~connector() noexcept { } catch (const std::exception& e) { engine_logger(log_runtime_error, basic) << "Error: could not stop connector properly: " << e.what(); - log_v2::runtime()->error("Error: could not stop connector properly: {}", - e.what()); + runtime_logger->error("Error: could not stop connector properly: {}", + e.what()); } // Wait restart thread. @@ -125,9 +124,8 @@ uint64_t connector::run(const std::string& processed_cmd, engine_logger(dbg_commands, basic) << "connector::run: connector='" << _name << "', cmd='" << processed_cmd << "', timeout=" << timeout; - log_v2::commands()->trace( - "connector::run: connector='{}', cmd='{}', timeout={}", _name, - processed_cmd, timeout); + commands_logger->trace("connector::run: connector='{}', cmd='{}', timeout={}", + _name, processed_cmd, timeout); // Set query informations. uint64_t command_id(get_uniq_id()); @@ -143,7 +141,7 @@ uint64_t connector::run(const std::string& processed_cmd, info->waiting_result = false; engine_logger(dbg_commands, basic) << "connector::run: id=" << command_id; - log_v2::commands()->trace("connector::run: id={}", command_id); + commands_logger->trace("connector::run: id={}", command_id); try { { UNIQUE_LOCK(lock, _lock); @@ -167,13 +165,13 @@ uint64_t connector::run(const std::string& processed_cmd, engine_logger(dbg_commands, basic) << "connector::run: start command success: id=" << command_id; - log_v2::commands()->trace("connector::run: start command success: id={}", - command_id); + commands_logger->trace("connector::run: start command success: id={}", + command_id); } catch (...) { engine_logger(dbg_commands, basic) << "connector::run: start command failed: id=" << command_id; - log_v2::commands()->trace("connector::run: start command failed: id={}", - command_id); + commands_logger->trace("connector::run: start command failed: id={}", + command_id); throw; } return command_id; @@ -196,9 +194,8 @@ void connector::run(const std::string& processed_cmd, engine_logger(dbg_commands, basic) << "connector::run: connector='" << _name << "', cmd='" << processed_cmd << "', timeout=" << timeout; - log_v2::commands()->trace( - "connector::run: connector='{}', cmd='{}', timeout={}", _name, - processed_cmd, timeout); + commands_logger->trace("connector::run: connector='{}', cmd='{}', timeout={}", + _name, processed_cmd, timeout); // Set query informations. uint64_t command_id(get_uniq_id()); @@ -209,7 +206,7 @@ void connector::run(const std::string& processed_cmd, info->waiting_result = true; engine_logger(dbg_commands, basic) << "connector::run: id=" << command_id; - log_v2::commands()->trace("connector::run: id={}", command_id); + commands_logger->trace("connector::run: id={}", command_id); try { { @@ -233,13 +230,13 @@ void connector::run(const std::string& processed_cmd, engine_logger(dbg_commands, basic) << "connector::run: start command success: id=" << command_id; - log_v2::commands()->trace("connector::run: start command success: id={}", - command_id); + commands_logger->trace("connector::run: start command success: id={}", + command_id); } catch (...) { engine_logger(dbg_commands, basic) << "connector::run: start command failed: id=" << command_id; - log_v2::commands()->trace("connector::run: start command failed: id={}", - command_id); + commands_logger->trace("connector::run: start command failed: id={}", + command_id); throw; } @@ -293,8 +290,8 @@ void connector::data_is_available(process& p) noexcept { try { engine_logger(dbg_commands, basic) << "connector::data_is_available: process=" << (void*)&p; - log_v2::commands()->trace("connector::data_is_available: process={}", - (void*)&p); + commands_logger->trace("connector::data_is_available: process={}", + (void*)&p); // Read process output. std::string data; @@ -321,8 +318,8 @@ void connector::data_is_available(process& p) noexcept { engine_logger(dbg_commands, basic) << "connector::data_is_available: responses.size=" << responses.size(); - log_v2::commands()->trace( - "connector::data_is_available: responses.size={}", responses.size()); + commands_logger->trace("connector::data_is_available: responses.size={}", + responses.size()); } // Parse queries responses. @@ -332,8 +329,7 @@ void connector::data_is_available(process& p) noexcept { uint32_t id(strtol(data, &endptr, 10)); engine_logger(dbg_commands, basic) << "connector::data_is_available: request id=" << id; - log_v2::commands()->trace("connector::data_is_available: request id={}", - id); + commands_logger->trace("connector::data_is_available: request id={}", id); // Invalid query. if (data == endptr || id >= tab_recv_query.size() || @@ -343,7 +339,7 @@ void connector::data_is_available(process& p) noexcept { << "' " "received bad request ID: " << id; - log_v2::runtime()->warn( + runtime_logger->warn( "Warning: Connector '{}' received bad request ID: {}", _name, id); // Valid query, so execute it. } else @@ -352,8 +348,7 @@ void connector::data_is_available(process& p) noexcept { } catch (std::exception const& e) { engine_logger(log_runtime_warning, basic) << "Warning: Connector '" << _name << "' error: " << e.what(); - log_v2::runtime()->warn("Warning: Connector '{}' error: {}", _name, - e.what()); + runtime_logger->warn("Warning: Connector '{}' error: {}", _name, e.what()); } } @@ -375,7 +370,7 @@ void connector::data_is_available_err(process& p) noexcept { void connector::finished(process& p) noexcept { try { engine_logger(dbg_commands, basic) << "connector::finished: process=" << &p; - log_v2::commands()->trace("connector::finished: process={}", (void*)&p); + commands_logger->trace("connector::finished: process={}", (void*)&p); UNIQUE_LOCK(lock, _lock); _is_running = false; @@ -395,7 +390,7 @@ void connector::finished(process& p) noexcept { engine_logger(log_runtime_error, basic) << "Error: Connector '" << _name << "' termination routine failed: " << e.what(); - log_v2::runtime()->error( + runtime_logger->error( "Error: Connector '{}' termination routine failed: {}", _name, e.what()); } @@ -413,8 +408,8 @@ void connector::_connector_close() { engine_logger(dbg_commands, basic) << "connector::_connector_close: process=" << &_process; - log_v2::commands()->trace("connector::_connector_close: process={:p}", - (void*)&_process); + commands_logger->trace("connector::_connector_close: process={:p}", + (void*)&_process); // Set variable to dosn't restart connector. { LOCK_GUARD(lck, _thread_m); @@ -438,8 +433,8 @@ void connector::_connector_close() { if (is_timeout) { engine_logger(log_runtime_warning, basic) << "Warning: Cannot close connector '" << _name << "': Timeout"; - log_v2::runtime()->warn("Warning: Cannot close connector '{}': Timeout", - _name); + runtime_logger->warn("Warning: Cannot close connector '{}': Timeout", + _name); } } UNLOCK(lock); @@ -454,8 +449,8 @@ void connector::_connector_close() { void connector::_connector_start() { engine_logger(dbg_commands, basic) << "connector::_connector_start: process=" << &_process; - log_v2::commands()->trace("connector::_connector_start: process={:p}", - (void*)&_process); + commands_logger->trace("connector::_connector_start: process={:p}", + (void*)&_process); { LOCK_GUARD(lock, _lock); @@ -496,14 +491,14 @@ void connector::_connector_start() { engine_logger(log_info_message, basic) << "Connector '" << _name << "' has started"; - log_v2::runtime()->info("Connector '{}' has started", _name); + runtime_logger->info("Connector '{}' has started", _name); { LOCK_GUARD(lock, _lock); engine_logger(dbg_commands, basic) << "connector::_connector_start: resend queries: queries.size=" << _queries.size(); - log_v2::commands()->trace( + commands_logger->trace( "connector::_connector_start: resend queries: queries.size={}", _queries.size()); // Resend commands. @@ -536,7 +531,7 @@ std::string connector::_query_ending() noexcept { void connector::_recv_query_error(char const* data) { try { engine_logger(dbg_commands, basic) << "connector::_recv_query_error"; - log_v2::commands()->trace("connector::_recv_query_error"); + commands_logger->trace("connector::_recv_query_error"); char* endptr(nullptr); int code(strtol(data, &endptr, 10)); if (data == endptr) @@ -549,25 +544,25 @@ void connector::_recv_query_error(char const* data) { case 0: engine_logger(log_info_message, basic) << "Info: Connector '" << _name << "': " << message; - log_v2::runtime()->info("Info: Connector '{}': {}", _name, message); + runtime_logger->info("Info: Connector '{}': {}", _name, message); break; // Warning message. case 1: engine_logger(log_runtime_warning, basic) << "Warning: Connector '" << _name << "': " << message; - log_v2::runtime()->warn("Warning: Connector '{}': {}", _name, message); + runtime_logger->warn("Warning: Connector '{}': {}", _name, message); break; // Error message. case 2: engine_logger(log_runtime_error, basic) << "Error: Connector '" << _name << "': " << message; - log_v2::runtime()->error("Error: Connector '{}': {}", _name, message); + runtime_logger->error("Error: Connector '{}': {}", _name, message); break; } } catch (std::exception const& e) { engine_logger(log_runtime_warning, basic) << "Warning: Connector '" << _name << "': " << e.what(); - log_v2::runtime()->warn("Warning: Connector '{}': {}", _name, e.what()); + runtime_logger->warn("Warning: Connector '{}': {}", _name, e.what()); } } @@ -579,7 +574,7 @@ void connector::_recv_query_error(char const* data) { void connector::_recv_query_execute(char const* data) { try { engine_logger(dbg_commands, basic) << "connector::_recv_query_execute"; - log_v2::commands()->trace("connector::_recv_query_execute"); + commands_logger->trace("connector::_recv_query_execute"); // Get query informations. char* endptr(nullptr); uint64_t command_id(strtol(data, &endptr, 10)); @@ -598,8 +593,7 @@ void connector::_recv_query_execute(char const* data) { engine_logger(dbg_commands, basic) << "connector::_recv_query_execute: id=" << command_id; - log_v2::commands()->trace("connector::_recv_query_execute: id={}", - command_id); + commands_logger->trace("connector::_recv_query_execute: id={}", command_id); std::shared_ptr info; { LOCK_GUARD(lock, _lock); @@ -612,7 +606,7 @@ void connector::_recv_query_execute(char const* data) { << "recv query failed: command_id(" << command_id << ") " "not found into queries"; - log_v2::commands()->trace( + commands_logger->trace( "recv query failed: command_id({}) not found into queries", command_id); return; @@ -665,7 +659,7 @@ void connector::_recv_query_execute(char const* data) { << ", " "output='" << res.output << "'"; - log_v2::commands()->trace( + commands_logger->trace( "connector::_recv_query_execute: " "id={}, {}", command_id, res); @@ -685,7 +679,7 @@ void connector::_recv_query_execute(char const* data) { } catch (std::exception const& e) { engine_logger(log_runtime_warning, basic) << "Warning: Connector '" << _name << "': " << e.what(); - log_v2::runtime()->warn("Warning: Connector '{}': {}", _name, e.what()); + runtime_logger->warn("Warning: Connector '{}': {}", _name, e.what()); } } @@ -697,7 +691,7 @@ void connector::_recv_query_execute(char const* data) { void connector::_recv_query_quit(char const* data) { (void)data; engine_logger(dbg_commands, basic) << "connector::_recv_query_quit"; - log_v2::commands()->trace("connector::_recv_query_quit"); + commands_logger->trace("connector::_recv_query_quit"); LOCK_GUARD(lock, _lock); _query_quit_ok = true; _cv_query.notify_all(); @@ -710,7 +704,7 @@ void connector::_recv_query_quit(char const* data) { */ void connector::_recv_query_version(char const* data) { engine_logger(dbg_commands, basic) << "connector::_recv_query_version"; - log_v2::commands()->trace("connector::_recv_query_version"); + commands_logger->trace("connector::_recv_query_version"); bool version_ok(false); try { // Parse query version response to get major and minor @@ -728,7 +722,7 @@ void connector::_recv_query_version(char const* data) { << "connector::_recv_query_version: " "major=" << version[0] << ", minor=" << version[1]; - log_v2::commands()->trace( + commands_logger->trace( "connector::_recv_query_version: " "major={}, minor={}", version[0], version[1]); @@ -740,7 +734,7 @@ void connector::_recv_query_version(char const* data) { } catch (std::exception const& e) { engine_logger(log_runtime_warning, basic) << "Warning: Connector '" << _name << "': " << e.what(); - log_v2::runtime()->warn("Warning: Connector '{}': {}", _name, e.what()); + runtime_logger->warn("Warning: Connector '{}': {}", _name, e.what()); } LOCK_GUARD(lock, _lock); @@ -773,7 +767,7 @@ void connector::_send_query_execute(const std::string& cmdline, << ", " "timeout=" << timeout; - log_v2::commands()->trace( + commands_logger->trace( "connector::_send_query_execute: " "id={}, " "cmd='{}', " @@ -792,7 +786,7 @@ void connector::_send_query_execute(const std::string& cmdline, */ void connector::_send_query_quit() { engine_logger(dbg_commands, basic) << "connector::_send_query_quit"; - log_v2::commands()->trace("connector::_send_query_quit"); + commands_logger->trace("connector::_send_query_quit"); std::string query("4\0", 2); _process.write(query + _query_ending()); } @@ -802,7 +796,7 @@ void connector::_send_query_quit() { */ void connector::_send_query_version() { engine_logger(dbg_commands, basic) << "connector::_send_query_version"; - log_v2::commands()->trace("connector::_send_query_version"); + commands_logger->trace("connector::_send_query_version"); std::string query("0\0", 2); query.append(_query_ending()); _process.write(query); @@ -849,7 +843,7 @@ void connector::_run_restart() { } catch (std::exception const& e) { engine_logger(log_runtime_warning, basic) << "Warning: Connector '" << _name << "': " << e.what(); - log_v2::runtime()->warn("Warning: Connector '{}': {}", _name, e.what()); + runtime_logger->warn("Warning: Connector '{}': {}", _name, e.what()); std::unordered_map > tmp_queries; { @@ -893,7 +887,7 @@ void connector::_run_restart() { << ", " "output='" << res.output << "'"; - log_v2::commands()->trace( + commands_logger->trace( "connector::_recv_query_execute: " "id={}, " "start_time={}, " diff --git a/engine/src/commands/processing.cc b/engine/src/commands/processing.cc index 8a8d5c3206d..173940589e0 100644 --- a/engine/src/commands/processing.cc +++ b/engine/src/commands/processing.cc @@ -1,28 +1,27 @@ /** -* Copyright 2011-2013,2015-2016 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2013,2015-2016 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/commands/processing.hh" #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/commands/commands.hh" #include "com/centreon/engine/flapping.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/retention/applier/state.hh" #include "com/centreon/engine/retention/dump.hh" @@ -573,7 +572,7 @@ void processing::_redirector_host(int id, time_t entry_time, char* args) { hst = it->second.get(); if (!hst) { - SPDLOG_LOGGER_ERROR(log_v2::external_command(), "unknown host: {}", name); + SPDLOG_LOGGER_ERROR(external_command_logger, "unknown host: {}", name); return; } (*fptr)(hst); @@ -592,7 +591,7 @@ void processing::_redirector_host(int id, time_t entry_time, char* args) { hst = it->second.get(); if (!hst) { - SPDLOG_LOGGER_ERROR(log_v2::external_command(), "unknown host: {}", name); + SPDLOG_LOGGER_ERROR(external_command_logger, "unknown host: {}", name); return; } (*fptr)(hst, args + name.length() + 1); @@ -610,7 +609,7 @@ void processing::_redirector_hostgroup(int id, time_t entry_time, char* args) { if (it != hostgroup::hostgroups.end()) group = it->second.get(); if (!group) { - SPDLOG_LOGGER_ERROR(log_v2::external_command(), "unknown group: {}", + SPDLOG_LOGGER_ERROR(external_command_logger, "unknown group: {}", group_name); return; } @@ -634,7 +633,7 @@ void processing::_redirector_service(int id, time_t entry_time, char* args) { service::services.find({name, description})); if (found == service::services.end() || !found->second) { - SPDLOG_LOGGER_ERROR(log_v2::external_command(), "unknown service: {}@{}", + SPDLOG_LOGGER_ERROR(external_command_logger, "unknown service: {}@{}", description, name); return; } @@ -652,7 +651,7 @@ void processing::_redirector_service(int id, time_t entry_time, char* args) { service::services.find({name, description})}; if (found == service::services.end() || !found->second) { - SPDLOG_LOGGER_ERROR(log_v2::external_command(), "unknown service: {}@{}", + SPDLOG_LOGGER_ERROR(external_command_logger, "unknown service: {}@{}", description, name); return; } @@ -670,7 +669,7 @@ void processing::_redirector_servicegroup(int id, servicegroup_map::const_iterator sg_it{ servicegroup::servicegroups.find(group_name)}; if (sg_it == servicegroup::servicegroups.end() || !sg_it->second) { - SPDLOG_LOGGER_ERROR(log_v2::external_command(), "unknown service group: {}", + SPDLOG_LOGGER_ERROR(external_command_logger, "unknown service group: {}", group_name); return; } @@ -693,7 +692,7 @@ void processing::_redirector_servicegroup(int id, servicegroup_map::const_iterator sg_it{ servicegroup::servicegroups.find(group_name)}; if (sg_it == servicegroup::servicegroups.end() || !sg_it->second) { - SPDLOG_LOGGER_ERROR(log_v2::external_command(), "unknown service group: {}", + SPDLOG_LOGGER_ERROR(external_command_logger, "unknown service group: {}", group_name); return; } @@ -722,8 +721,7 @@ void processing::_redirector_contact(int id, time_t entry_time, char* args) { char* name(my_strtok(args, ";")); contact_map::const_iterator ct_it{contact::contacts.find(name)}; if (ct_it == contact::contacts.end()) { - SPDLOG_LOGGER_ERROR(log_v2::external_command(), "unknown contact: {}", - name); + SPDLOG_LOGGER_ERROR(external_command_logger, "unknown contact: {}", name); return; } (*fptr)(ct_it->second.get()); @@ -748,7 +746,7 @@ void processing::_redirector_contactgroup(int id, contactgroup_map::iterator it_cg{ contactgroup::contactgroups.find(group_name)}; if (it_cg == contactgroup::contactgroups.end() || !it_cg->second) { - SPDLOG_LOGGER_ERROR(log_v2::external_command(), "unknown contact group: {}", + SPDLOG_LOGGER_ERROR(external_command_logger, "unknown contact group: {}", group_name); return; } @@ -774,13 +772,13 @@ void processing::_redirector_anomalydetection(int id, service::services.find({name, description})}; if (found == service::services.end() || !found->second) { - SPDLOG_LOGGER_ERROR(log_v2::external_command(), + SPDLOG_LOGGER_ERROR(external_command_logger, "unknown anomaly detection {}@{}", description, name); return; } if (found->second->get_service_type() != service_type::ANOMALY_DETECTION) { - SPDLOG_LOGGER_ERROR(log_v2::external_command(), + SPDLOG_LOGGER_ERROR(external_command_logger, "{}@{} is not an anomalydetection", description, name); return; } @@ -792,7 +790,7 @@ void processing::_redirector_anomalydetection(int id, bool processing::execute(const std::string& cmdstr) { engine_logger(dbg_functions, basic) << "processing external command"; - log_v2::functions()->trace("processing external command {}", cmdstr); + functions_logger->trace("processing external command {}", cmdstr); char const* cmd{cmdstr.c_str()}; size_t len{cmdstr.size()}; @@ -839,7 +837,7 @@ bool processing::execute(const std::string& cmdstr) { else if (command_name[0] != '_') { engine_logger(log_external_command | log_runtime_warning, basic) << "Warning: Unrecognized external command -> " << command_name; - log_v2::external_command()->warn( + external_command_logger->warn( "Warning: Unrecognized external command -> {}", command_name); return false; } @@ -854,12 +852,12 @@ bool processing::execute(const std::string& cmdstr) { if (config->log_passive_checks()) { engine_logger(log_passive_check, basic) << "EXTERNAL COMMAND: " << command_name << ';' << args; - log_v2::checks()->info("EXTERNAL COMMAND: {};{}", command_name, args); + checks_logger->info("EXTERNAL COMMAND: {};{}", command_name, args); } } else if (config->log_external_commands()) { engine_logger(log_external_command, basic) << "EXTERNAL COMMAND: " << command_name << ';' << args; - SPDLOG_LOGGER_INFO(log_v2::external_command(), "EXTERNAL COMMAND: {};{}", + SPDLOG_LOGGER_INFO(external_command_logger, "EXTERNAL COMMAND: {};{}", command_name, args); } @@ -867,12 +865,11 @@ bool processing::execute(const std::string& cmdstr) { << "External command id: " << command_id << "\nCommand entry time: " << entry_time << "\nCommand arguments: " << args; - SPDLOG_LOGGER_DEBUG(log_v2::external_command(), "External command id: {}", + SPDLOG_LOGGER_DEBUG(external_command_logger, "External command id: {}", command_id); - SPDLOG_LOGGER_DEBUG(log_v2::external_command(), "Command entry time: {}", + SPDLOG_LOGGER_DEBUG(external_command_logger, "Command entry time: {}", entry_time); - SPDLOG_LOGGER_DEBUG(log_v2::external_command(), "Command arguments: {}", - args); + SPDLOG_LOGGER_DEBUG(external_command_logger, "Command arguments: {}", args); // Send data to event broker. broker_external_command(NEBTYPE_EXTERNALCOMMAND_START, command_id, @@ -912,7 +909,7 @@ void processing::_wrapper_read_state_information() { } catch (std::exception const& e) { engine_logger(log_runtime_error, basic) << "Error: could not load retention file: " << e.what(); - SPDLOG_LOGGER_ERROR(log_v2::runtime(), + SPDLOG_LOGGER_ERROR(runtime_logger, "Error: could not load retention file: {}", e.what()); } } @@ -974,7 +971,7 @@ void processing::_wrapper_set_host_notification_number(host* hst, char* args) { int notification_number; if (!absl::SimpleAtoi(args, ¬ification_number)) { SPDLOG_LOGGER_ERROR( - log_v2::runtime(), + runtime_logger, "Error: could not set host notification number: '{}' must be a " "positive integer", args); @@ -991,7 +988,7 @@ void processing::_wrapper_send_custom_host_notification(host* hst, char* args) { (buf[2] = my_strtok(NULL, ";"))) { if (!absl::SimpleAtoi(buf[0], &option)) { SPDLOG_LOGGER_ERROR( - log_v2::runtime(), + runtime_logger, "Error: could not send custom host notification: '{}' must be an " "integer between 0 and 7", buf[0]); @@ -1000,7 +997,7 @@ void processing::_wrapper_send_custom_host_notification(host* hst, char* args) { static_cast(option)); } else { SPDLOG_LOGGER_ERROR( - log_v2::runtime(), + runtime_logger, "Error: could not send custom host notification: '{}' must be an " "integer between 0 and 7", buf[0]); @@ -1063,7 +1060,7 @@ void processing::_wrapper_set_service_notification_number(service* svc, if (svc && str) { if (!absl::SimpleAtoi(str, ¬ification_number)) { SPDLOG_LOGGER_ERROR( - log_v2::runtime(), + runtime_logger, "Error: could not set service notification number: '{}' must be a " "positive integer", str); @@ -1081,7 +1078,7 @@ void processing::_wrapper_send_custom_service_notification(service* svc, (buf[2] = my_strtok(NULL, ";"))) { if (!absl::SimpleAtoi(buf[0], ¬ification_number)) { SPDLOG_LOGGER_ERROR( - log_v2::runtime(), + runtime_logger, "Error: could not send custom service notification: '{}' must be an " "integer between 0 and 7", buf[0]); @@ -1091,7 +1088,7 @@ void processing::_wrapper_send_custom_service_notification(service* svc, static_cast(notification_number)); } else { SPDLOG_LOGGER_ERROR( - log_v2::runtime(), + runtime_logger, "Error: could not send custom service notification: '{}' must be an " "integer between 0 and 7", buf[0]); @@ -1106,7 +1103,7 @@ void processing::change_anomaly_detection_sensitivity(anomalydetection* ano, ano->set_sensitivity(new_sensitivity); } else { SPDLOG_LOGGER_ERROR( - log_v2::external_command(), + external_command_logger, "change_anomaly_detection_sensitivity unable to parse args: {}", args); } } diff --git a/engine/src/commands/raw.cc b/engine/src/commands/raw.cc index 8e47972b45a..50e195545a1 100644 --- a/engine/src/commands/raw.cc +++ b/engine/src/commands/raw.cc @@ -1,27 +1,26 @@ /** -* Copyright 2011-2015,2017 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2015,2017 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/commands/raw.hh" #include "com/centreon/engine/commands/environment.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/macros.hh" @@ -64,7 +63,7 @@ raw::~raw() noexcept { } catch (std::exception const& e) { engine_logger(log_runtime_error, basic) << "Error: Raw command destructor failed: " << e.what(); - SPDLOG_LOGGER_ERROR(log_v2::runtime(), + SPDLOG_LOGGER_ERROR(runtime_logger, "Error: Raw command destructor failed: {}", e.what()); } } @@ -87,7 +86,7 @@ uint64_t raw::run(std::string const& processed_cmd, const void* caller) { engine_logger(dbg_commands, basic) << "raw::run: cmd='" << processed_cmd << "', timeout=" << timeout; - SPDLOG_LOGGER_TRACE(log_v2::commands(), "raw::run: cmd='{}', timeout={}", + SPDLOG_LOGGER_TRACE(commands_logger, "raw::run: cmd='{}', timeout={}", processed_cmd, timeout); // Get process and put into the busy list. @@ -105,7 +104,7 @@ uint64_t raw::run(std::string const& processed_cmd, engine_logger(dbg_commands, basic) << "raw::run: id=" << command_id << ", process=" << p; - SPDLOG_LOGGER_TRACE(log_v2::commands(), "raw::run: id={} , process={}", + SPDLOG_LOGGER_TRACE(commands_logger, "raw::run: id={} , process={}", command_id, (void*)p); // Setup environnement macros if is necessary. @@ -117,12 +116,12 @@ uint64_t raw::run(std::string const& processed_cmd, p->exec(processed_cmd.c_str(), env.data(), timeout); engine_logger(dbg_commands, basic) << "raw::run: start process success: id=" << command_id; - SPDLOG_LOGGER_TRACE(log_v2::commands(), + SPDLOG_LOGGER_TRACE(commands_logger, "raw::run: start process success: id={}", command_id); } catch (...) { engine_logger(dbg_commands, basic) << "raw::run: start process failed: id=" << command_id; - SPDLOG_LOGGER_TRACE(log_v2::commands(), + SPDLOG_LOGGER_TRACE(commands_logger, "raw::run: start process failed: id={}", command_id); std::lock_guard lock(_lock); @@ -147,7 +146,7 @@ void raw::run(std::string const& processed_cmd, result& res) { engine_logger(dbg_commands, basic) << "raw::run: cmd='" << processed_cmd << "', timeout=" << timeout; - SPDLOG_LOGGER_TRACE(log_v2::commands(), "raw::run: cmd='{}', timeout={}", + SPDLOG_LOGGER_TRACE(commands_logger, "raw::run: cmd='{}', timeout={}", processed_cmd, timeout); // Get process. @@ -156,7 +155,7 @@ void raw::run(std::string const& processed_cmd, engine_logger(dbg_commands, basic) << "raw::run: id=" << command_id << ", process=" << &p; - SPDLOG_LOGGER_TRACE(log_v2::commands(), "raw::run: id={}, process={}", + SPDLOG_LOGGER_TRACE(commands_logger, "raw::run: id={}, process={}", command_id, (void*)&p); // Setup environement macros if is necessary. @@ -168,12 +167,12 @@ void raw::run(std::string const& processed_cmd, p.exec(processed_cmd.c_str(), env.data(), timeout); engine_logger(dbg_commands, basic) << "raw::run: start process success: id=" << command_id; - SPDLOG_LOGGER_TRACE(log_v2::commands(), + SPDLOG_LOGGER_TRACE(commands_logger, "raw::run: start process success: id={}", command_id); } catch (...) { engine_logger(dbg_commands, basic) << "raw::run: start process failed: id=" << command_id; - SPDLOG_LOGGER_TRACE(log_v2::commands(), + SPDLOG_LOGGER_TRACE(commands_logger, "raw::run: start process failed: id={}", command_id); throw; } @@ -216,7 +215,7 @@ void raw::run(std::string const& processed_cmd, << ", " "output='" << res.output << "'"; - SPDLOG_LOGGER_TRACE(log_v2::commands(), + SPDLOG_LOGGER_TRACE(commands_logger, "raw::run: end process: " "id={}, {}", command_id, res); @@ -255,7 +254,7 @@ void raw::data_is_available_err(process& p) noexcept { void raw::finished(process& p) noexcept { try { engine_logger(dbg_commands, basic) << "raw::finished: process=" << &p; - SPDLOG_LOGGER_TRACE(log_v2::commands(), "raw::finished: process={}", + SPDLOG_LOGGER_TRACE(commands_logger, "raw::finished: process={}", (void*)&p); uint64_t command_id(0); @@ -272,7 +271,7 @@ void raw::finished(process& p) noexcept { engine_logger(log_runtime_warning, basic) << "Warning: Invalid process pointer: " "process not found into process busy list"; - SPDLOG_LOGGER_WARN(log_v2::runtime(), + SPDLOG_LOGGER_WARN(runtime_logger, "Warning: Invalid process pointer: " "process not found into process busy list"); return; @@ -283,7 +282,7 @@ void raw::finished(process& p) noexcept { } engine_logger(dbg_commands, basic) << "raw::finished: id=" << command_id; - SPDLOG_LOGGER_TRACE(log_v2::commands(), "raw::finished: id={}", command_id); + SPDLOG_LOGGER_TRACE(commands_logger, "raw::finished: id={}", command_id); // Build check result. result res; @@ -318,8 +317,8 @@ void raw::finished(process& p) noexcept { << ", exit_code=" << res.exit_code << ", exit_status=" << res.exit_status << ", output='" << res.output << "'"; - SPDLOG_LOGGER_TRACE(log_v2::commands(), "raw::finished: id={}, {}", - command_id, res); + SPDLOG_LOGGER_TRACE(commands_logger, "raw::finished: id={}, {}", command_id, + res); update_result_cache(command_id, res); @@ -329,7 +328,7 @@ void raw::finished(process& p) noexcept { } catch (std::exception const& e) { engine_logger(log_runtime_warning, basic) << "Warning: Raw process termination routine failed: " << e.what(); - SPDLOG_LOGGER_WARN(log_v2::runtime(), + SPDLOG_LOGGER_WARN(runtime_logger, "Warning: Raw process termination routine failed: {}", e.what()); diff --git a/engine/src/compatibility/logging.cc b/engine/src/compatibility/logging.cc index e214eeba3e4..6b9b1a2396d 100644 --- a/engine/src/compatibility/logging.cc +++ b/engine/src/compatibility/logging.cc @@ -1,21 +1,21 @@ /** -* Copyright 2011-2013,2017 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2013,2017 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/logging.hh" #include @@ -23,7 +23,6 @@ #include "com/centreon/engine/common.hh" #include "com/centreon/engine/globals.hh" #include "com/centreon/engine/host.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/service.hh" #include "com/centreon/engine/statusdata.hh" @@ -52,9 +51,9 @@ void log_host_state(unsigned int type, com::centreon::engine::host* hst) { << type_str << " HOST STATE: " << hst->name() << ";" << state << ";" << state_type << ";" << hst->get_current_attempt() << ";" << hst->get_plugin_output(); - log_v2::events()->info("{} HOST STATE: {};{};{};{};{}", type_str, hst->name(), - state, state_type, hst->get_current_attempt(), - hst->get_plugin_output()); + events_logger->info("{} HOST STATE: {};{};{};{};{}", type_str, hst->name(), + state, state_type, hst->get_current_attempt(), + hst->get_plugin_output()); } /** @@ -76,7 +75,7 @@ void log_service_state(unsigned int type, com::centreon::engine::service* svc) { << type_str << " SERVICE STATE: " << svc->get_hostname() << ";" << svc->description() << ";" << state << ";" << state_type << ";" << svc->get_current_attempt() << ";" << output; - log_v2::events()->info("{} SERVICE STATE: {};{};{};{};{};{}", type_str, - svc->get_hostname(), svc->description(), state, - state_type, svc->get_current_attempt(), output); + events_logger->info("{} SERVICE STATE: {};{};{};{};{};{}", type_str, + svc->get_hostname(), svc->description(), state, + state_type, svc->get_current_attempt(), output); } diff --git a/engine/src/config.cc b/engine/src/config.cc index 3cc9dab9122..87cd3d99014 100644 --- a/engine/src/config.cc +++ b/engine/src/config.cc @@ -1,29 +1,28 @@ /** -* Copyright 1999-2008 Ethan Galstad -* Copyright 2011-2019 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 1999-2008 Ethan Galstad + * Copyright 2011-2024 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/config.hh" #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/configuration/parser.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/string.hh" @@ -131,7 +130,7 @@ int pre_flight_circular_check(int* w, int* e) { engine_logger(log_verification_error, basic) << "Error: The host '" << it->first << "' is part of a circular parent/child chain!"; - log_v2::config()->error( + config_logger->error( "Error: The host '{}' is part of a circular parent/child chain!", it->first); } @@ -163,7 +162,7 @@ int pre_flight_circular_check(int* w, int* e) { "in a deadlock) exists for service '" << it->second->get_service_description() << "' on host '" << it->second->get_hostname() << "'!"; - log_v2::config()->error( + config_logger->error( "Error: A circular execution dependency (which could result " "in a deadlock) exists for service '{}' on host '{}'!", it->second->get_service_description(), it->second->get_hostname()); @@ -191,7 +190,7 @@ int pre_flight_circular_check(int* w, int* e) { "result in a deadlock) exists for service '" << it->second->get_service_description() << "' on host '" << it->second->get_hostname() << "'!"; - log_v2::config()->error( + config_logger->error( "Error: A circular notification dependency (which could " "result in a deadlock) exists for service '{}' on host '{}'!", it->second->get_service_description(), it->second->get_hostname()); @@ -225,7 +224,7 @@ int pre_flight_circular_check(int* w, int* e) { << "Error: A circular execution dependency (which could " "result in a deadlock) exists for host '" << it->second->get_hostname() << "'!"; - log_v2::config()->error( + config_logger->error( "Error: A circular execution dependency (which could " "result in a deadlock) exists for host '{}'!", it->second->get_hostname()); @@ -252,7 +251,7 @@ int pre_flight_circular_check(int* w, int* e) { << "Error: A circular notification dependency (which could " "result in a deadlock) exists for host '" << it->first << "'!"; - log_v2::config()->error( + config_logger->error( "Error: A circular notification dependency (which could " "result in a deadlock) exists for host '{}'!", it->first); diff --git a/engine/src/configuration/CMakeLists.txt b/engine/src/configuration/CMakeLists.txt index 8121674ec0b..d4adc8d11fc 100644 --- a/engine/src/configuration/CMakeLists.txt +++ b/engine/src/configuration/CMakeLists.txt @@ -1,18 +1,19 @@ # -# Copyright 2011-2013 Merethis +# Copyright 2009-2024 Centreon # -# This file is part of Centreon Engine. +# Licensed under the Apache License, Version 2.0 (the "License"); you may not +# use this file except in compliance with the License. You may obtain a copy of +# the License at # -# Centreon Engine is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License version 2 as published by -# the Free Software Foundation. +# http://www.apache.org/licenses/LICENSE-2.0 # -# Centreon Engine is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations under +# the License. # -# You should have received a copy of the GNU General Public License along with -# Centreon Engine. If not, see . +# For more information : contact@centreon.com # # Set directories. @@ -20,7 +21,7 @@ set(SRC_DIR "${SRC_DIR}/configuration") set(INC_DIR "${INC_DIR}/com/centreon/engine/configuration") # Subdirectory. -add_subdirectory("applier") +add_subdirectory(applier) # Set files. set(FILES diff --git a/engine/src/configuration/anomalydetection.cc b/engine/src/configuration/anomalydetection.cc index 98977cc1701..df58470b648 100644 --- a/engine/src/configuration/anomalydetection.cc +++ b/engine/src/configuration/anomalydetection.cc @@ -1,21 +1,21 @@ /** -* Copyright 2020-2022 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2020-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include "com/centreon/engine/configuration/anomalydetection.hh" #include @@ -24,8 +24,8 @@ #include "com/centreon/engine/configuration/serviceextinfo.hh" #include "com/centreon/engine/customvariable.hh" #include "com/centreon/engine/exceptions/error.hh" +#include "com/centreon/engine/globals.hh" #include "com/centreon/engine/host.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/string.hh" @@ -327,7 +327,7 @@ bool anomalydetection::operator==( if (!object::operator==(other)) { engine_logger(dbg_config, more) << "configuration::anomalydetection::equality => object don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::equality => object don't match"); return false; } @@ -335,7 +335,7 @@ bool anomalydetection::operator==( engine_logger(dbg_config, more) << "configuration::anomalydetection::equality => " "acknowledgement_timeout don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::equality => " "acknowledgement_timeout don't match"); return false; @@ -343,7 +343,7 @@ bool anomalydetection::operator==( if (_action_url != other._action_url) { engine_logger(dbg_config, more) << "configuration::anomalydetection::" "equality => action_url don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::" "equality => action_url don't match"); return false; @@ -351,7 +351,7 @@ bool anomalydetection::operator==( if (_status_change != other._status_change) { engine_logger(dbg_config, more) << "configuration::anomalydetection::" "equality => status_change don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::" "equality => status_change don't match"); return false; @@ -359,7 +359,7 @@ bool anomalydetection::operator==( if (_checks_active != other._checks_active) { engine_logger(dbg_config, more) << "configuration::anomalydetection::" "equality => checks_active don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::" "equality => checks_active don't match"); return false; @@ -367,7 +367,7 @@ bool anomalydetection::operator==( if (_checks_passive != other._checks_passive) { engine_logger(dbg_config, more) << "configuration::anomalydetection::" "equality => checks_passive don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::" "equality => checks_passive don't match"); return false; @@ -375,7 +375,7 @@ bool anomalydetection::operator==( if (_metric_name != other._metric_name) { engine_logger(dbg_config, more) << "configuration::anomalydetection::" "equality => metric_name don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::" "equality => metric_name don't match"); return false; @@ -384,7 +384,7 @@ bool anomalydetection::operator==( engine_logger(dbg_config, more) << "configuration::anomalydetection::equality => thresholds_file don't " "match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::equality => thresholds_file don't " "match"); return false; @@ -393,7 +393,7 @@ bool anomalydetection::operator==( engine_logger(dbg_config, more) << "configuration::anomalydetection::equality => check_freshness don't " "match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::equality => check_freshness don't " "match"); return false; @@ -401,7 +401,7 @@ bool anomalydetection::operator==( if (_check_interval != other._check_interval) { engine_logger(dbg_config, more) << "configuration::anomalydetection::" "equality => check_interval don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::" "equality => check_interval don't match"); return false; @@ -409,7 +409,7 @@ bool anomalydetection::operator==( if (_contactgroups != other._contactgroups) { engine_logger(dbg_config, more) << "configuration::anomalydetection::" "equality => contactgroups don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::" "equality => contactgroups don't match"); return false; @@ -417,7 +417,7 @@ bool anomalydetection::operator==( if (_contacts != other._contacts) { engine_logger(dbg_config, more) << "configuration::anomalydetection::equality => contacts don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::equality => contacts don't match"); return false; } @@ -425,7 +425,7 @@ bool anomalydetection::operator==( engine_logger(dbg_config, more) << "configuration::anomalydetection::equality => customvariables don't " "match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::equality => customvariables don't " "match"); return false; @@ -433,7 +433,7 @@ bool anomalydetection::operator==( if (_display_name != other._display_name) { engine_logger(dbg_config, more) << "configuration::anomalydetection::" "equality => display_name don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::" "equality => display_name don't match"); return false; @@ -441,7 +441,7 @@ bool anomalydetection::operator==( if (_event_handler != other._event_handler) { engine_logger(dbg_config, more) << "configuration::anomalydetection::" "equality => event_handler don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::" "equality => event_handler don't match"); return false; @@ -449,7 +449,7 @@ bool anomalydetection::operator==( if (_event_handler_enabled != other._event_handler_enabled) { engine_logger(dbg_config, more) << "configuration::anomalydetection::" "equality => event_handler don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::" "equality => event_handler don't match"); return false; @@ -458,7 +458,7 @@ bool anomalydetection::operator==( engine_logger(dbg_config, more) << "configuration::anomalydetection::equality => " "first_notification_delay don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::equality => " "first_notification_delay don't match"); return false; @@ -467,7 +467,7 @@ bool anomalydetection::operator==( engine_logger(dbg_config, more) << "configuration::anomalydetection::equality => " "flap_detection_enabled don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::equality => " "flap_detection_enabled don't match"); return false; @@ -476,7 +476,7 @@ bool anomalydetection::operator==( engine_logger(dbg_config, more) << "configuration::anomalydetection::equality => " "flap_detection_options don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::equality => " "flap_detection_options don't match"); return false; @@ -485,7 +485,7 @@ bool anomalydetection::operator==( engine_logger(dbg_config, more) << "configuration::anomalydetection::equality => " "freshness_threshold don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::equality => " "freshness_threshold don't match"); return false; @@ -494,7 +494,7 @@ bool anomalydetection::operator==( engine_logger(dbg_config, more) << "configuration::anomalydetection::equality => " "high_flap_threshold don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::equality => " "high_flap_threshold don't match"); return false; @@ -502,7 +502,7 @@ bool anomalydetection::operator==( if (_host_name != other._host_name) { engine_logger(dbg_config, more) << "configuration::anomalydetection::" "equality => _host_name don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::" "equality => _host_name don't match"); return false; @@ -510,7 +510,7 @@ bool anomalydetection::operator==( if (_icon_image != other._icon_image) { engine_logger(dbg_config, more) << "configuration::anomalydetection::" "equality => icon_image don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::" "equality => icon_image don't match"); return false; @@ -518,7 +518,7 @@ bool anomalydetection::operator==( if (_icon_image_alt != other._icon_image_alt) { engine_logger(dbg_config, more) << "configuration::anomalydetection::" "equality => icon_image_alt don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::" "equality => icon_image_alt don't match"); return false; @@ -526,7 +526,7 @@ bool anomalydetection::operator==( if (_initial_state != other._initial_state) { engine_logger(dbg_config, more) << "configuration::anomalydetection::" "equality => initial_state don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::" "equality => initial_state don't match"); return false; @@ -534,7 +534,7 @@ bool anomalydetection::operator==( if (_is_volatile != other._is_volatile) { engine_logger(dbg_config, more) << "configuration::anomalydetection::" "equality => is_volatile don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::" "equality => is_volatile don't match"); return false; @@ -543,7 +543,7 @@ bool anomalydetection::operator==( engine_logger(dbg_config, more) << "configuration::anomalydetection::equality => low_flap_threshold " "don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::equality => low_flap_threshold " "don't match"); return false; @@ -552,7 +552,7 @@ bool anomalydetection::operator==( engine_logger(dbg_config, more) << "configuration::anomalydetection::equality => max_check_attempts " "don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::equality => max_check_attempts " "don't match"); return false; @@ -560,14 +560,14 @@ bool anomalydetection::operator==( if (_notes != other._notes) { engine_logger(dbg_config, more) << "configuration::anomalydetection::equality => notes don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::equality => notes don't match"); return false; } if (_notes_url != other._notes_url) { engine_logger(dbg_config, more) << "configuration::anomalydetection::equality => notes_url don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::equality => notes_url don't match"); return false; } @@ -575,7 +575,7 @@ bool anomalydetection::operator==( engine_logger(dbg_config, more) << "configuration::anomalydetection::equality => " "notifications_enabled don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::equality => " "notifications_enabled don't match"); return false; @@ -584,7 +584,7 @@ bool anomalydetection::operator==( engine_logger(dbg_config, more) << "configuration::anomalydetection::equality => " "notification_interval don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::equality => " "notification_interval don't match"); return false; @@ -593,7 +593,7 @@ bool anomalydetection::operator==( engine_logger(dbg_config, more) << "configuration::anomalydetection::equality => " "notification_options don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::equality => " "notification_options don't match"); return false; @@ -602,7 +602,7 @@ bool anomalydetection::operator==( engine_logger(dbg_config, more) << "configuration::anomalydetection::equality => " "notification_period don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::equality => " "notification_period don't match"); return false; @@ -611,7 +611,7 @@ bool anomalydetection::operator==( engine_logger(dbg_config, more) << "configuration::anomalydetection::equality => " "obsess_over_service don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::equality => " "obsess_over_service don't match"); return false; @@ -620,7 +620,7 @@ bool anomalydetection::operator==( engine_logger(dbg_config, more) << "configuration::anomalydetection::equality => process_perf_data " "don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::equality => process_perf_data " "don't match"); return false; @@ -629,7 +629,7 @@ bool anomalydetection::operator==( engine_logger(dbg_config, more) << "configuration::anomalydetection::equality => " "retain_nonstatus_information don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::equality => " "retain_nonstatus_information don't match"); return false; @@ -638,7 +638,7 @@ bool anomalydetection::operator==( engine_logger(dbg_config, more) << "configuration::anomalydetection::equality => " "retain_status_information don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::equality => " "retain_status_information don't match"); return false; @@ -646,7 +646,7 @@ bool anomalydetection::operator==( if (_retry_interval != other._retry_interval) { engine_logger(dbg_config, more) << "configuration::anomalydetection::" "equality => retry_interval don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::" "equality => retry_interval don't match"); return false; @@ -655,7 +655,7 @@ bool anomalydetection::operator==( engine_logger(dbg_config, more) << "configuration::anomalydetection::equality => " "recovery_notification_delay don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::equality => " "recovery_notification_delay don't match"); return false; @@ -663,7 +663,7 @@ bool anomalydetection::operator==( if (_servicegroups != other._servicegroups) { engine_logger(dbg_config, more) << "configuration::anomalydetection::" "equality => servicegroups don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::" "equality => servicegroups don't match"); return false; @@ -672,7 +672,7 @@ bool anomalydetection::operator==( engine_logger(dbg_config, more) << "configuration::anomalydetection::equality => " "service_description don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::equality => " "service_description don't match"); return false; @@ -680,27 +680,27 @@ bool anomalydetection::operator==( if (_host_id != other._host_id) { engine_logger(dbg_config, more) << "configuration::anomalydetection::equality => host_id don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::equality => host_id don't match"); return false; } if (_host_id != other._host_id) { engine_logger(dbg_config, more) << "configuration::anomalydetection::equality => host_id don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::equality => host_id don't match"); return false; } if (_service_id != other._service_id) { engine_logger(dbg_config, more) << "configuration::anomalydetection::" "equality => service_id don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::" "equality => service_id don't match"); return false; } if (_internal_id != other._internal_id) { - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::equality => internal_id " "don't match"); return false; @@ -709,7 +709,7 @@ bool anomalydetection::operator==( engine_logger(dbg_config, more) << "configuration::anomalydetection::equality => dependent_service_id " "don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::equality => dependent_service_id " "don't match"); return false; @@ -718,7 +718,7 @@ bool anomalydetection::operator==( engine_logger(dbg_config, more) << "configuration::anomalydetection::equality => stalking_options " "don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::equality => stalking_options " "don't match"); return false; @@ -726,41 +726,41 @@ bool anomalydetection::operator==( if (_timezone != other._timezone) { engine_logger(dbg_config, more) << "configuration::anomalydetection::equality => timezone don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::equality => timezone don't match"); return false; } if (_severity_id != other._severity_id) { engine_logger(dbg_config, more) << "configuration::anomalydetection::" "equality => severity id don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::equality => severity id don't match"); return false; } if (_icon_id != other._icon_id) { engine_logger(dbg_config, more) << "configuration::anomalydetection::equality => icon id don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::equality => icon id don't match"); return false; } if (_tags != other._tags) { engine_logger(dbg_config, more) << "configuration::anomalydetection::equality => tags don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::equality => tags don't match"); return false; } if (_sensitivity != other._sensitivity) { engine_logger(dbg_config, more) << "configuration::anomalydetection::" "equality => sensitivity don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::anomalydetection::equality => sensitivity don't match"); return false; } engine_logger(dbg_config, more) << "configuration::anomalydetection::equality => OK"; - log_v2::config()->debug("configuration::anomalydetection::equality => OK"); + config_logger->debug("configuration::anomalydetection::equality => OK"); return true; } @@ -1769,7 +1769,7 @@ bool anomalydetection::_set_failure_prediction_enabled(bool value) { engine_logger(log_verification_error, basic) << "Warning: anomalydetection failure_prediction_enabled is deprecated." << " This option will not be supported in 20.04."; - log_v2::config()->warn( + config_logger->warn( "Warning: anomalydetection failure_prediction_enabled is deprecated. " "This option will not be supported in 20.04."); ++config_warnings; @@ -1789,7 +1789,7 @@ bool anomalydetection::_set_failure_prediction_options( engine_logger(log_verification_error, basic) << "Warning: anomalydetection failure_prediction_options is deprecated." << " This option will not be supported in 20.04."; - log_v2::config()->warn( + config_logger->warn( "Warning: anomalydetection failure_prediction_options is deprecated. " "This option will not be supported in 20.04."); ++config_warnings; @@ -2095,7 +2095,7 @@ bool anomalydetection::_set_parallelize_check(bool value) { engine_logger(log_verification_error, basic) << "Warning: anomalydetection parallelize_check is deprecated" << " This option will not be supported in 20.04."; - log_v2::config()->warn( + config_logger->warn( "Warning: anomalydetection parallelize_check is deprecated This option " "will not be supported in 20.04."); ++config_warnings; @@ -2295,7 +2295,7 @@ bool anomalydetection::_set_category_tags(const std::string& value) { if (parse_ok) { _tags.emplace(id, tag::servicecategory); } else { - log_v2::config()->warn( + config_logger->warn( "Warning: anomalydetection ({}, {}) error for parsing tag {}", _host_id, _service_id, value); ret = false; @@ -2330,7 +2330,7 @@ bool anomalydetection::_set_group_tags(const std::string& value) { if (parse_ok) { _tags.emplace(id, tag::servicegroup); } else { - log_v2::config()->warn( + config_logger->warn( "Warning: anomalydetection ({}, {}) error for parsing tag {}", _host_id, _service_id, value); ret = false; diff --git a/engine/src/configuration/applier/anomalydetection.cc b/engine/src/configuration/applier/anomalydetection.cc index abda4c69468..7050832c5a2 100644 --- a/engine/src/configuration/applier/anomalydetection.cc +++ b/engine/src/configuration/applier/anomalydetection.cc @@ -1,21 +1,21 @@ /** -* Copyright 2020 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2020 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/configuration/applier/anomalydetection.hh" #include "com/centreon/engine/anomalydetection.hh" @@ -25,7 +25,6 @@ #include "com/centreon/engine/downtimes/downtime_manager.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" using namespace com::centreon; using namespace com::centreon::engine; @@ -100,7 +99,7 @@ void applier::anomalydetection::add_object( engine_logger(logging::dbg_config, logging::more) << "Creating new anomalydetection '" << obj.service_description() << "' of host '" << obj.host_name() << "'."; - SPDLOG_LOGGER_DEBUG(log_v2::config(), + SPDLOG_LOGGER_DEBUG(config_logger, "Creating new anomalydetection '{}' of host '{}'.", obj.service_description(), obj.host_name()); @@ -239,7 +238,7 @@ void applier::anomalydetection::modify_object( engine_logger(logging::dbg_config, logging::more) << "Modifying new anomalydetection '" << service_description << "' of host '" << host_name << "'."; - SPDLOG_LOGGER_DEBUG(log_v2::config(), + SPDLOG_LOGGER_DEBUG(config_logger, "Modifying new anomalydetection '{}' of host '{}'.", service_description, host_name); @@ -447,7 +446,7 @@ void applier::anomalydetection::remove_object( engine_logger(logging::dbg_config, logging::more) << "Removing anomalydetection '" << service_description << "' of host '" << host_name << "'."; - SPDLOG_LOGGER_DEBUG(log_v2::config(), + SPDLOG_LOGGER_DEBUG(config_logger, "Removing anomalydetection '{}' of host '{}'.", service_description, host_name); @@ -497,7 +496,7 @@ void applier::anomalydetection::resolve_object( engine_logger(logging::dbg_config, logging::more) << "Resolving anomalydetection '" << obj.service_description() << "' of host '" << obj.host_name() << "'."; - SPDLOG_LOGGER_DEBUG(log_v2::config(), + SPDLOG_LOGGER_DEBUG(config_logger, "Resolving anomalydetection '{}' of host '{}'.", obj.service_description(), obj.host_name()); diff --git a/engine/src/configuration/applier/command.cc b/engine/src/configuration/applier/command.cc index d59baf279ea..48275d2ed3e 100644 --- a/engine/src/configuration/applier/command.cc +++ b/engine/src/configuration/applier/command.cc @@ -1,21 +1,21 @@ /** -* Copyright 2011-2013,2017 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2013,2017-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include "com/centreon/engine/configuration/applier/command.hh" #include "com/centreon/engine/broker.hh" @@ -26,7 +26,6 @@ #include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" using namespace com::centreon::engine; @@ -51,7 +50,7 @@ void applier::command::add_object(configuration::command const& obj) { // Logging. engine_logger(logging::dbg_config, logging::more) << "Creating new command '" << obj.command_name() << "'."; - log_v2::config()->debug("Creating new command '{}'.", obj.command_name()); + config_logger->debug("Creating new command '{}'.", obj.command_name()); // Add command to the global configuration set. config->commands().insert(obj); @@ -97,7 +96,7 @@ void applier::command::modify_object(configuration::command const& obj) { // Logging. engine_logger(logging::dbg_config, logging::more) << "Modifying command '" << obj.command_name() << "'."; - log_v2::config()->debug("Modifying command '{}'.", obj.command_name()); + config_logger->debug("Modifying command '{}'.", obj.command_name()); // Find old configuration. set_command::iterator it_cfg(config->commands_find(obj.key())); @@ -158,7 +157,7 @@ void applier::command::remove_object(configuration::command const& obj) { // Logging. engine_logger(logging::dbg_config, logging::more) << "Removing command '" << obj.command_name() << "'."; - log_v2::config()->debug("Removing command '{}'.", obj.command_name()); + config_logger->debug("Removing command '{}'.", obj.command_name()); // Find command. std::unordered_map >::iterator diff --git a/engine/src/configuration/applier/connector.cc b/engine/src/configuration/applier/connector.cc index 7190dc6f474..3b075341e3c 100644 --- a/engine/src/configuration/applier/connector.cc +++ b/engine/src/configuration/applier/connector.cc @@ -1,21 +1,21 @@ /** -* Copyright 2011-2013,2017 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2013,2017 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/commands/connector.hh" #include "com/centreon/engine/checks/checker.hh" @@ -23,7 +23,6 @@ #include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/macros/misc.hh" #include "com/centreon/engine/macros/process.hh" @@ -48,7 +47,7 @@ void applier::connector::add_object(configuration::connector const& obj) { // Logging. engine_logger(logging::dbg_config, logging::more) << "Creating new connector '" << obj.connector_name() << "'."; - log_v2::config()->debug("Creating new connector '{}'.", obj.connector_name()); + config_logger->debug("Creating new connector '{}'.", obj.connector_name()); // Expand command line. nagios_macros* macros(get_global_macros()); @@ -86,7 +85,7 @@ void applier::connector::modify_object(configuration::connector const& obj) { // Logging. engine_logger(logging::dbg_config, logging::more) << "Modifying connector '" << obj.connector_name() << "'."; - log_v2::config()->debug("Modifying connector '{}'.", obj.connector_name()); + config_logger->debug("Modifying connector '{}'.", obj.connector_name()); // Find old configuration. set_connector::iterator it_cfg(config->connectors_find(obj.key())); @@ -127,7 +126,7 @@ void applier::connector::remove_object(configuration::connector const& obj) { // Logging. engine_logger(logging::dbg_config, logging::more) << "Removing connector '" << obj.connector_name() << "'."; - log_v2::config()->debug("Removing connector '{}'.", obj.connector_name()); + config_logger->debug("Removing connector '{}'.", obj.connector_name()); // Find connector. connector_map::iterator it(commands::connector::connectors.find(obj.key())); diff --git a/engine/src/configuration/applier/contact.cc b/engine/src/configuration/applier/contact.cc index ee9d9d899bc..07d225eb9e5 100644 --- a/engine/src/configuration/applier/contact.cc +++ b/engine/src/configuration/applier/contact.cc @@ -1,5 +1,5 @@ /** - * Copyright 2011-2015,2017-2019 Centreon (https://www.centreon.com/) + * Copyright 2011-2015,2017-2024 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,6 @@ #include "com/centreon/engine/deleter/listmember.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" using namespace com::centreon; using namespace com::centreon::engine; @@ -80,7 +79,7 @@ void applier::contact::add_object(configuration::contact const& obj) { // Logging. engine_logger(logging::dbg_config, logging::more) << "Creating new contact '" << obj.contact_name() << "'."; - log_v2::config()->debug("Creating new contact '{}'.", obj.contact_name()); + config_logger->debug("Creating new contact '{}'.", obj.contact_name()); // Add contact to the global configuration set. config->contacts().insert(obj); @@ -195,7 +194,7 @@ void applier::contact::modify_object(configuration::contact const& obj) { // Logging. engine_logger(logging::dbg_config, logging::more) << "Modifying contact '" << obj.contact_name() << "'."; - log_v2::config()->debug("Modifying contact '{}'.", obj.contact_name()); + config_logger->debug("Modifying contact '{}'.", obj.contact_name()); // Find old configuration. set_contact::iterator it_cfg(config->contacts_find(obj.key())); @@ -357,7 +356,7 @@ void applier::contact::remove_object(configuration::contact const& obj) { // Logging. engine_logger(logging::dbg_config, logging::more) << "Removing contact '" << obj.contact_name() << "'."; - log_v2::config()->debug("Removing contact '{}'.", obj.contact_name()); + config_logger->debug("Removing contact '{}'.", obj.contact_name()); // Find contact. contact_map::iterator it{engine::contact::contacts.find(obj.key())}; @@ -391,7 +390,7 @@ void applier::contact::resolve_object(configuration::contact const& obj) { // Logging. engine_logger(logging::dbg_config, logging::more) << "Resolving contact '" << obj.contact_name() << "'."; - log_v2::config()->debug("Resolving contact '{}'.", obj.contact_name()); + config_logger->debug("Resolving contact '{}'.", obj.contact_name()); // Find contact. contact_map::const_iterator ct_it{ diff --git a/engine/src/configuration/applier/contactgroup.cc b/engine/src/configuration/applier/contactgroup.cc index af3cd9b5b9a..2b27dfa35e0 100644 --- a/engine/src/configuration/applier/contactgroup.cc +++ b/engine/src/configuration/applier/contactgroup.cc @@ -1,21 +1,21 @@ /** -* Copyright 2011-2019 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2017 - 2024 Centreon (https://www.centreon.com/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include "com/centreon/engine/configuration/applier/contactgroup.hh" #include "com/centreon/engine/broker.hh" @@ -24,7 +24,6 @@ #include "com/centreon/engine/deleter/listmember.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" using namespace com::centreon::engine::configuration; @@ -73,7 +72,7 @@ void applier::contactgroup::add_object(configuration::contactgroup const& obj) { // Logging. engine_logger(logging::dbg_config, logging::more) << "Creating new contactgroup '" << name << "'."; - log_v2::config()->debug("Creating new contactgroup '{}'.", name); + config_logger->debug("Creating new contactgroup '{}'.", name); if (engine::contactgroup::contactgroups.find(name) != engine::contactgroup::contactgroups.end()) @@ -93,7 +92,7 @@ void applier::contactgroup::add_object(configuration::contactgroup const& obj) { engine_logger(log_verification_error, basic) << "Error: Contact '" << *it << "' specified in contact group '" << cg->get_name() << "' is not defined anywhere!"; - log_v2::config()->error( + config_logger->error( "Error: Contact '{}' specified in contact group '{}' is not defined " "anywhere!", *it, cg->get_name()); @@ -139,8 +138,7 @@ void applier::contactgroup::modify_object( // Logging. engine_logger(logging::dbg_config, logging::more) << "Modifying contactgroup '" << obj.contactgroup_name() << "'"; - log_v2::config()->debug("Modifying contactgroup '{}'", - obj.contactgroup_name()); + config_logger->debug("Modifying contactgroup '{}'", obj.contactgroup_name()); // Find old configuration. set_contactgroup::iterator it_cfg(config->contactgroups_find(obj.key())); @@ -178,7 +176,7 @@ void applier::contactgroup::modify_object( engine_logger(log_verification_error, basic) << "Error: Contact '" << *it << "' specified in contact group '" << it_obj->second->get_name() << "' is not defined anywhere!"; - log_v2::config()->error( + config_logger->error( "Error: Contact '{}' specified in contact group '{}' is not " "defined anywhere!", *it, it_obj->second->get_name()); @@ -207,8 +205,7 @@ void applier::contactgroup::remove_object( // Logging. engine_logger(logging::dbg_config, logging::more) << "Removing contactgroup '" << obj.contactgroup_name() << "'"; - log_v2::config()->debug("Removing contactgroup '{}'", - obj.contactgroup_name()); + config_logger->debug("Removing contactgroup '{}'", obj.contactgroup_name()); // Find contact group. contactgroup_map::iterator it( @@ -238,8 +235,7 @@ void applier::contactgroup::resolve_object( // Logging. engine_logger(logging::dbg_config, logging::more) << "Resolving contact group '" << obj.contactgroup_name() << "'"; - log_v2::config()->debug("Resolving contact group '{}'", - obj.contactgroup_name()); + config_logger->debug("Resolving contact group '{}'", obj.contactgroup_name()); // Find contact group. contactgroup_map::iterator it{ @@ -267,8 +263,8 @@ void applier::contactgroup::_resolve_members( engine_logger(logging::dbg_config, logging::more) << "Resolving members of contact group '" << obj.contactgroup_name() << "'"; - log_v2::config()->debug("Resolving members of contact group '{}'", - obj.contactgroup_name()); + config_logger->debug("Resolving members of contact group '{}'", + obj.contactgroup_name()); // Mark object as resolved. configuration::contactgroup& resolved_obj(_resolved[obj.key()]); diff --git a/engine/src/configuration/applier/host.cc b/engine/src/configuration/applier/host.cc index 8ed4b562c82..6ca6239e0a8 100644 --- a/engine/src/configuration/applier/host.cc +++ b/engine/src/configuration/applier/host.cc @@ -1,21 +1,21 @@ /** -* Copyright 2011-2019,2022 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2019,2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include "com/centreon/engine/configuration/applier/host.hh" @@ -27,7 +27,6 @@ #include "com/centreon/engine/downtimes/downtime_manager.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/severity.hh" using namespace com::centreon; @@ -53,7 +52,7 @@ void applier::host::add_object(configuration::host const& obj) { // Logging. engine_logger(logging::dbg_config, logging::more) << "Creating new host '" << obj.host_name() << "'."; - log_v2::config()->debug("Creating new host '{}'.", obj.host_name()); + config_logger->debug("Creating new host '{}'.", obj.host_name()); // Add host to the global configuration set. config->hosts().insert(obj); @@ -226,7 +225,7 @@ void applier::host::modify_object(configuration::host const& obj) { // Logging. engine_logger(logging::dbg_config, logging::more) << "Modifying host '" << obj.host_name() << "'."; - log_v2::config()->debug("Modifying host '{}'.", obj.host_name()); + config_logger->debug("Modifying host '{}'.", obj.host_name()); // Find the configuration object. set_host::iterator it_cfg(config->hosts_find(obj.key())); @@ -462,7 +461,7 @@ void applier::host::remove_object(configuration::host const& obj) { // Logging. engine_logger(logging::dbg_config, logging::more) << "Removing host '" << obj.host_name() << "'."; - log_v2::config()->debug("Removing host '{}'.", obj.host_name()); + config_logger->debug("Removing host '{}'.", obj.host_name()); // Find host. host_id_map::iterator it(engine::host::hosts_by_id.find(obj.key())); @@ -509,7 +508,7 @@ void applier::host::resolve_object(configuration::host const& obj) { // Logging. engine_logger(logging::dbg_config, logging::more) << "Resolving host '" << obj.host_name() << "'."; - log_v2::config()->debug("Resolving host '{}'.", obj.host_name()); + config_logger->debug("Resolving host '{}'.", obj.host_name()); // If it is the very first host to be resolved, // remove all the child backlinks of all the hosts. diff --git a/engine/src/configuration/applier/hostdependency.cc b/engine/src/configuration/applier/hostdependency.cc index b13592c8e5c..f30f8f35b6c 100644 --- a/engine/src/configuration/applier/hostdependency.cc +++ b/engine/src/configuration/applier/hostdependency.cc @@ -1,20 +1,20 @@ /** - * Copyright 2011-2019 Centreon + * Copyright 2011-2024 Centreon * - * This file is part of Centreon Engine. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Centreon Engine is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License version 2 - * as published by the Free Software Foundation. + * http://www.apache.org/licenses/LICENSE-2.0 * - * Centreon Engine is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com * - * You should have received a copy of the GNU General Public License - * along with Centreon Engine. If not, see - * . */ #include "com/centreon/engine/configuration/applier/hostdependency.hh" @@ -23,7 +23,6 @@ #include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" using namespace com::centreon::engine::configuration; @@ -65,7 +64,7 @@ void applier::hostdependency::add_object( << "Creating new host dependency of host '" << *obj.dependent_hosts().begin() << "' on host '" << *obj.hosts().begin() << "'."; - log_v2::config()->debug( + config_logger->debug( "Creating new host dependency of host '{}' on host '{}'.", *obj.dependent_hosts().begin(), *obj.hosts().begin()); @@ -156,8 +155,9 @@ void applier::hostdependency::expand_objects(configuration::state& s) { hdep.dependent_hosts().clear(); hdep.dependent_hosts().insert(*it2); hdep.dependency_type( - i == 0 ? configuration::hostdependency::execution_dependency - : configuration::hostdependency::notification_dependency); + i == 0 + ? configuration::hostdependency::execution_dependency + : configuration::hostdependency::notification_dependency); if (i == 1) hdep.execution_failure_options(0); else @@ -206,7 +206,7 @@ void applier::hostdependency::remove_object( // Logging. engine_logger(logging::dbg_config, logging::more) << "Removing a host dependency."; - log_v2::config()->debug("Removing a host dependency."); + config_logger->debug("Removing a host dependency."); // Find host dependency. hostdependency_mmap::iterator it( @@ -235,7 +235,7 @@ void applier::hostdependency::resolve_object( // Logging. engine_logger(logging::dbg_config, logging::more) << "Resolving a host dependency."; - log_v2::config()->debug("Resolving a host dependency."); + config_logger->debug("Resolving a host dependency."); // Find host escalation hostdependency_mmap::iterator it{ diff --git a/engine/src/configuration/applier/hostescalation.cc b/engine/src/configuration/applier/hostescalation.cc index b776931cadf..f0db4b1b576 100644 --- a/engine/src/configuration/applier/hostescalation.cc +++ b/engine/src/configuration/applier/hostescalation.cc @@ -1,21 +1,21 @@ /** -* Copyright 2011-2019 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include "com/centreon/engine/configuration/applier/hostescalation.hh" #include "com/centreon/engine/broker.hh" @@ -23,7 +23,6 @@ #include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" using namespace com::centreon::engine::configuration; @@ -53,8 +52,8 @@ void applier::hostescalation::add_object( // Logging. engine_logger(logging::dbg_config, logging::more) << "Creating new escalation for host '" << *obj.hosts().begin() << "'."; - log_v2::config()->debug("Creating new escalation for host '{}'.", - *obj.hosts().begin()); + config_logger->debug("Creating new escalation for host '{}'.", + *obj.hosts().begin()); // Add escalation to the global configuration set. config->hostescalations().insert(obj); @@ -154,7 +153,7 @@ void applier::hostescalation::remove_object( // Logging. engine_logger(logging::dbg_config, logging::more) << "Removing a host escalation."; - log_v2::config()->debug("Removing a host escalation."); + config_logger->debug("Removing a host escalation."); // Find host escalation. std::string const& host_name{*obj.hosts().begin()}; @@ -168,8 +167,7 @@ void applier::hostescalation::remove_object( if (hit == engine::host::hosts.end()) { engine_logger(logging::dbg_config, logging::more) << "Cannot find host '" << host_name << "' - already removed."; - log_v2::config()->debug("Cannot find host '{}' - already removed.", - host_name); + config_logger->debug("Cannot find host '{}' - already removed.", host_name); host_exists = false; } else host_exists = true; @@ -204,8 +202,8 @@ void applier::hostescalation::remove_object( engine_logger(logging::dbg_config, logging::more) << "Host '" << host_name << "' found - removing escalation from it."; - log_v2::config()->debug( - "Host '{}' found - removing escalation from it.", host_name); + config_logger->debug("Host '{}' found - removing escalation from it.", + host_name); std::list& escalations(hit->second->get_escalations()); /* We need also to remove the escalation from the host */ for (std::list::iterator heit{escalations.begin()}, @@ -237,7 +235,7 @@ void applier::hostescalation::resolve_object( // Logging. engine_logger(logging::dbg_config, logging::more) << "Resolving a host escalation."; - log_v2::config()->debug("Resolving a host escalation."); + config_logger->debug("Resolving a host escalation."); // Find host escalation bool found{false}; diff --git a/engine/src/configuration/applier/hostgroup.cc b/engine/src/configuration/applier/hostgroup.cc index 84a7ef79ed5..b3b1b8c2303 100644 --- a/engine/src/configuration/applier/hostgroup.cc +++ b/engine/src/configuration/applier/hostgroup.cc @@ -1,21 +1,21 @@ /** -* Copyright 2011-2013,2015,2017 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2013,2015,2017-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include "com/centreon/engine/configuration/applier/hostgroup.hh" @@ -25,7 +25,6 @@ #include "com/centreon/engine/deleter/listmember.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" using namespace com::centreon::engine::configuration; @@ -58,7 +57,7 @@ void applier::hostgroup::add_object(configuration::hostgroup const& obj) { // Logging. engine_logger(logging::dbg_config, logging::more) << "Creating new hostgroup '" << obj.hostgroup_name() << "'."; - log_v2::config()->debug("Creating new hostgroup '{}'.", obj.hostgroup_name()); + config_logger->debug("Creating new hostgroup '{}'.", obj.hostgroup_name()); // Add host group to the global configuration state. config->hostgroups().insert(obj); @@ -111,7 +110,7 @@ void applier::hostgroup::modify_object(configuration::hostgroup const& obj) { // Logging. engine_logger(logging::dbg_config, logging::more) << "Modifying hostgroup '" << obj.hostgroup_name() << "'"; - log_v2::config()->debug("Modifying hostgroup '{}'", obj.hostgroup_name()); + config_logger->debug("Modifying hostgroup '{}'", obj.hostgroup_name()); // Find old configuration. set_hostgroup::iterator it_cfg(config->hostgroups_find(obj.key())); @@ -168,7 +167,7 @@ void applier::hostgroup::remove_object(configuration::hostgroup const& obj) { // Logging. engine_logger(logging::dbg_config, logging::more) << "Removing host group '" << obj.hostgroup_name() << "'"; - log_v2::config()->debug("Removing host group '{}'", obj.hostgroup_name()); + config_logger->debug("Removing host group '{}'", obj.hostgroup_name()); // Find host group. hostgroup_map::iterator it{engine::hostgroup::hostgroups.find(obj.key())}; @@ -195,7 +194,7 @@ void applier::hostgroup::resolve_object(configuration::hostgroup const& obj) { // Logging. engine_logger(logging::dbg_config, logging::more) << "Resolving host group '" << obj.hostgroup_name() << "'"; - log_v2::config()->debug("Resolving host group '{}'", obj.hostgroup_name()); + config_logger->debug("Resolving host group '{}'", obj.hostgroup_name()); // Find host group. hostgroup_map::iterator it{engine::hostgroup::hostgroups.find(obj.key())}; @@ -221,8 +220,8 @@ void applier::hostgroup::_resolve_members(configuration::state& s // Logging. engine_logger(logging::dbg_config, logging::more) << "Resolving members of host group '" << obj.hostgroup_name() << "'"; - log_v2::config()->debug("Resolving members of host group '{}'", - obj.hostgroup_name()); + config_logger->debug("Resolving members of host group '{}'", + obj.hostgroup_name()); // Mark object as resolved. configuration::hostgroup& resolved_obj(_resolved[obj.key()]); diff --git a/engine/src/configuration/applier/scheduler.cc b/engine/src/configuration/applier/scheduler.cc index f8b6135bfd2..7db63225c18 100644 --- a/engine/src/configuration/applier/scheduler.cc +++ b/engine/src/configuration/applier/scheduler.cc @@ -1,21 +1,21 @@ /** -* Copyright 2011-2017 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include "com/centreon/engine/configuration/applier/scheduler.hh" #include "com/centreon/engine/configuration/applier/difference.hh" @@ -23,7 +23,6 @@ #include "com/centreon/engine/deleter/listmember.hh" #include "com/centreon/engine/events/loop.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/statusdata.hh" #include "com/centreon/engine/timezone_locker.hh" @@ -519,23 +518,23 @@ void applier::scheduler::_calculate_host_inter_check_delay( engine_logger(dbg_events, most) << "Total scheduled host checks: " << scheduling_info.total_scheduled_hosts; - log_v2::events()->debug("Total scheduled host checks: {}", - scheduling_info.total_scheduled_hosts); + events_logger->debug("Total scheduled host checks: {}", + scheduling_info.total_scheduled_hosts); engine_logger(dbg_events, most) << "Host check interval total: " << scheduling_info.host_check_interval_total; - log_v2::events()->debug("Host check interval total: {}", - scheduling_info.host_check_interval_total); + events_logger->debug("Host check interval total: {}", + scheduling_info.host_check_interval_total); engine_logger(dbg_events, most) << setprecision(2) << "Average host check interval: " << scheduling_info.average_host_check_interval << " sec"; - log_v2::events()->debug("Average host check interval: {:.2f} sec", - scheduling_info.average_host_check_interval); + events_logger->debug("Average host check interval: {:.2f} sec", + scheduling_info.average_host_check_interval); engine_logger(dbg_events, most) << setprecision(2) << "Host inter-check delay: " << scheduling_info.host_inter_check_delay << " sec"; - log_v2::events()->debug("Host inter-check delay: {:.2f} sec", - scheduling_info.host_inter_check_delay); + events_logger->debug("Host inter-check delay: {:.2f} sec", + scheduling_info.host_inter_check_delay); } } @@ -545,7 +544,7 @@ void applier::scheduler::_calculate_host_inter_check_delay( void applier::scheduler::_calculate_host_scheduling_params() { engine_logger(dbg_events, most) << "Determining host scheduling parameters..."; - log_v2::events()->debug("Determining host scheduling parameters..."); + events_logger->debug("Determining host scheduling parameters..."); // get current time. time_t const now(time(nullptr)); @@ -578,7 +577,7 @@ void applier::scheduler::_calculate_host_scheduling_params() { hst.set_should_be_scheduled(false); engine_logger(dbg_events, more) << "Host " << hst.name() << " should not be scheduled."; - log_v2::events()->debug("Host {} should not be scheduled.", hst.name()); + events_logger->debug("Host {} should not be scheduled.", hst.name()); } ++scheduling_info.total_hosts; @@ -645,18 +644,18 @@ void applier::scheduler::_calculate_service_inter_check_delay( engine_logger(dbg_events, more) << "Total scheduled service checks: " << scheduling_info.total_scheduled_services; - log_v2::events()->debug("Total scheduled service checks: {}", - scheduling_info.total_scheduled_services); + events_logger->debug("Total scheduled service checks: {}", + scheduling_info.total_scheduled_services); engine_logger(dbg_events, more) << setprecision(2) << "Average service check interval: " << scheduling_info.average_service_check_interval << " sec"; - log_v2::events()->debug("Average service check interval: {:.2f} sec", - scheduling_info.average_service_check_interval); + events_logger->debug("Average service check interval: {:.2f} sec", + scheduling_info.average_service_check_interval); engine_logger(dbg_events, more) << setprecision(2) << "Service inter-check delay: " << scheduling_info.service_inter_check_delay << " sec"; - log_v2::events()->debug("Service inter-check delay: {:.2f} sec", - scheduling_info.service_inter_check_delay); + events_logger->debug("Service inter-check delay: {:.2f} sec", + scheduling_info.service_inter_check_delay); } } @@ -680,17 +679,17 @@ void applier::scheduler::_calculate_service_interleave_factor( engine_logger(dbg_events, more) << "Total scheduled service checks: " << scheduling_info.total_scheduled_services; - log_v2::events()->debug("Total scheduled service checks: {}", - scheduling_info.total_scheduled_services); + events_logger->debug("Total scheduled service checks: {}", + scheduling_info.total_scheduled_services); engine_logger(dbg_events, more) << "Total hosts: " << scheduling_info.total_hosts; - log_v2::events()->debug("Total hosts: {}", - scheduling_info.total_hosts); + events_logger->debug("Total hosts: {}", + scheduling_info.total_hosts); engine_logger(dbg_events, more) << "Service Interleave factor: " << scheduling_info.service_interleave_factor; - log_v2::events()->debug("Service Interleave factor: {}", - scheduling_info.service_interleave_factor); + events_logger->debug("Service Interleave factor: {}", + scheduling_info.service_interleave_factor); } } @@ -700,7 +699,7 @@ void applier::scheduler::_calculate_service_interleave_factor( void applier::scheduler::_calculate_service_scheduling_params() { engine_logger(dbg_events, most) << "Determining service scheduling parameters..."; - log_v2::events()->debug("Determining service scheduling parameters..."); + events_logger->debug("Determining service scheduling parameters..."); // get current time. time_t const now(time(nullptr)); @@ -736,8 +735,8 @@ void applier::scheduler::_calculate_service_scheduling_params() { engine_logger(dbg_events, more) << "Service " << svc.description() << " on host " << svc.get_hostname() << " should not be scheduled."; - log_v2::events()->debug("Service {} on host {} should not be scheduled.", - svc.description(), svc.get_hostname()); + events_logger->debug("Service {} on host {} should not be scheduled.", + svc.description(), svc.get_hostname()); } ++scheduling_info.total_services; } @@ -901,7 +900,7 @@ void applier::scheduler::_remove_misc_event(timed_event*& evt) { void applier::scheduler::_schedule_host_events( std::vector const& hosts) { engine_logger(dbg_events, most) << "Scheduling host checks..."; - log_v2::events()->debug("Scheduling host checks..."); + events_logger->debug("Scheduling host checks..."); // get current time. time_t const now(time(nullptr)); @@ -914,12 +913,12 @@ void applier::scheduler::_schedule_host_events( com::centreon::engine::host& hst(*hosts[i]); engine_logger(dbg_events, most) << "Host '" << hst.name() << "'"; - log_v2::events()->debug("Host '{}'", hst.name()); + events_logger->debug("Host '{}'", hst.name()); // skip hosts that shouldn't be scheduled. if (!hst.get_should_be_scheduled()) { engine_logger(dbg_events, most) << "Host check should not be scheduled."; - log_v2::events()->debug("Host check should not be scheduled."); + events_logger->debug("Host check should not be scheduled."); continue; } @@ -931,8 +930,8 @@ void applier::scheduler::_schedule_host_events( engine_logger(dbg_events, most) << "Preferred Check Time: " << hst.get_next_check() << " --> " << my_ctime(&time); - log_v2::events()->debug("Preferred Check Time: {} --> {}", - hst.get_next_check(), my_ctime(&time)); + events_logger->debug("Preferred Check Time: {} --> {}", + hst.get_next_check(), my_ctime(&time)); // Make sure the host can actually be scheduled at this time. { @@ -950,8 +949,8 @@ void applier::scheduler::_schedule_host_events( engine_logger(dbg_events, most) << "Actual Check Time: " << hst.get_next_check() << " --> " << my_ctime(&time); - log_v2::events()->debug("Actual Check Time: {} --> {}", - hst.get_next_check(), my_ctime(&time)); + events_logger->debug("Actual Check Time: {} --> {}", hst.get_next_check(), + my_ctime(&time)); if (!scheduling_info.first_host_check || (hst.get_next_check() < scheduling_info.first_host_check)) @@ -999,7 +998,7 @@ void applier::scheduler::_schedule_host_events( // Schedule acknowledgement expirations. engine_logger(dbg_events, most) << "Scheduling host acknowledgement expirations..."; - log_v2::events()->debug("Scheduling host acknowledgement expirations..."); + events_logger->debug("Scheduling host acknowledgement expirations..."); for (int i(0), end(hosts.size()); i < end; ++i) if (hosts[i]->problem_has_been_acknowledged()) hosts[i]->schedule_acknowledgement_expiration(); @@ -1013,7 +1012,7 @@ void applier::scheduler::_schedule_host_events( void applier::scheduler::_schedule_service_events( std::vector const& services) { engine_logger(dbg_events, most) << "Scheduling service checks..."; - log_v2::events()->debug("Scheduling service checks..."); + events_logger->debug("Scheduling service checks..."); // get current time. time_t const now(time(nullptr)); @@ -1106,7 +1105,7 @@ void applier::scheduler::_schedule_service_events( // Schedule acknowledgement expirations. engine_logger(dbg_events, most) << "Scheduling service acknowledgement expirations..."; - log_v2::events()->debug("Scheduling service acknowledgement expirations..."); + events_logger->debug("Scheduling service acknowledgement expirations..."); for (engine::service* s : services) if (s->problem_has_been_acknowledged()) s->schedule_acknowledgement_expiration(); diff --git a/engine/src/configuration/applier/service.cc b/engine/src/configuration/applier/service.cc index 051d0bd20b5..e26d4f3d955 100644 --- a/engine/src/configuration/applier/service.cc +++ b/engine/src/configuration/applier/service.cc @@ -1,21 +1,21 @@ /** -* Copyright 2011-2019,2022 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2019,2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include "com/centreon/engine/configuration/applier/service.hh" #include "com/centreon/engine/anomalydetection.hh" @@ -25,7 +25,6 @@ #include "com/centreon/engine/downtimes/downtime_manager.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/severity.hh" using namespace com::centreon; @@ -110,8 +109,8 @@ void applier::service::add_object(configuration::service const& obj) { engine_logger(logging::dbg_config, logging::more) << "Creating new service '" << obj.service_description() << "' of host '" << *obj.hosts().begin() << "'."; - log_v2::config()->debug("Creating new service '{}' of host '{}'.", - obj.service_description(), *obj.hosts().begin()); + config_logger->debug("Creating new service '{}' of host '{}'.", + obj.service_description(), *obj.hosts().begin()); // Add service to the global configuration set. config->services().insert(obj); @@ -319,8 +318,8 @@ void applier::service::modify_object(configuration::service const& obj) { engine_logger(logging::dbg_config, logging::more) << "Modifying new service '" << service_description << "' of host '" << host_name << "'."; - log_v2::config()->debug("Modifying new service '{}' of host '{}'.", - service_description, host_name); + config_logger->debug("Modifying new service '{}' of host '{}'.", + service_description, host_name); // Find the configuration object. set_service::iterator it_cfg(config->services_find(obj.key())); @@ -548,8 +547,8 @@ void applier::service::remove_object(configuration::service const& obj) { engine_logger(logging::dbg_config, logging::more) << "Removing service '" << service_description << "' of host '" << host_name << "'."; - log_v2::config()->debug("Removing service '{}' of host '{}'.", - service_description, host_name); + config_logger->debug("Removing service '{}' of host '{}'.", + service_description, host_name); // Find anomaly detections depending on this service set_anomalydetection sad = config->anomalydetections(); @@ -605,8 +604,8 @@ void applier::service::resolve_object(configuration::service const& obj) { engine_logger(logging::dbg_config, logging::more) << "Resolving service '" << obj.service_description() << "' of host '" << *obj.hosts().begin() << "'."; - log_v2::config()->debug("Resolving service '{}' of host '{}'.", - obj.service_description(), *obj.hosts().begin()); + config_logger->debug("Resolving service '{}' of host '{}'.", + obj.service_description(), *obj.hosts().begin()); // Find service. service_id_map::iterator it(engine::service::services_by_id.find(obj.key())); diff --git a/engine/src/configuration/applier/servicedependency.cc b/engine/src/configuration/applier/servicedependency.cc index 001cb016602..25c69f6bf43 100644 --- a/engine/src/configuration/applier/servicedependency.cc +++ b/engine/src/configuration/applier/servicedependency.cc @@ -1,21 +1,21 @@ /** -* Copyright 2011-2013,2017-2019 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2013,2017-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include "com/centreon/engine/configuration/applier/servicedependency.hh" #include "com/centreon/engine/broker.hh" @@ -25,7 +25,6 @@ #include "com/centreon/engine/configuration/servicedependency.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" using namespace com::centreon::engine::configuration; @@ -78,7 +77,7 @@ void applier::servicedependency::add_object( << obj.dependent_hosts().front() << "' on service '" << obj.service_description().front() << "' of host '" << obj.hosts().front() << "'."; - log_v2::config()->debug( + config_logger->debug( "Creating new service dependency of service '{}' of host '{}' on service " "'{}' of host '{}'.", obj.dependent_service_description().front(), @@ -249,7 +248,7 @@ void applier::servicedependency::remove_object( // Logging. engine_logger(logging::dbg_config, logging::more) << "Removing a service dependency."; - log_v2::config()->debug("Removing a service dependency."); + config_logger->debug("Removing a service dependency."); // Find service dependency. servicedependency_mmap::iterator it( @@ -278,7 +277,7 @@ void applier::servicedependency::resolve_object( // Logging. engine_logger(logging::dbg_config, logging::more) << "Resolving a service dependency."; - log_v2::config()->debug("Resolving a service dependency."); + config_logger->debug("Resolving a service dependency."); // Find service dependency. servicedependency_mmap::iterator it( diff --git a/engine/src/configuration/applier/serviceescalation.cc b/engine/src/configuration/applier/serviceescalation.cc index df15c12bae1..1cf4309b7e7 100644 --- a/engine/src/configuration/applier/serviceescalation.cc +++ b/engine/src/configuration/applier/serviceescalation.cc @@ -1,21 +1,39 @@ /** -* Copyright 2011-2019 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ + +/** + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/configuration/applier/serviceescalation.hh" #include "com/centreon/engine/broker.hh" @@ -23,7 +41,6 @@ #include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" using namespace com::centreon::engine::configuration; @@ -56,9 +73,8 @@ void applier::serviceescalation::add_object( << "Creating new escalation for service '" << obj.service_description().front() << "' of host '" << obj.hosts().front() << "'"; - log_v2::config()->debug( - "Creating new escalation for service '{}' of host '{}'", - obj.service_description().front(), obj.hosts().front()); + config_logger->debug("Creating new escalation for service '{}' of host '{}'", + obj.service_description().front(), obj.hosts().front()); // Add escalation to the global configuration set. config->serviceescalations().insert(obj); @@ -110,7 +126,7 @@ void applier::serviceescalation::expand_objects(configuration::state& s) { // Browse all escalations. engine_logger(logging::dbg_config, logging::more) << "Expanding service escalations"; - log_v2::config()->debug("Expanding service escalations"); + config_logger->debug("Expanding service escalations"); configuration::set_serviceescalation expanded; for (configuration::set_serviceescalation::const_iterator @@ -175,7 +191,7 @@ void applier::serviceescalation::remove_object( // Logging. engine_logger(logging::dbg_config, logging::more) << "Removing a service escalation."; - log_v2::config()->debug("Removing a service escalation."); + config_logger->debug("Removing a service escalation."); // Find service escalation. std::string const& host_name{obj.hosts().front()}; @@ -194,8 +210,8 @@ void applier::serviceescalation::remove_object( engine_logger(logging::dbg_config, logging::more) << "Cannot find service '" << host_name << "/" << description << "' - already removed."; - log_v2::config()->debug("Cannot find service '{}/{}' - already removed.", - host_name, description); + config_logger->debug("Cannot find service '{}/{}' - already removed.", + host_name, description); service_exists = false; } else service_exists = true; @@ -215,7 +231,7 @@ void applier::serviceescalation::remove_object( engine_logger(logging::dbg_config, logging::more) << "Service '" << host_name << "/" << description << "' found - removing escalation from it."; - log_v2::config()->debug( + config_logger->debug( "Service '{}/{}' found - removing escalation from it.", host_name, description); std::list& srv_escalations(sit->second->get_escalations()); @@ -251,7 +267,7 @@ void applier::serviceescalation::resolve_object( // Logging. engine_logger(logging::dbg_config, logging::more) << "Resolving a service escalation."; - log_v2::config()->debug("Resolving a service escalation."); + config_logger->debug("Resolving a service escalation."); // Find service escalation bool found{false}; diff --git a/engine/src/configuration/applier/servicegroup.cc b/engine/src/configuration/applier/servicegroup.cc index 5c2d6c1574c..2f18c2ae047 100644 --- a/engine/src/configuration/applier/servicegroup.cc +++ b/engine/src/configuration/applier/servicegroup.cc @@ -1,21 +1,21 @@ /** -* Copyright 2011-2013,2015,2017 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2013,2015,2017-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include "com/centreon/engine/configuration/applier/servicegroup.hh" #include "com/centreon/engine/broker.hh" @@ -23,7 +23,6 @@ #include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" using namespace com::centreon::engine::configuration; @@ -70,8 +69,8 @@ void applier::servicegroup::add_object(configuration::servicegroup const& obj) { // Logging. engine_logger(logging::dbg_config, logging::more) << "Creating new servicegroup '" << obj.servicegroup_name() << "'"; - log_v2::config()->debug("Creating new servicegroup '{}'", - obj.servicegroup_name()); + config_logger->debug("Creating new servicegroup '{}'", + obj.servicegroup_name()); // Add service group to the global configuration set. config->servicegroups().insert(obj); @@ -129,8 +128,7 @@ void applier::servicegroup::modify_object( // Logging. engine_logger(logging::dbg_config, logging::more) << "Modifying servicegroup '" << obj.servicegroup_name() << "'"; - log_v2::config()->debug("Modifying servicegroup '{}'", - obj.servicegroup_name()); + config_logger->debug("Modifying servicegroup '{}'", obj.servicegroup_name()); // Find old configuration. set_servicegroup::iterator it_cfg(config->servicegroups_find(obj.key())); @@ -193,8 +191,7 @@ void applier::servicegroup::remove_object( // Logging. engine_logger(logging::dbg_config, logging::more) << "Removing servicegroup '" << obj.servicegroup_name() << "'"; - log_v2::config()->debug("Removing servicegroup '{}'", - obj.servicegroup_name()); + config_logger->debug("Removing servicegroup '{}'", obj.servicegroup_name()); // Find service group. servicegroup_map::iterator it{ @@ -221,8 +218,7 @@ void applier::servicegroup::resolve_object( // Logging. engine_logger(logging::dbg_config, logging::more) << "Removing service group '" << obj.servicegroup_name() << "'"; - log_v2::config()->debug("Removing service group '{}'", - obj.servicegroup_name()); + config_logger->debug("Removing service group '{}'", obj.servicegroup_name()); // Find service group. servicegroup_map::const_iterator it{ @@ -250,8 +246,8 @@ void applier::servicegroup::_resolve_members( engine_logger(logging::dbg_config, logging::more) << "Resolving members of service group '" << obj.servicegroup_name() << "'"; - log_v2::config()->debug("Resolving members of service group '{}'", - obj.servicegroup_name()); + config_logger->debug("Resolving members of service group '{}'", + obj.servicegroup_name()); // Mark object as resolved. configuration::servicegroup& resolved_obj(_resolved[obj.key()]); diff --git a/engine/src/configuration/applier/severity.cc b/engine/src/configuration/applier/severity.cc index 872be285e0e..04be7930374 100644 --- a/engine/src/configuration/applier/severity.cc +++ b/engine/src/configuration/applier/severity.cc @@ -1,5 +1,5 @@ /** - * Copyright 2022 Centreon (https://www.centreon.com/) + * Copyright 2022-2024 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,6 @@ #include "com/centreon/engine/configuration/severity.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/severity.hh" using namespace com::centreon; @@ -38,8 +37,8 @@ using namespace com::centreon::engine::configuration; */ void applier::severity::add_object(const configuration::severity& obj) { // Logging. - log_v2::config()->debug("Creating new severity ({}, {}).", obj.key().first, - obj.key().second); + config_logger->debug("Creating new severity ({}, {}).", obj.key().first, + obj.key().second); // Add severity to the global configuration set. config->mut_severities().insert(obj); @@ -74,8 +73,8 @@ void applier::severity::expand_objects(configuration::state&) {} */ void applier::severity::modify_object(const configuration::severity& obj) { // Logging. - log_v2::config()->debug("Modifying severity ({}, {}).", obj.key().first, - obj.key().second); + config_logger->debug("Modifying severity ({}, {}).", obj.key().first, + obj.key().second); // Find old configuration. auto it_cfg = config->severities_find(obj.key()); @@ -104,8 +103,8 @@ void applier::severity::modify_object(const configuration::severity& obj) { // Notify event broker. broker_adaptive_severity_data(NEBTYPE_SEVERITY_UPDATE, s); } else - log_v2::config()->debug("Severity ({}, {}) did not change", obj.key().first, - obj.key().second); + config_logger->debug("Severity ({}, {}) did not change", obj.key().first, + obj.key().second); } /** @@ -115,8 +114,8 @@ void applier::severity::modify_object(const configuration::severity& obj) { */ void applier::severity::remove_object(const configuration::severity& obj) { // Logging. - log_v2::config()->debug("Removing severity ({}, {}).", obj.key().first, - obj.key().second); + config_logger->debug("Removing severity ({}, {}).", obj.key().first, + obj.key().second); // Find severity. severity_map::iterator it = engine::severity::severities.find(obj.key()); diff --git a/engine/src/configuration/applier/state.cc b/engine/src/configuration/applier/state.cc index ff8ae42e7cd..dcf62c66ff0 100644 --- a/engine/src/configuration/applier/state.cc +++ b/engine/src/configuration/applier/state.cc @@ -1,26 +1,24 @@ /** - * Copyright 2011-2020 Centreon + * Copyright 2011-2024 Centreon * - * This file is part of Centreon Engine. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Centreon Engine is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License version 2 - * as published by the Free Software Foundation. + * http://www.apache.org/licenses/LICENSE-2.0 * - * Centreon Engine is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com * - * You should have received a copy of the GNU General Public License - * along with Centreon Engine. If not, see - * . */ #include "com/centreon/engine/configuration/applier/state.hh" -#include "com/centreon/engine/log_v2.hh" - #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/commands/connector.hh" #include "com/centreon/engine/config.hh" @@ -49,6 +47,7 @@ #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" #include "com/centreon/engine/logging.hh" +#include "com/centreon/engine/logging/broker_sink.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/objects.hh" #include "com/centreon/engine/retention/applier/state.hh" @@ -56,11 +55,14 @@ #include "com/centreon/engine/version.hh" #include "com/centreon/engine/xpddefault.hh" #include "com/centreon/engine/xsddefault.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon; using namespace com::centreon::engine; using namespace com::centreon::engine::configuration; using namespace com::centreon::engine::logging; +using com::centreon::common::log_v2::log_v2; +using com::centreon::engine::logging::broker_sink_mt; static bool has_already_been_loaded(false); @@ -84,15 +86,14 @@ void applier::state::apply(configuration::state& new_cfg) { // If is not the first time, we can restore the old one. engine_logger(log_config_error, basic) << "Error: Could not apply new configuration: " << e.what(); - log_v2::config()->error("Error: Could not apply new configuration: {}", - e.what()); + config_logger->error("Error: Could not apply new configuration: {}", + e.what()); // Check if we need to restore old configuration. if (_processing_state == state_error) { engine_logger(dbg_config, more) << "configuration: try to restore old configuration"; - log_v2::config()->debug( - "configuration: try to restore old configuration"); + config_logger->debug("configuration: try to restore old configuration"); _processing(save); } } @@ -119,14 +120,13 @@ void applier::state::apply(configuration::state& new_cfg, // If is not the first time, we can restore the old one. engine_logger(log_config_error, basic) << "Cannot apply new configuration: " << e.what(); - log_v2::config()->error("Cannot apply new configuration: {}", e.what()); + config_logger->error("Cannot apply new configuration: {}", e.what()); // Check if we need to restore old configuration. if (_processing_state == state_error) { engine_logger(dbg_config, more) << "configuration: try to restore old configuration"; - log_v2::config()->debug( - "configuration: try to restore old configuration"); + config_logger->debug("configuration: try to restore old configuration"); _processing(save, &state); } } @@ -250,7 +250,7 @@ void applier::state::_apply(configuration::state const& new_cfg) { if (config->broker_module() != new_cfg.broker_module()) { engine_logger(log_config_warning, basic) << "Warning: Broker modules cannot be changed nor reloaded"; - log_v2::config()->warn( + config_logger->warn( "Warning: Broker modules cannot be changed nor reloaded"); ++config_warnings; } @@ -258,28 +258,27 @@ void applier::state::_apply(configuration::state const& new_cfg) { new_cfg.broker_module_directory()) { engine_logger(log_config_warning, basic) << "Warning: Broker module directory cannot be changed"; - log_v2::config()->warn( - "Warning: Broker module directory cannot be changed"); + config_logger->warn("Warning: Broker module directory cannot be changed"); ++config_warnings; } if (config->command_file() != new_cfg.command_file()) { engine_logger(log_config_warning, basic) << "Warning: Command file cannot be changed"; - log_v2::config()->warn("Warning: Command file cannot be changed"); + config_logger->warn("Warning: Command file cannot be changed"); ++config_warnings; } if (config->external_command_buffer_slots() != new_cfg.external_command_buffer_slots()) { engine_logger(log_config_warning, basic) << "Warning: External command buffer slots cannot be changed"; - log_v2::config()->warn( + config_logger->warn( "Warning: External command buffer slots cannot be changed"); ++config_warnings; } if (config->use_timezone() != new_cfg.use_timezone()) { engine_logger(log_config_warning, basic) << "Warning: Timezone can not be changed"; - log_v2::config()->warn("Warning: Timezone can not be changed"); + config_logger->warn("Warning: Timezone can not be changed"); ++config_warnings; } } @@ -483,7 +482,7 @@ void applier::state::_apply(configuration::state const& new_cfg) { if (verify_config) { engine_logger(log_info_message, basic) << "Checking global event handlers..."; - log_v2::events()->info("Checking global event handlers..."); + events_logger->info("Checking global event handlers..."); } if (!config->global_host_event_handler().empty()) { // Check the event handler command. @@ -495,7 +494,7 @@ void applier::state::_apply(configuration::state const& new_cfg) { engine_logger(log_verification_error, basic) << "Error: Global host event handler command '" << temp_command_name << "' is not defined anywhere!"; - log_v2::config()->error( + config_logger->error( "Error: Global host event handler command '{}' is not defined " "anywhere!", temp_command_name); @@ -514,7 +513,7 @@ void applier::state::_apply(configuration::state const& new_cfg) { engine_logger(log_verification_error, basic) << "Error: Global service event handler command '" << temp_command_name << "' is not defined anywhere!"; - log_v2::config()->error( + config_logger->error( "Error: Global service event handler command '{}' is not defined " "anywhere!", temp_command_name); @@ -528,8 +527,7 @@ void applier::state::_apply(configuration::state const& new_cfg) { if (verify_config) { engine_logger(log_info_message, basic) << "Checking obsessive compulsive processor commands..."; - log_v2::events()->info( - "Checking obsessive compulsive processor commands..."); + events_logger->info("Checking obsessive compulsive processor commands..."); } if (!config->ocsp_command().empty()) { std::string temp_command_name(config->ocsp_command().substr( @@ -540,7 +538,7 @@ void applier::state::_apply(configuration::state const& new_cfg) { engine_logger(log_verification_error, basic) << "Error: Obsessive compulsive service processor command '" << temp_command_name << "' is not defined anywhere!"; - log_v2::config()->error( + config_logger->error( "Error: Obsessive compulsive service processor command '{}' is not " "defined anywhere!", temp_command_name); @@ -558,7 +556,7 @@ void applier::state::_apply(configuration::state const& new_cfg) { engine_logger(log_verification_error, basic) << "Error: Obsessive compulsive host processor command '" << temp_command_name << "' is not defined anywhere!"; - log_v2::config()->error( + config_logger->error( "Error: Obsessive compulsive host processor command '{}' is not " "defined anywhere!", temp_command_name); @@ -605,7 +603,7 @@ void applier::state::_apply( } catch (std::exception const& e) { ++config_errors; engine_logger(log_info_message, basic) << e.what(); - log_v2::events()->info(e.what()); + events_logger->info(e.what()); } } } @@ -622,7 +620,7 @@ void applier::state::_apply( } catch (std::exception const& e) { ++config_errors; engine_logger(log_info_message, basic) << e.what(); - log_v2::events()->info(e.what()); + events_logger->info(e.what()); } } } @@ -639,7 +637,7 @@ void applier::state::_apply( } catch (std::exception const& e) { ++config_errors; engine_logger(log_info_message, basic) << e.what(); - log_v2::events()->info(e.what()); + events_logger->info(e.what()); } } } @@ -671,7 +669,7 @@ void applier::state::_check_serviceescalations() const { << "Error on serviceescalation !!! The service " << srv->get_hostname() << "/" << srv->get_description() << " contains a non existing service escalation"; - log_v2::config()->error( + config_logger->error( "Error on serviceescalation !!! The service {}/{} contains a non " "existing service escalation", srv->get_hostname(), srv->get_description()); @@ -685,7 +683,7 @@ void applier::state::_check_serviceescalations() const { << srv->get_hostname() << "/" << srv->get_description() << "set size: " << s.size() << " ; list size: " << srv->get_escalations().size(); - log_v2::config()->error( + config_logger->error( "Error on serviceescalation !!! Some escalations are stored " "several times in service {}/{} set size: {} ; list size: {}", srv->get_hostname(), srv->get_description(), s.size(), @@ -708,7 +706,7 @@ void applier::state::_check_serviceescalations() const { << "Host name given by the escalation is " << se->get_hostname() << " whereas the hostname from the notifier is " << p.second->get_hostname() << "."; - log_v2::config()->error( + config_logger->error( "Error on serviceescalation !!! The notifier seen by the " "escalation is wrong. Host name given by the escalation is {} " "whereas the hostname from the notifier is {}.", @@ -723,7 +721,7 @@ void applier::state::_check_serviceescalations() const { << se->get_description() << " whereas the service description from the notifier is " << p.second->get_description() << "."; - log_v2::config()->error( + config_logger->error( "Error on serviceescalation !!! The notifier seen by the " "escalation is wrong. Service description given by the " "escalation is {} whereas the service description from the " @@ -740,7 +738,7 @@ void applier::state::_check_serviceescalations() const { "escalation is wrong " << "The bug is detected on escalation concerning host " << se->get_hostname() << " and service " << se->get_description(); - log_v2::config()->error( + config_logger->error( "Error on serviceescalation !!! The notifier seen by the " "escalation is wrong The bug is detected on escalation concerning " "host {} and service {}", @@ -772,7 +770,7 @@ void applier::state::_check_hostescalations() const { engine_logger(log_config_error, basic) << "Error on hostescalation !!! The host " << hst->get_name() << " contains a non existing host escalation"; - log_v2::config()->error( + config_logger->error( "Error on hostescalation !!! The host {} contains a non existing " "host escalation", hst->get_name()); @@ -795,7 +793,7 @@ void applier::state::_check_hostescalations() const { << "Host name given by the escalation is " << he->get_hostname() << " whereas the hostname from the notifier is " << p.second->get_name() << "."; - log_v2::config()->error( + config_logger->error( "Error on hostescalation !!! The notifier seen by the escalation " "is wrong. Host name given by the escalation is {} whereas the " "hostname from the notifier is {}.", @@ -811,7 +809,7 @@ void applier::state::_check_hostescalations() const { "is wrong " << "The bug is detected on escalation concerning host " << he->get_hostname(); - log_v2::config()->error( + config_logger->error( "Error on hostescalation !!! The notifier seen by the escalation is " "wrong The bug is detected on escalation concerning host {}", he->get_hostname()); @@ -837,7 +835,7 @@ void applier::state::_check_contacts() const { << "Error on contact !!! The contact " << pp.first << " used in contactgroup " << p.first << " is not or badly defined"; - log_v2::config()->error( + config_logger->error( "Error on contact !!! The contact {} used in contactgroup {} is " "not or badly defined", pp.first, p.first); @@ -855,7 +853,7 @@ void applier::state::_check_contacts() const { << "Error on contact !!! The contact " << pp.first << " used in service " << p.second->get_hostname() << '/' << p.second->get_description() << " is not or badly defined"; - log_v2::config()->error( + config_logger->error( "Error on contact !!! The contact {} used in service {}/{} is not " "or badly defined", pp.first, p.second->get_hostname(), p.second->get_description()); @@ -873,7 +871,7 @@ void applier::state::_check_contacts() const { << "Error on contact !!! The contact " << pp.first << " used in service " << p.second->get_name() << " is not or badly defined"; - log_v2::config()->error( + config_logger->error( "Error on contact !!! The contact {} used in service {} is not or " "badly defined", pp.first, p.second->get_name()); @@ -901,7 +899,7 @@ void applier::state::_check_contactgroups() const { << "Error on contactgroup !!! The contactgroup " << pp.first << " used in service " << p.first.first << '/' << p.first.second << " is not or badly defined"; - log_v2::config()->error( + config_logger->error( "Error on contactgroup !!! The contactgroup {} used in service " "{}/{} is not or badly defined", pp.first, p.first.first, p.first.second); @@ -919,7 +917,7 @@ void applier::state::_check_contactgroups() const { engine_logger(log_config_error, basic) << "Error on contactgroup !!! The contactgroup " << pp.first << " used in host " << p.first << " is not or badly defined"; - log_v2::config()->error( + config_logger->error( "Error on contactgroup !!! The contactgroup {} used in host {} is " "not or badly defined", pp.first, p.first); @@ -938,7 +936,7 @@ void applier::state::_check_contactgroups() const { << "Error on contactgroup !!! The contactgroup " << pp.first << " used in serviceescalation " << p.second->get_uuid().to_string() << " is not or badly defined"; - log_v2::config()->error( + config_logger->error( "Error on contactgroup !!! The contactgroup {} used in " "serviceescalation {} is not or badly defined", pp.first, p.second->get_uuid().to_string()); @@ -957,7 +955,7 @@ void applier::state::_check_contactgroups() const { << "Error on contactgroup !!! The contactgroup " << pp.first << " used in hostescalation " << p.second->get_uuid().to_string() << " is not or badly defined"; - log_v2::config()->error( + config_logger->error( "Error on contactgroup !!! The contactgroup {} used in " "hostescalation {} is not or badly defined", pp.first, p.second->get_uuid().to_string()); @@ -987,7 +985,7 @@ void applier::state::_check_services() const { << "Error on service !!! The service " << p.first.first << '/' << p.first.second << " used in service dependency " << p.first.first << '/' << p.first.second << " is not or badly defined"; - log_v2::config()->error( + config_logger->error( "Error on service !!! The service {}/{} used in service dependency " "{}/{} is not or badly defined", p.first.first, p.first.second, p.first.first, p.first.second); @@ -1005,7 +1003,7 @@ void applier::state::_check_services() const { << "Error on service !!! The service " << p.first.first << '/' << p.first.second << " defined in services is not defined in services_by_id"; - log_v2::config()->error( + config_logger->error( "Error on service !!! The service {}/{} defined in services is not " "defined in services_by_id", p.first.first, p.first.second); @@ -1032,7 +1030,7 @@ void applier::state::_check_services() const { << "Error on service !!! The service " << p.first.first << '/' << p.first.second << " defined in services has a wrong check command"; - log_v2::config()->error( + config_logger->error( "Error on service !!! The service {}/{} defined in services has " "a wrong check command", p.first.first, p.first.second); @@ -1049,7 +1047,7 @@ void applier::state::_check_services() const { "services. The first one size is " << engine::service::services.size() << " the second size is " << engine::service::services.size(); - log_v2::config()->error( + config_logger->error( "Error on service !!! services_by_id contains ices that are not in " "services. The first one size is {} the second size is {}", engine::service::services.size(), engine::service::services.size()); @@ -1071,7 +1069,7 @@ void applier::state::_check_hosts() const { engine_logger(log_config_error, basic) << "Error on host !!! The host " << hst->get_name() << " used in " << where << " is not defined or badly defined in hosts"; - log_v2::config()->error( + config_logger->error( "Error on host !!! The host {} used in {} is not defined or badly " "defined in hosts", hst->get_name(), where); @@ -1108,7 +1106,7 @@ void applier::state::_check_hosts() const { engine_logger(log_config_error, basic) << "Error on host !!! The host " << p.first << " defined in hosts has a wrong check command"; - log_v2::config()->error( + config_logger->error( "Error on host !!! The host {} defined in hosts has a wrong " "check command", p.first); @@ -1124,7 +1122,7 @@ void applier::state::_check_hosts() const { "hosts. The first one size is " << engine::service::services.size() << " whereas the second size is " << engine::service::services.size(); - log_v2::config()->error( + config_logger->error( "Error on host !!! hosts_by_id contains hosts that are not in " "hosts. The first one size is {} whereas the second size is {}", engine::service::services.size(), engine::service::services.size()); @@ -1137,6 +1135,69 @@ void applier::state::_check_hosts() const { #endif +void applier::state::apply_log_config(configuration::state& new_cfg) { + using log_v2_config = com::centreon::common::log_v2::config; + log_v2_config::logger_type log_type; + if (new_cfg.log_v2_enabled()) { + if (new_cfg.log_v2_logger() == "file") { + if (!new_cfg.log_file().empty()) + log_type = log_v2_config::logger_type::LOGGER_FILE; + else + log_type = log_v2_config::logger_type::LOGGER_STDOUT; + } else + log_type = log_v2_config::logger_type::LOGGER_SYSLOG; + + log_v2_config log_cfg("centengine", log_type, new_cfg.log_flush_period(), + new_cfg.log_pid(), new_cfg.log_file_line()); + if (log_type == log_v2_config::logger_type::LOGGER_FILE) { + log_cfg.set_log_path(new_cfg.log_file()); + log_cfg.set_max_size(new_cfg.max_log_file_size()); + } + auto broker_sink = std::make_shared(); + broker_sink->set_level(spdlog::level::info); + log_cfg.add_custom_sink(broker_sink); + + log_cfg.apply_custom_sinks({"functions", "config", "events", "checks", + "notifications", "eventbroker", + "external_command", "commands", "downtimes", + "comments", "macros", "process", "runtime"}); + log_cfg.set_level("functions", new_cfg.log_level_functions()); + log_cfg.set_level("config", new_cfg.log_level_config()); + log_cfg.set_level("events", new_cfg.log_level_events()); + log_cfg.set_level("checks", new_cfg.log_level_checks()); + log_cfg.set_level("notifications", new_cfg.log_level_notifications()); + log_cfg.set_level("eventbroker", new_cfg.log_level_eventbroker()); + log_cfg.set_level("external_command", new_cfg.log_level_external_command()); + log_cfg.set_level("commands", new_cfg.log_level_commands()); + log_cfg.set_level("downtimes", new_cfg.log_level_downtimes()); + log_cfg.set_level("comments", new_cfg.log_level_comments()); + log_cfg.set_level("macros", new_cfg.log_level_macros()); + log_cfg.set_level("process", new_cfg.log_level_process()); + log_cfg.set_level("runtime", new_cfg.log_level_runtime()); + if (has_already_been_loaded) + log_cfg.allow_only_atomic_changes(true); + log_v2::instance().apply(log_cfg); + } else { + if (!new_cfg.log_file().empty()) + log_type = log_v2_config::logger_type::LOGGER_FILE; + else + log_type = log_v2_config::logger_type::LOGGER_STDOUT; + log_v2_config log_cfg("centengine", log_type, new_cfg.log_flush_period(), + new_cfg.log_pid(), new_cfg.log_file_line()); + if (!new_cfg.log_file().empty()) { + log_cfg.set_log_path(new_cfg.log_file()); + log_cfg.set_max_size(new_cfg.max_log_file_size()); + } + log_v2::instance().apply(log_cfg); + log_v2::instance().disable( + {log_v2::CORE, log_v2::CONFIG, log_v2::PROCESS, log_v2::FUNCTIONS, + log_v2::EVENTS, log_v2::CHECKS, log_v2::NOTIFICATIONS, + log_v2::EVENTBROKER, log_v2::EXTERNAL_COMMAND, log_v2::COMMANDS, + log_v2::DOWNTIMES, log_v2::COMMENTS, log_v2::MACROS, log_v2::RUNTIME}); + } + init_loggers(); +} + /** * Apply retention. * @@ -1325,7 +1386,7 @@ void applier::state::_processing(configuration::state& new_cfg, applier::logging::instance().apply(new_cfg); - log_v2::instance()->apply(new_cfg); + apply_log_config(new_cfg); // Apply globals configurations. applier::globals::instance().apply(new_cfg); @@ -1342,16 +1403,16 @@ void applier::state::_processing(configuration::state& new_cfg, engine_logger(log_process_info, basic) << "Centreon Engine " << CENTREON_ENGINE_VERSION_STRING << " starting ... (PID=" << getpid() << ")"; - log_v2::process()->info("Centreon Engine {} starting ... (PID={})", - CENTREON_ENGINE_VERSION_STRING, getpid()); + process_logger->info("Centreon Engine {} starting ... (PID={})", + CENTREON_ENGINE_VERSION_STRING, getpid()); // Log the local time - may be different than clock // time due to timezone offset. engine_logger(log_process_info, basic) << "Local time is " << string::ctime(program_start) << "\n" << "LOG VERSION: " << LOG_VERSION_2; - log_v2::process()->info("Local time is {}", string::ctime(program_start)); - log_v2::process()->info("LOG VERSION: {}", LOG_VERSION_2); + process_logger->info("Local time is {}", string::ctime(program_start)); + process_logger->info("LOG VERSION: {}", LOG_VERSION_2); } // @@ -1473,7 +1534,7 @@ void applier::state::_processing(configuration::state& new_cfg, } catch (std::exception const& e) { ++config_errors; engine_logger(log_info_message, basic) << e.what(); - log_v2::events()->info(e.what()); + events_logger->info(e.what()); } } diff --git a/engine/src/configuration/applier/tag.cc b/engine/src/configuration/applier/tag.cc index abeb947305f..182515f6a52 100644 --- a/engine/src/configuration/applier/tag.cc +++ b/engine/src/configuration/applier/tag.cc @@ -1,5 +1,5 @@ /** - * Copyright 2022 Centreon (https://www.centreon.com/) + * Copyright 2022-2024 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,6 @@ #include "com/centreon/engine/configuration/tag.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/tag.hh" using namespace com::centreon; @@ -38,8 +37,8 @@ using namespace com::centreon::engine::configuration; */ void applier::tag::add_object(const configuration::tag& obj) { // Logging. - log_v2::config()->debug("Creating new tag ({},{}).", obj.key().first, - obj.key().second); + config_logger->debug("Creating new tag ({},{}).", obj.key().first, + obj.key().second); // Add tag to the global configuration set. config->mut_tags().insert(obj); @@ -54,7 +53,7 @@ void applier::tag::add_object(const configuration::tag& obj) { // Add new items to the configuration state. auto res = engine::tag::tags.insert({obj.key(), tg}); if (!res.second) - log_v2::config()->error( + config_logger->error( "Could not insert tag ({},{}) into cache because it already exists", obj.key().first, obj.key().second); @@ -78,8 +77,8 @@ void applier::tag::expand_objects(configuration::state&) {} */ void applier::tag::modify_object(const configuration::tag& obj) { // Logging. - log_v2::config()->debug("Modifying tag ({},{}).", obj.key().first, - obj.key().second); + config_logger->debug("Modifying tag ({},{}).", obj.key().first, + obj.key().second); // Find old configuration. auto it_cfg = config->tags_find(obj.key()); @@ -107,8 +106,8 @@ void applier::tag::modify_object(const configuration::tag& obj) { // Notify event broker. broker_adaptive_tag_data(NEBTYPE_TAG_UPDATE, t); } else - log_v2::config()->debug("Tag ({},{}) did not change", obj.key().first, - obj.key().second); + config_logger->debug("Tag ({},{}) did not change", obj.key().first, + obj.key().second); } /** @@ -118,8 +117,8 @@ void applier::tag::modify_object(const configuration::tag& obj) { */ void applier::tag::remove_object(const configuration::tag& obj) { // Logging. - log_v2::config()->debug("Removing tag ({},{}).", obj.key().first, - obj.key().second); + config_logger->debug("Removing tag ({},{}).", obj.key().first, + obj.key().second); // Find tag. tag_map::iterator it = diff --git a/engine/src/configuration/applier/timeperiod.cc b/engine/src/configuration/applier/timeperiod.cc index f05a5ed3329..74338ac5c39 100644 --- a/engine/src/configuration/applier/timeperiod.cc +++ b/engine/src/configuration/applier/timeperiod.cc @@ -1,21 +1,22 @@ /** -* Copyright 2011-2013,2017 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2013,2017-2024 Centreon + * Copyright 2017 - 2024 Centreon (https://www.centreon.com/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include "com/centreon/engine/configuration/applier/timeperiod.hh" #include "com/centreon/engine/broker.hh" @@ -24,7 +25,6 @@ #include "com/centreon/engine/deleter/listmember.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" using namespace com::centreon::engine::configuration; @@ -67,8 +67,7 @@ void applier::timeperiod::add_object(configuration::timeperiod const& obj) { // Logging. engine_logger(logging::dbg_config, logging::more) << "Creating new time period '" << obj.timeperiod_name() << "'."; - log_v2::config()->debug("Creating new time period '{}'.", - obj.timeperiod_name()); + config_logger->debug("Creating new time period '{}'.", obj.timeperiod_name()); // Add time period to the global configuration set. config->timeperiods().insert(obj); @@ -111,7 +110,7 @@ void applier::timeperiod::modify_object(configuration::timeperiod const& obj) { // Logging. engine_logger(logging::dbg_config, logging::more) << "Modifying time period '" << obj.timeperiod_name() << "'."; - log_v2::config()->debug("Modifying time period '{}'.", obj.timeperiod_name()); + config_logger->debug("Modifying time period '{}'.", obj.timeperiod_name()); // Find old configuration. set_timeperiod::iterator it_cfg(config->timeperiods_find(obj.key())); @@ -170,7 +169,7 @@ void applier::timeperiod::remove_object(configuration::timeperiod const& obj) { // Logging. engine_logger(logging::dbg_config, logging::more) << "Removing time period '" << obj.timeperiod_name() << "'."; - log_v2::config()->debug("Removing time period '{}'.", obj.timeperiod_name()); + config_logger->debug("Removing time period '{}'.", obj.timeperiod_name()); // Find time period. timeperiod_map::iterator it(engine::timeperiod::timeperiods.find(obj.key())); @@ -201,7 +200,7 @@ void applier::timeperiod::resolve_object(configuration::timeperiod const& obj) { // Logging. engine_logger(logging::dbg_config, logging::more) << "Resolving time period '" << obj.timeperiod_name() << "'."; - log_v2::config()->debug("Resolving time period '{}'.", obj.timeperiod_name()); + config_logger->debug("Resolving time period '{}'.", obj.timeperiod_name()); // Find time period. timeperiod_map::iterator it{engine::timeperiod::timeperiods.find(obj.key())}; diff --git a/engine/src/configuration/extended_conf.cc b/engine/src/configuration/extended_conf.cc index bb0cbd846eb..49d686dbd01 100644 --- a/engine/src/configuration/extended_conf.cc +++ b/engine/src/configuration/extended_conf.cc @@ -18,6 +18,7 @@ #include "com/centreon/engine/configuration/extended_conf.hh" #include "com/centreon/engine/configuration/state.hh" +#include "com/centreon/engine/globals.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon::engine::configuration; @@ -32,15 +33,15 @@ std::list> extended_conf::_confs; */ extended_conf::extended_conf(const std::string& path) : _path(path) { if (::stat(_path.c_str(), &_file_info)) { - SPDLOG_LOGGER_ERROR(log_v2::config(), "can't access to {}", _path); + SPDLOG_LOGGER_ERROR(config_logger, "can't access to {}", _path); throw exceptions::msg_fmt("can't access to {}", _path); } try { _content = common::rapidjson_helper::read_from_file(_path); - SPDLOG_LOGGER_INFO(log_v2::config(), "extended conf file {} loaded", _path); + SPDLOG_LOGGER_INFO(config_logger, "extended conf file {} loaded", _path); } catch (const std::exception& e) { SPDLOG_LOGGER_ERROR( - log_v2::config(), + config_logger, "extended_conf::extended_conf : fail to read json content from {}: {}", _path, e.what()); throw; @@ -56,7 +57,7 @@ extended_conf::extended_conf(const std::string& path) : _path(path) { void extended_conf::reload() { struct stat file_info; if (::stat(_path.c_str(), &file_info)) { - SPDLOG_LOGGER_ERROR(log_v2::config(), + SPDLOG_LOGGER_ERROR(config_logger, "can't access to {} anymore => we keep old content", _path); return; @@ -68,7 +69,7 @@ void extended_conf::reload() { _content = common::rapidjson_helper::read_from_file(_path); _file_info = file_info; } catch (const std::exception& e) { - SPDLOG_LOGGER_ERROR(log_v2::config(), + SPDLOG_LOGGER_ERROR(config_logger, "extended_conf::extended_conf : fail to read json " "content from {} => we keep old content, cause: {}", _path, e.what()); diff --git a/engine/src/configuration/host.cc b/engine/src/configuration/host.cc index 054e0a80064..43b0cdb6ef5 100644 --- a/engine/src/configuration/host.cc +++ b/engine/src/configuration/host.cc @@ -1,21 +1,22 @@ /** -* Copyright 2011-2013,2015-2017,2019,2022 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2013,2015-2017,2019,2022-2024 Centreon + * Copyright 2017 - 2024 Centreon (https://www.centreon.com/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include "com/centreon/engine/configuration/host.hh" #include "absl/strings/numbers.h" @@ -23,8 +24,8 @@ #include "absl/strings/string_view.h" #include "com/centreon/engine/configuration/hostextinfo.hh" #include "com/centreon/engine/exceptions/error.hh" +#include "com/centreon/engine/globals.hh" #include "com/centreon/engine/host.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/string.hh" @@ -1291,7 +1292,7 @@ bool host::_set_failure_prediction_enabled(bool value) { engine_logger(log_verification_error, basic) << "Warning: host failure_prediction_enabled is deprecated" << " This option will not be supported in 20.04."; - log_v2::config()->warn( + config_logger->warn( "Warning: host failure_prediction_enabled is deprecated This option will " "not be supported in 20.04."); ++config_warnings; @@ -1310,7 +1311,7 @@ bool host::_set_failure_prediction_options(std::string const& value) { engine_logger(log_verification_error, basic) << "Warning: service failure_prediction_options is deprecated" << " This option will not be supported in 20.04."; - log_v2::config()->warn( + config_logger->warn( "Warning: service failure_prediction_options is deprecated This option " "will not be supported in 20.04."); ++config_warnings; @@ -1763,8 +1764,8 @@ bool host::_set_category_tags(const std::string& value) { if (parse_ok) { _tags.emplace(id, tag::hostcategory); } else { - log_v2::config()->warn("Warning: host ({}) error for parsing tag {}", - _host_id, value); + config_logger->warn("Warning: host ({}) error for parsing tag {}", + _host_id, value); ret = false; } } @@ -1797,8 +1798,8 @@ bool host::_set_group_tags(const std::string& value) { if (parse_ok) { _tags.emplace(id, tag::hostgroup); } else { - log_v2::config()->warn("Warning: host ({}) error for parsing tag {}", - _host_id, value); + config_logger->warn("Warning: host ({}) error for parsing tag {}", + _host_id, value); ret = false; } } diff --git a/engine/src/configuration/hostdependency.cc b/engine/src/configuration/hostdependency.cc index 944da2979b5..158b378384f 100644 --- a/engine/src/configuration/hostdependency.cc +++ b/engine/src/configuration/hostdependency.cc @@ -1,25 +1,26 @@ /** -* Copyright 2011-2013,2015 Merethis -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2013,2015 Merethis + * Copyright 2017 - 2024 Centreon (https://www.centreon.com/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include "com/centreon/engine/configuration/hostdependency.hh" #include "com/centreon/engine/exceptions/error.hh" -#include "com/centreon/engine/log_v2.hh" +#include "com/centreon/engine/globals.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/string.hh" @@ -199,7 +200,7 @@ void hostdependency::check_validity() const { engine_logger(log_config_warning, basic) << "Warning: Ignoring lame host dependency of '" << dependend_host_name << "' on host/hostgroups '" << host_name << "'."; - log_v2::config()->warn( + config_logger->warn( "Warning: Ignoring lame host dependency of '{}' on host/hostgroups " "'{}'.", dependend_host_name, host_name); diff --git a/engine/src/configuration/hostgroup.cc b/engine/src/configuration/hostgroup.cc index 9d15d76128e..0e09a0b0c24 100644 --- a/engine/src/configuration/hostgroup.cc +++ b/engine/src/configuration/hostgroup.cc @@ -1,25 +1,25 @@ /** -* Copyright 2011-2013,2017 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2013,2017-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include "com/centreon/engine/configuration/hostgroup.hh" #include "com/centreon/engine/exceptions/error.hh" -#include "com/centreon/engine/log_v2.hh" +#include "com/centreon/engine/globals.hh" #include "com/centreon/engine/logging/logger.hh" using namespace com::centreon; @@ -93,56 +93,56 @@ bool hostgroup::operator==(hostgroup const& right) const throw() { if (!object::operator==(right)) { engine_logger(dbg_config, more) << "configuration::hostgroup::equality => object don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::hostgroup::equality => object don't match"); return false; } if (_action_url != right._action_url) { engine_logger(dbg_config, more) << "configuration::hostgroup::equality => action url don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::hostgroup::equality => action url don't match"); return false; } if (_alias != right._alias) { engine_logger(dbg_config, more) << "configuration::hostgroup::equality => alias don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::hostgroup::equality => alias don't match"); return false; } if (_hostgroup_id != right._hostgroup_id) { engine_logger(dbg_config, more) << "configuration::hostgroup::equality => hostgroup id don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::hostgroup::equality => hostgroup id don't match"); return false; } if (_hostgroup_name != right._hostgroup_name) { engine_logger(dbg_config, more) << "configuration::hostgroup::equality => hostgroup name don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::hostgroup::equality => hostgroup name don't match"); return false; } if (_members != right._members) { engine_logger(dbg_config, more) << "configuration::hostgroup::equality => members don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::hostgroup::equality => members don't match"); return false; } if (_notes != right._notes) { engine_logger(dbg_config, more) << "configuration::hostgroup::equality => notes don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::hostgroup::equality => notes don't match"); return false; } if (_notes_url != right._notes_url) { engine_logger(dbg_config, more) << "configuration::hostgroup::equality => notes url don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::hostgroup::equality => notes url don't match"); return false; } diff --git a/engine/src/configuration/parser.cc b/engine/src/configuration/parser.cc index b4dafa2ef0f..f2826e4ce94 100644 --- a/engine/src/configuration/parser.cc +++ b/engine/src/configuration/parser.cc @@ -1,25 +1,25 @@ /** -* Copyright 2011-2014,2017 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2014,2017-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include "com/centreon/engine/configuration/parser.hh" #include "com/centreon/engine/exceptions/error.hh" -#include "com/centreon/engine/log_v2.hh" +#include "com/centreon/engine/globals.hh" #include "com/centreon/engine/string.hh" #include "com/centreon/io/directory_entry.hh" @@ -366,7 +366,7 @@ void parser::_parse_directory_configuration(std::string const& path) { void parser::_parse_global_configuration(std::string const& path) { engine_logger(logging::log_info_message, logging::most) << "Reading main configuration file '" << path << "'."; - log_v2::config()->info("Reading main configuration file '{}'.", path); + config_logger->info("Reading main configuration file '{}'.", path); std::ifstream stream(path.c_str(), std::ios::binary); if (!stream.is_open()) @@ -399,7 +399,7 @@ void parser::_parse_global_configuration(std::string const& path) { void parser::_parse_object_definitions(std::string const& path) { engine_logger(logging::log_info_message, logging::basic) << "Processing object config file '" << path << "'"; - log_v2::config()->info("Processing object config file '{}'", path); + config_logger->info("Processing object config file '{}'", path); std::ifstream stream(path, std::ios::binary); if (!stream.is_open()) @@ -477,7 +477,7 @@ void parser::_parse_object_definitions(std::string const& path) { void parser::_parse_resource_file(std::string const& path) { engine_logger(logging::log_info_message, logging::most) << "Reading resource file '" << path << "'"; - log_v2::config()->info("Reading resource file '{}'", path); + config_logger->info("Reading resource file '{}'", path); std::ifstream stream(path.c_str(), std::ios::binary); if (!stream.is_open()) diff --git a/engine/src/configuration/service.cc b/engine/src/configuration/service.cc index 8aaf297cbb1..c342beee52b 100644 --- a/engine/src/configuration/service.cc +++ b/engine/src/configuration/service.cc @@ -1,21 +1,21 @@ /** -* Copyright 2011-2013,2015-2017,2019,2022 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2013,2015-2017,2019-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include "com/centreon/engine/configuration/service.hh" #include @@ -24,8 +24,8 @@ #include "com/centreon/engine/configuration/serviceextinfo.hh" #include "com/centreon/engine/customvariable.hh" #include "com/centreon/engine/exceptions/error.hh" +#include "com/centreon/engine/globals.hh" #include "com/centreon/engine/host.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/string.hh" @@ -310,14 +310,14 @@ bool service::operator==(service const& other) const noexcept { if (!object::operator==(other)) { engine_logger(dbg_config, more) << "configuration::service::equality => object don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => object don't match"); return false; } if (_acknowledgement_timeout != other._acknowledgement_timeout) { engine_logger(dbg_config, more) << "configuration::service::equality => " "acknowledgement_timeout don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => " "acknowledgement_timeout don't match"); return false; @@ -325,105 +325,105 @@ bool service::operator==(service const& other) const noexcept { if (_action_url != other._action_url) { engine_logger(dbg_config, more) << "configuration::service::equality => action_url don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => action_url don't match"); return false; } if (_checks_active != other._checks_active) { engine_logger(dbg_config, more) << "configuration::service::equality => checks_active don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => checks_active don't match"); return false; } if (_checks_passive != other._checks_passive) { engine_logger(dbg_config, more) << "configuration::service::equality => checks_passive don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => checks_passive don't match"); return false; } if (_check_command != other._check_command) { engine_logger(dbg_config, more) << "configuration::service::equality => checks_passive don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => checks_passive don't match"); return false; } if (_check_command_is_important != other._check_command_is_important) { engine_logger(dbg_config, more) << "configuration::service::equality => check_command don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => check_command don't match"); return false; } if (_check_freshness != other._check_freshness) { engine_logger(dbg_config, more) << "configuration::service::equality => check_freshness don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => check_freshness don't match"); return false; } if (_check_interval != other._check_interval) { engine_logger(dbg_config, more) << "configuration::service::equality => check_interval don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => check_interval don't match"); return false; } if (_check_period != other._check_period) { engine_logger(dbg_config, more) << "configuration::service::equality => check_period don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => check_period don't match"); return false; } if (_contactgroups != other._contactgroups) { engine_logger(dbg_config, more) << "configuration::service::equality => contactgroups don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => contactgroups don't match"); return false; } if (_contacts != other._contacts) { engine_logger(dbg_config, more) << "configuration::service::equality => contacts don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => contacts don't match"); return false; } if (std::operator!=(_customvariables, other._customvariables)) { engine_logger(dbg_config, more) << "configuration::service::equality => customvariables don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => customvariables don't match"); return false; } if (_display_name != other._display_name) { engine_logger(dbg_config, more) << "configuration::service::equality => display_name don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => display_name don't match"); return false; } if (_event_handler != other._event_handler) { engine_logger(dbg_config, more) << "configuration::service::equality => event_handler don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => event_handler don't match"); return false; } if (_event_handler_enabled != other._event_handler_enabled) { engine_logger(dbg_config, more) << "configuration::service::equality => event_handler don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => event_handler don't match"); return false; } if (_first_notification_delay != other._first_notification_delay) { engine_logger(dbg_config, more) << "configuration::service::equality => " "first_notification_delay don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => " "first_notification_delay don't match"); return false; @@ -431,7 +431,7 @@ bool service::operator==(service const& other) const noexcept { if (_flap_detection_enabled != other._flap_detection_enabled) { engine_logger(dbg_config, more) << "configuration::service::equality => " "flap_detection_enabled don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => " "flap_detection_enabled don't match"); return false; @@ -439,7 +439,7 @@ bool service::operator==(service const& other) const noexcept { if (_flap_detection_options != other._flap_detection_options) { engine_logger(dbg_config, more) << "configuration::service::equality => " "flap_detection_options don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => " "flap_detection_options don't match"); return false; @@ -447,7 +447,7 @@ bool service::operator==(service const& other) const noexcept { if (_freshness_threshold != other._freshness_threshold) { engine_logger(dbg_config, more) << "configuration::service::equality => " "freshness_threshold don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => " "freshness_threshold don't match"); return false; @@ -455,7 +455,7 @@ bool service::operator==(service const& other) const noexcept { if (_high_flap_threshold != other._high_flap_threshold) { engine_logger(dbg_config, more) << "configuration::service::equality => " "high_flap_threshold don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => " "high_flap_threshold don't match"); return false; @@ -463,77 +463,77 @@ bool service::operator==(service const& other) const noexcept { if (_hostgroups != other._hostgroups) { engine_logger(dbg_config, more) << "configuration::service::equality => hostgroups don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => hostgroups don't match"); return false; } if (_hosts != other._hosts) { engine_logger(dbg_config, more) << "configuration::service::equality => _hosts don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => _hosts don't match"); return false; } if (_icon_image != other._icon_image) { engine_logger(dbg_config, more) << "configuration::service::equality => icon_image don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => icon_image don't match"); return false; } if (_icon_image_alt != other._icon_image_alt) { engine_logger(dbg_config, more) << "configuration::service::equality => icon_image_alt don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => icon_image_alt don't match"); return false; } if (_initial_state != other._initial_state) { engine_logger(dbg_config, more) << "configuration::service::equality => initial_state don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => initial_state don't match"); return false; } if (_is_volatile != other._is_volatile) { engine_logger(dbg_config, more) << "configuration::service::equality => is_volatile don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => is_volatile don't match"); return false; } if (_low_flap_threshold != other._low_flap_threshold) { engine_logger(dbg_config, more) << "configuration::service::equality => low_flap_threshold don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => low_flap_threshold don't match"); return false; } if (_max_check_attempts != other._max_check_attempts) { engine_logger(dbg_config, more) << "configuration::service::equality => max_check_attempts don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => max_check_attempts don't match"); return false; } if (_notes != other._notes) { engine_logger(dbg_config, more) << "configuration::service::equality => notes don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => notes don't match"); return false; } if (_notes_url != other._notes_url) { engine_logger(dbg_config, more) << "configuration::service::equality => notes_url don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => notes_url don't match"); return false; } if (_notifications_enabled != other._notifications_enabled) { engine_logger(dbg_config, more) << "configuration::service::equality => " "notifications_enabled don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => " "notifications_enabled don't match"); return false; @@ -541,7 +541,7 @@ bool service::operator==(service const& other) const noexcept { if (_notification_interval != other._notification_interval) { engine_logger(dbg_config, more) << "configuration::service::equality => " "notification_interval don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => " "notification_interval don't match"); return false; @@ -549,7 +549,7 @@ bool service::operator==(service const& other) const noexcept { if (_notification_options != other._notification_options) { engine_logger(dbg_config, more) << "configuration::service::equality => " "notification_options don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => " "notification_options don't match"); return false; @@ -557,7 +557,7 @@ bool service::operator==(service const& other) const noexcept { if (_notification_period != other._notification_period) { engine_logger(dbg_config, more) << "configuration::service::equality => " "notification_period don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => " "notification_period don't match"); return false; @@ -565,7 +565,7 @@ bool service::operator==(service const& other) const noexcept { if (_obsess_over_service != other._obsess_over_service) { engine_logger(dbg_config, more) << "configuration::service::equality => " "obsess_over_service don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => " "obsess_over_service don't match"); return false; @@ -573,7 +573,7 @@ bool service::operator==(service const& other) const noexcept { if (_process_perf_data != other._process_perf_data) { engine_logger(dbg_config, more) << "configuration::service::equality => process_perf_data don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => process_perf_data don't match"); return false; } @@ -581,7 +581,7 @@ bool service::operator==(service const& other) const noexcept { engine_logger(dbg_config, more) << "configuration::service::equality => " "retain_nonstatus_information don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => " "retain_nonstatus_information don't match"); return false; @@ -589,7 +589,7 @@ bool service::operator==(service const& other) const noexcept { if (_retain_status_information != other._retain_status_information) { engine_logger(dbg_config, more) << "configuration::service::equality => " "retain_status_information don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => " "retain_status_information don't match"); return false; @@ -597,7 +597,7 @@ bool service::operator==(service const& other) const noexcept { if (_retry_interval != other._retry_interval) { engine_logger(dbg_config, more) << "configuration::service::equality => retry_interval don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => retry_interval don't match"); return false; } @@ -605,7 +605,7 @@ bool service::operator==(service const& other) const noexcept { engine_logger(dbg_config, more) << "configuration::service::equality => " "recovery_notification_delay don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => " "recovery_notification_delay don't match"); return false; @@ -613,14 +613,14 @@ bool service::operator==(service const& other) const noexcept { if (_servicegroups != other._servicegroups) { engine_logger(dbg_config, more) << "configuration::service::equality => servicegroups don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => servicegroups don't match"); return false; } if (_service_description != other._service_description) { engine_logger(dbg_config, more) << "configuration::service::equality => " "service_description don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => " "service_description don't match"); return false; @@ -628,54 +628,54 @@ bool service::operator==(service const& other) const noexcept { if (_host_id != other._host_id) { engine_logger(dbg_config, more) << "configuration::service::equality => host_id don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => host_id don't match"); return false; } if (_service_id != other._service_id) { engine_logger(dbg_config, more) << "configuration::service::equality => service_id don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => service_id don't match"); return false; } if (_stalking_options != other._stalking_options) { engine_logger(dbg_config, more) << "configuration::service::equality => stalking_options don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => stalking_options don't match"); return false; } if (_timezone != other._timezone) { engine_logger(dbg_config, more) << "configuration::service::equality => timezone don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => timezone don't match"); return false; } if (_severity_id != other._severity_id) { engine_logger(dbg_config, more) << "configuration::service::equality => severity id don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => severity id don't match"); return false; } if (_icon_id != other._icon_id) { engine_logger(dbg_config, more) << "configuration::service::equality => icon id don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => icon id don't match"); return false; } if (_tags != other._tags) { engine_logger(dbg_config, more) << "configuration::service::equality => tags don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::service::equality => tags don't match"); return false; } engine_logger(dbg_config, more) << "configuration::service::equality => OK"; - log_v2::config()->debug("configuration::service::equality => OK"); + config_logger->debug("configuration::service::equality => OK"); return true; } @@ -1663,7 +1663,7 @@ bool service::_set_failure_prediction_enabled(bool value) { engine_logger(log_verification_error, basic) << "Warning: service failure_prediction_enabled is deprecated." << " This option will not be supported in 20.04."; - log_v2::config()->warn( + config_logger->warn( "Warning: service failure_prediction_enabled is deprecated. This option " "will not be supported in 20.04."); ++config_warnings; @@ -1682,7 +1682,7 @@ bool service::_set_failure_prediction_options(std::string const& value) { engine_logger(log_verification_error, basic) << "Warning: service failure_prediction_options is deprecated." << " This option will not be supported in 20.04."; - log_v2::config()->warn( + config_logger->warn( "Warning: service failure_prediction_options is deprecated. This option " "will not be supported in 20.04."); ++config_warnings; @@ -2000,7 +2000,7 @@ bool service::_set_parallelize_check(bool value) { engine_logger(log_verification_error, basic) << "Warning: service parallelize_check is deprecated" << " This option will not be supported in 20.04."; - log_v2::config()->warn( + config_logger->warn( "Warning: service parallelize_check is deprecated This option will not " "be supported in 20.04."); ++config_warnings; @@ -2176,9 +2176,8 @@ bool service::_set_category_tags(const std::string& value) { if (parse_ok) { _tags.emplace(id, tag::servicecategory); } else { - log_v2::config()->warn( - "Warning: service ({}, {}) error for parsing tag {}", _host_id, - _service_id, value); + config_logger->warn("Warning: service ({}, {}) error for parsing tag {}", + _host_id, _service_id, value); ret = false; } } @@ -2211,9 +2210,8 @@ bool service::_set_group_tags(const std::string& value) { if (parse_ok) { _tags.emplace(id, tag::servicegroup); } else { - log_v2::config()->warn( - "Warning: service ({}, {}) error for parsing tag {}", _host_id, - _service_id, value); + config_logger->warn("Warning: service ({}, {}) error for parsing tag {}", + _host_id, _service_id, value); ret = false; } } diff --git a/engine/src/configuration/servicedependency.cc b/engine/src/configuration/servicedependency.cc index 7b3f3053865..ec5d032bf11 100644 --- a/engine/src/configuration/servicedependency.cc +++ b/engine/src/configuration/servicedependency.cc @@ -1,25 +1,26 @@ /** -* Copyright 2011-2014 Merethis -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2014 Merethis + * Copyright 2015 - 2024 Centreon (https://www.centreon.com/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include "com/centreon/engine/configuration/servicedependency.hh" #include "com/centreon/engine/exceptions/error.hh" -#include "com/centreon/engine/log_v2.hh" +#include "com/centreon/engine/globals.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/string.hh" @@ -278,10 +279,8 @@ void servicedependency::check_validity() const { msg << "host '" << _hosts->front() << "'"; } engine_logger(log_config_warning, basic) << msg.str(); - log_v2::config()->warn(msg.str()); + config_logger->warn(msg.str()); } - - return; } /** diff --git a/engine/src/configuration/serviceescalation.cc b/engine/src/configuration/serviceescalation.cc index 801ce0e46d7..820af49c438 100644 --- a/engine/src/configuration/serviceescalation.cc +++ b/engine/src/configuration/serviceescalation.cc @@ -1,25 +1,25 @@ /** -* Copyright 2011-2015,2017 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2015,2017-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include "com/centreon/engine/configuration/serviceescalation.hh" #include "com/centreon/engine/exceptions/error.hh" -#include "com/centreon/engine/log_v2.hh" +#include "com/centreon/engine/globals.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/string.hh" @@ -126,14 +126,14 @@ bool serviceescalation::operator==(serviceescalation const& right) const if (!object::operator==(right)) { engine_logger(dbg_config, more) << "configuration::serviceescalation::equality => object don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::serviceescalation::equality => object don't match"); return false; } if (_contactgroups != right._contactgroups) { engine_logger(dbg_config, more) << "configuration::serviceescalation::" "equality => contact groups don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::serviceescalation::" "equality => contact groups don't match"); return false; @@ -142,7 +142,7 @@ bool serviceescalation::operator==(serviceescalation const& right) const engine_logger(dbg_config, more) << "configuration::serviceescalation::equality => escalation options " "don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::serviceescalation::equality => escalation options " "don't match"); return false; @@ -151,7 +151,7 @@ bool serviceescalation::operator==(serviceescalation const& right) const engine_logger(dbg_config, more) << "configuration::serviceescalation::equality => escalation periods " "don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::serviceescalation::equality => escalation periods " "don't match"); return false; @@ -160,7 +160,7 @@ bool serviceescalation::operator==(serviceescalation const& right) const engine_logger(dbg_config, more) << "configuration::serviceescalation::equality => first notifications " "don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::serviceescalation::equality => first notifications " "don't match"); return false; @@ -168,7 +168,7 @@ bool serviceescalation::operator==(serviceescalation const& right) const if (_hostgroups != right._hostgroups) { engine_logger(dbg_config, more) << "configuration::serviceescalation::" "equality => host groups don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::serviceescalation::" "equality => host groups don't match"); return false; @@ -176,7 +176,7 @@ bool serviceescalation::operator==(serviceescalation const& right) const if (_hosts != right._hosts) { engine_logger(dbg_config, more) << "configuration::serviceescalation::equality => hosts don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::serviceescalation::equality => hosts don't match"); return false; } @@ -184,7 +184,7 @@ bool serviceescalation::operator==(serviceescalation const& right) const engine_logger(dbg_config, more) << "configuration::serviceescalation::equality => last notification " "don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::serviceescalation::equality => last notification " "don't match"); return false; @@ -193,7 +193,7 @@ bool serviceescalation::operator==(serviceescalation const& right) const engine_logger(dbg_config, more) << "configuration::serviceescalation::equality => notification " "interval don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::serviceescalation::equality => notification " "interval don't match"); return false; @@ -201,7 +201,7 @@ bool serviceescalation::operator==(serviceescalation const& right) const if (_servicegroups != right._servicegroups) { engine_logger(dbg_config, more) << "configuration::serviceescalation::" "equality => service groups don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::serviceescalation::" "equality => service groups don't match"); return false; @@ -210,14 +210,14 @@ bool serviceescalation::operator==(serviceescalation const& right) const engine_logger(dbg_config, more) << "configuration::serviceescalation::equality => service descriptions " "don't match"; - log_v2::config()->debug( + config_logger->debug( "configuration::serviceescalation::equality => service descriptions " "don't match"); return false; } engine_logger(dbg_config, more) << "configuration::serviceescalation::equality => OK"; - log_v2::config()->debug("configuration::serviceescalation::equality => OK"); + config_logger->debug("configuration::serviceescalation::equality => OK"); return true; } diff --git a/engine/src/configuration/state.cc b/engine/src/configuration/state.cc index dd549b763cf..e648c0f03c7 100644 --- a/engine/src/configuration/state.cc +++ b/engine/src/configuration/state.cc @@ -1,5 +1,5 @@ /** - * Copyright 2011-2013,2015-2017, 2021-2022 Centreon + * Copyright 2011-2013,2015-2017, 2021-2024 Centreon * * This file is part of Centreon Engine. * @@ -17,14 +17,11 @@ * . */ -#include "com/centreon/common/rapidjson_helper.hh" - #include "com/centreon/engine/configuration/state.hh" - +#include "com/centreon/common/rapidjson_helper.hh" #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/string.hh" #include "com/centreon/io/file_entry.hh" #include "compatibility/locations.h" @@ -33,6 +30,7 @@ using namespace com::centreon; using namespace com::centreon::engine; using namespace com::centreon::engine::configuration; using namespace com::centreon::engine::logging; +using com::centreon::common::log_v2::log_v2; namespace com::centreon::engine::configuration::detail { template @@ -45,8 +43,7 @@ struct setter : public setter_base { return false; (obj.*ptr)(val); } catch (std::exception const& e) { - SPDLOG_LOGGER_ERROR(log_v2::config(), - "fail to update {} with value {}: {}", + SPDLOG_LOGGER_ERROR(config_logger, "fail to update {} with value {}: {}", setter_base::_field_name, value, e.what()); return false; } @@ -59,7 +56,7 @@ struct setter : public setter_base { common::rapidjson_helper(doc).get(setter_base::_field_name.data()); (obj.*ptr)(val); } catch (std::exception const& e) { - SPDLOG_LOGGER_ERROR(log_v2::config(), "fail to update {} : {}", + SPDLOG_LOGGER_ERROR(config_logger, "fail to update {} : {}", setter_base::_field_name, e.what()); return false; } @@ -74,9 +71,8 @@ struct setter : public setter_base { try { (obj.*ptr)(value); } catch (std::exception const& e) { - SPDLOG_LOGGER_ERROR(log_v2::config(), - "fail to update {} with value {}: {}", _field_name, - value, e.what()); + SPDLOG_LOGGER_ERROR(config_logger, "fail to update {} with value {}: {}", + _field_name, value, e.what()); return false; } return true; @@ -87,8 +83,8 @@ struct setter : public setter_base { common::rapidjson_helper(doc).get_string(_field_name.data()); (obj.*ptr)(val); } catch (std::exception const& e) { - SPDLOG_LOGGER_ERROR(log_v2::config(), "fail to update {} : {}", - _field_name, e.what()); + SPDLOG_LOGGER_ERROR(config_logger, "fail to update {} : {}", _field_name, + e.what()); return false; } return true; @@ -3619,7 +3615,7 @@ bool state::set(char const* key, char const* value) { return (it->second)->apply_from_cfg(*this, value); } catch (std::exception const& e) { engine_logger(log_config_error, basic) << e.what(); - log_v2::config()->error(e.what()); + config_logger->error(e.what()); return false; } return true; @@ -3756,7 +3752,7 @@ void state::use_aggressive_host_checking(bool value __attribute__((unused))) { engine_logger(log_verification_error, basic) << "Warning: use_aggressive_host_checking is deprecated." " This option is no more supported since version 21.04."; - log_v2::config()->warn( + config_logger->warn( "Warning: use_aggressive_host_checking is deprecated. This option is " "no " "more supported since version 21.04."); @@ -3961,7 +3957,7 @@ std::string const& state::log_level_functions() const noexcept { * @param[in] value The new log_level_functions value. */ void state::log_level_functions(std::string const& value) { - if (log_v2::contains_level(value)) + if (log_v2::instance().contains_level(value)) _log_level_functions = value; else throw engine_error() << "error wrong level setted for log_level_functions"; @@ -3982,7 +3978,7 @@ std::string const& state::log_level_config() const noexcept { * @param[in] value The new log_level_config value. */ void state::log_level_config(std::string const& value) { - if (log_v2::contains_level(value)) + if (log_v2::instance().contains_level(value)) _log_level_config = value; else throw engine_error() << "error wrong level setted for log_level_config"; @@ -4003,7 +3999,7 @@ std::string const& state::log_level_events() const noexcept { * @param[in] value The new log_level_events value. */ void state::log_level_events(std::string const& value) { - if (log_v2::contains_level(value)) + if (log_v2::instance().contains_level(value)) _log_level_events = value; else throw engine_error() << "error wrong level setted for log_level_events"; @@ -4024,7 +4020,7 @@ std::string const& state::log_level_checks() const noexcept { * @param[in] value The new log_level_checks value. */ void state::log_level_checks(std::string const& value) { - if (log_v2::contains_level(value)) + if (log_v2::instance().contains_level(value)) _log_level_checks = value; else throw engine_error() << "error wrong level setted for log_level_checks"; @@ -4045,7 +4041,7 @@ std::string const& state::log_level_notifications() const noexcept { * @param[in] value The new log_level_notifications value. */ void state::log_level_notifications(std::string const& value) { - if (log_v2::contains_level(value)) + if (log_v2::instance().contains_level(value)) _log_level_notifications = value; else throw engine_error() @@ -4067,7 +4063,7 @@ std::string const& state::log_level_eventbroker() const noexcept { * @param[in] value The new log_level_eventbroker value. */ void state::log_level_eventbroker(std::string const& value) { - if (log_v2::contains_level(value)) + if (log_v2::instance().contains_level(value)) _log_level_eventbroker = value; else throw engine_error() @@ -4089,7 +4085,7 @@ std::string const& state::log_level_external_command() const noexcept { * @param[in] value The new log_level_external_command value. */ void state::log_level_external_command(std::string const& value) { - if (log_v2::contains_level(value)) + if (log_v2::instance().contains_level(value)) _log_level_external_command = value; else throw engine_error() @@ -4111,7 +4107,7 @@ std::string const& state::log_level_commands() const noexcept { * @param[in] value The new log_level_commands value. */ void state::log_level_commands(std::string const& value) { - if (log_v2::contains_level(value)) + if (log_v2::instance().contains_level(value)) _log_level_commands = value; else throw engine_error() << "error wrong level setted for log_level_commands"; @@ -4132,7 +4128,7 @@ std::string const& state::log_level_downtimes() const noexcept { * @param[in] value The new log_level_downtimes value. */ void state::log_level_downtimes(std::string const& value) { - if (log_v2::contains_level(value)) + if (log_v2::instance().contains_level(value)) _log_level_downtimes = value; else throw engine_error() << "error wrong level setted for log_level_downtimes"; @@ -4153,7 +4149,7 @@ std::string const& state::log_level_comments() const noexcept { * @param[in] value The new log_level_comments value. */ void state::log_level_comments(std::string const& value) { - if (log_v2::contains_level(value)) + if (log_v2::instance().contains_level(value)) _log_level_comments = value; else throw engine_error() << "error wrong level setted for log_level_comments"; @@ -4174,7 +4170,7 @@ std::string const& state::log_level_macros() const noexcept { * @param[in] value The new log_level_macros value. */ void state::log_level_macros(std::string const& value) { - if (log_v2::contains_level(value)) + if (log_v2::instance().contains_level(value)) _log_level_macros = value; else throw engine_error() << "error wrong level setted for log_level_macros"; @@ -4195,7 +4191,7 @@ std::string const& state::log_level_process() const noexcept { * @param[in] value The new log_level_process value. */ void state::log_level_process(std::string const& value) { - if (log_v2::contains_level(value)) + if (log_v2::instance().contains_level(value)) _log_level_process = value; else throw engine_error() << "error wrong level setted for log_level_process"; @@ -4216,7 +4212,7 @@ std::string const& state::log_level_runtime() const noexcept { * @param[in] value The new log_level_runtime value. */ void state::log_level_runtime(std::string const& value) { - if (log_v2::contains_level(value)) + if (log_v2::instance().contains_level(value)) _log_level_runtime = value; else throw engine_error() << "error wrong level setted for log_level_runtime"; @@ -4267,7 +4263,7 @@ void state::_set_aggregate_status_updates(std::string const& value) { (void)value; engine_logger(log_config_warning, basic) << "Warning: aggregate_status_updates variable ignored"; - log_v2::config()->warn("Warning: aggregate_status_updates variable ignored"); + config_logger->warn("Warning: aggregate_status_updates variable ignored"); ++config_warnings; } @@ -4280,7 +4276,7 @@ void state::_set_auth_file(std::string const& value) { (void)value; engine_logger(log_config_warning, basic) << "Warning: auth_file variable ignored"; - log_v2::config()->warn("Warning: auth_file variable ignored"); + config_logger->warn("Warning: auth_file variable ignored"); ++config_warnings; } @@ -4293,7 +4289,7 @@ void state::_set_bare_update_check(std::string const& value) { (void)value; engine_logger(log_config_warning, basic) << "Warning: bare_update_check variable ignored"; - log_v2::config()->warn("Warning: bare_update_check variable ignored"); + config_logger->warn("Warning: bare_update_check variable ignored"); ++config_warnings; } @@ -4345,7 +4341,7 @@ void state::_set_check_for_updates(std::string const& value) { (void)value; engine_logger(log_config_warning, basic) << "Warning: check_for_updates variable ignored"; - log_v2::config()->warn("Warning: check_for_updates variable ignored"); + config_logger->warn("Warning: check_for_updates variable ignored"); ++config_warnings; } @@ -4358,8 +4354,7 @@ void state::_set_child_processes_fork_twice(std::string const& value) { (void)value; engine_logger(log_config_warning, basic) << "Warning: child_processes_fork_twice variable ignored"; - log_v2::config()->warn( - "Warning: child_processes_fork_twice variable ignored"); + config_logger->warn("Warning: child_processes_fork_twice variable ignored"); ++config_warnings; } @@ -4390,7 +4385,7 @@ void state::_set_comment_file(std::string const& value) { (void)value; engine_logger(log_config_warning, basic) << "Warning: comment_file variable ignored"; - log_v2::config()->warn("Warning: comment_file variable ignored"); + config_logger->warn("Warning: comment_file variable ignored"); ++config_warnings; } @@ -4403,7 +4398,7 @@ void state::_set_daemon_dumps_core(std::string const& value) { (void)value; engine_logger(log_config_warning, basic) << "Warning: daemon_dumps_core variable ignored"; - log_v2::config()->warn("Warning: daemon_dumps_core variable ignored"); + config_logger->warn("Warning: daemon_dumps_core variable ignored"); ++config_warnings; } @@ -4432,7 +4427,7 @@ void state::_set_downtime_file(std::string const& value) { (void)value; engine_logger(log_config_warning, basic) << "Warning: downtime_file variable ignored"; - log_v2::config()->warn("Warning: downtime_file variable ignored"); + config_logger->warn("Warning: downtime_file variable ignored"); ++config_warnings; } @@ -4445,7 +4440,7 @@ void state::_set_enable_embedded_perl(std::string const& value) { (void)value; engine_logger(log_config_warning, basic) << "Warning: enable_embedded_perl variable ignored"; - log_v2::config()->warn("Warning: enable_embedded_perl variable ignored"); + config_logger->warn("Warning: enable_embedded_perl variable ignored"); ++config_warnings; } @@ -4458,7 +4453,7 @@ void state::_set_enable_failure_prediction(std::string const& value) { (void)value; engine_logger(log_config_warning, basic) << "Warning: enable_failure_prediction variable ignored"; - log_v2::config()->warn("Warning: enable_failure_prediction variable ignored"); + config_logger->warn("Warning: enable_failure_prediction variable ignored"); ++config_warnings; return; } @@ -4486,7 +4481,7 @@ void state::_set_free_child_process_memory(std::string const& value) { (void)value; engine_logger(log_config_warning, basic) << "Warning: free_child_process_memory variable ignored"; - log_v2::config()->warn("Warning: free_child_process_memory variable ignored"); + config_logger->warn("Warning: free_child_process_memory variable ignored"); ++config_warnings; } @@ -4536,7 +4531,7 @@ void state::_set_lock_file(std::string const& value) { (void)value; engine_logger(log_config_warning, basic) << "Warning: lock_file variable ignored"; - log_v2::config()->warn("Warning: lock_file variable ignored"); + config_logger->warn("Warning: lock_file variable ignored"); ++config_warnings; } @@ -4549,7 +4544,7 @@ void state::_set_log_archive_path(std::string const& value) { (void)value; engine_logger(log_config_warning, basic) << "Warning: log_archive_path variable ignored"; - log_v2::config()->warn("Warning: log_archive_path variable ignored"); + config_logger->warn("Warning: log_archive_path variable ignored"); ++config_warnings; } @@ -4562,7 +4557,7 @@ void state::_set_log_initial_states(std::string const& value) { (void)value; engine_logger(log_config_warning, basic) << "Warning: log_initial_states variable ignored"; - log_v2::config()->warn("Warning: log_initial_states variable ignored"); + config_logger->warn("Warning: log_initial_states variable ignored"); ++config_warnings; return; } @@ -4576,7 +4571,7 @@ void state::_set_log_rotation_method(std::string const& value) { (void)value; engine_logger(log_config_warning, basic) << "Warning: log_rotation_method variable ignored"; - log_v2::config()->warn("Warning: log_rotation_method variable ignored"); + config_logger->warn("Warning: log_rotation_method variable ignored"); ++config_warnings; } @@ -4589,7 +4584,7 @@ void state::_set_nagios_group(std::string const& value) { (void)value; engine_logger(log_config_warning, basic) << "Warning: nagios_group variable ignored"; - log_v2::config()->warn("Warning: nagios_group variable ignored"); + config_logger->warn("Warning: nagios_group variable ignored"); ++config_warnings; } @@ -4602,7 +4597,7 @@ void state::_set_nagios_user(std::string const& value) { (void)value; engine_logger(log_config_warning, basic) << "Warning: nagios_user variable ignored"; - log_v2::config()->warn("Warning: nagios_user variable ignored"); + config_logger->warn("Warning: nagios_user variable ignored"); ++config_warnings; } @@ -4615,7 +4610,7 @@ void state::_set_object_cache_file(std::string const& value) { (void)value; engine_logger(log_config_warning, basic) << "Warning: object_cache_file variable ignored"; - log_v2::config()->warn("Warning: object_cache_file variable ignored"); + config_logger->warn("Warning: object_cache_file variable ignored"); ++config_warnings; } @@ -4628,7 +4623,7 @@ void state::_set_p1_file(std::string const& value) { (void)value; engine_logger(log_config_warning, basic) << "Warning: p1_file variable ignored"; - log_v2::config()->warn("Warning: p1_file variable ignored"); + config_logger->warn("Warning: p1_file variable ignored"); ++config_warnings; } @@ -4642,7 +4637,7 @@ void state::_set_precached_object_file(std::string const& value) { (void)value; engine_logger(log_config_warning, basic) << "Warning: precached_object_file variable ignored"; - log_v2::config()->warn("Warning: precached_object_file variable ignored"); + config_logger->warn("Warning: precached_object_file variable ignored"); ++config_warnings; } @@ -4671,7 +4666,7 @@ void state::_set_retained_process_service_attribute_mask( (void)value; engine_logger(log_config_warning, basic) << "Warning: retained_process_service_attribute_mask variable ignored"; - log_v2::config()->warn( + config_logger->warn( "Warning: retained_process_service_attribute_mask variable ignored"); ++config_warnings; } @@ -4685,7 +4680,7 @@ void state::_set_retained_service_attribute_mask(std::string const& value) { (void)value; engine_logger(log_config_warning, basic) << "Warning: retained_service_attribute_mask variable ignored"; - log_v2::config()->warn( + config_logger->warn( "Warning: retained_service_attribute_mask variable ignored"); ++config_warnings; } @@ -4752,7 +4747,7 @@ void state::_set_temp_file(std::string const& value) { (void)value; engine_logger(log_config_warning, basic) << "Warning: temp_file variable ignored"; - log_v2::config()->warn("Warning: temp_file variable ignored"); + config_logger->warn("Warning: temp_file variable ignored"); ++config_warnings; } @@ -4765,7 +4760,7 @@ void state::_set_temp_path(std::string const& value) { (void)value; engine_logger(log_config_warning, basic) << "Warning: temp_path variable ignored"; - log_v2::config()->warn("Warning: temp_path variable ignored"); + config_logger->warn("Warning: temp_path variable ignored"); ++config_warnings; } @@ -4778,8 +4773,7 @@ void state::_set_use_embedded_perl_implicitly(std::string const& value) { (void)value; engine_logger(log_config_warning, basic) << "Warning: use_embedded_perl_implicitly variable ignored"; - log_v2::config()->warn( - "Warning: use_embedded_perl_implicitly variable ignored"); + config_logger->warn("Warning: use_embedded_perl_implicitly variable ignored"); ++config_warnings; } @@ -4861,17 +4855,17 @@ void state::use_send_recovery_notifications_anyways(bool value) { */ void state::apply_extended_conf(const std::string& file_path, const rapidjson::Document& json_doc) { - SPDLOG_LOGGER_INFO(log_v2::config(), "apply conf from file {}", file_path); + SPDLOG_LOGGER_INFO(config_logger, "apply conf from file {}", file_path); for (rapidjson::Value::ConstMemberIterator member_iter = json_doc.MemberBegin(); member_iter != json_doc.MemberEnd(); ++member_iter) { const std::string_view field_name = member_iter->name.GetString(); auto setter = _setters.find(field_name); if (setter == _setters.end()) { - SPDLOG_LOGGER_ERROR(log_v2::config(), "unknown field: {} in file {}", + SPDLOG_LOGGER_ERROR(config_logger, "unknown field: {} in file {}", field_name, file_path); } else if (!setter->second->apply_from_json(*this, json_doc)) { - SPDLOG_LOGGER_ERROR(log_v2::config(), + SPDLOG_LOGGER_ERROR(config_logger, "fail to update field: {} from file {}", field_name, file_path); } diff --git a/engine/src/configuration/whitelist.cc b/engine/src/configuration/whitelist.cc index febb4756302..40e617dd0a7 100644 --- a/engine/src/configuration/whitelist.cc +++ b/engine/src/configuration/whitelist.cc @@ -30,7 +30,7 @@ #include #include "absl/base/call_once.h" -#include "com/centreon/engine/log_v2.hh" +#include "com/centreon/engine/globals.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon; @@ -98,16 +98,15 @@ bool whitelist::_parse_file(const std::string_view& file_path) { // check file struct stat infos; if (::stat(file_path.data(), &infos)) { - SPDLOG_LOGGER_ERROR(log_v2::config(), "{} doesn't exist", file_path); + SPDLOG_LOGGER_ERROR(config_logger, "{} doesn't exist", file_path); return false; } if ((infos.st_mode & S_IFMT) != S_IFREG) { - SPDLOG_LOGGER_ERROR(log_v2::config(), "{} is not a regular file", - file_path); + SPDLOG_LOGGER_ERROR(config_logger, "{} is not a regular file", file_path); return false; } if (!infos.st_size) { - SPDLOG_LOGGER_ERROR(log_v2::config(), "{} is an empty file", file_path); + SPDLOG_LOGGER_ERROR(config_logger, "{} is an empty file", file_path); return false; } @@ -115,13 +114,13 @@ bool whitelist::_parse_file(const std::string_view& file_path) { if (centengine_group) { if (infos.st_uid || infos.st_gid != centengine_group->gr_gid) { - SPDLOG_LOGGER_ERROR(log_v2::config(), + SPDLOG_LOGGER_ERROR(config_logger, "file {} must be owned by root@centreon-engine", file_path); } } if (infos.st_mode & S_IRWXO || (infos.st_mode & S_IRWXG) != S_IRGRP) { - SPDLOG_LOGGER_ERROR(log_v2::config(), "file {} must have x40 right access", + SPDLOG_LOGGER_ERROR(config_logger, "file {} must have x40 right access", file_path); } @@ -135,13 +134,13 @@ bool whitelist::_parse_file(const std::string_view& file_path) { std::streamsize some_read = f.readsome(buff.get() + read, file_size - read); if (some_read < 0) { - SPDLOG_LOGGER_ERROR(log_v2::config(), "fail to read {}: {}"); + SPDLOG_LOGGER_ERROR(config_logger, "fail to read {}: {}"); return false; } read += some_read; } } catch (const std::exception& e) { - SPDLOG_LOGGER_ERROR(log_v2::config(), "fail to read {}: {}", file_path, + SPDLOG_LOGGER_ERROR(config_logger, "fail to read {}: {}", file_path, e.what()); return false; } @@ -151,7 +150,7 @@ bool whitelist::_parse_file(const std::string_view& file_path) { ryml::Tree tree = ryml::parse_in_place(ryml::substr(buff.get(), file_size)); return _read_file_content(tree); } catch (const std::exception& e) { - SPDLOG_LOGGER_ERROR(log_v2::config(), "fail to parse {}: {}", file_path, + SPDLOG_LOGGER_ERROR(config_logger, "fail to parse {}: {}", file_path, e.what()); return false; } @@ -171,12 +170,12 @@ bool whitelist::_read_file_content(const ryml_tree& file_content) { bool ret = false; if (wildcards.valid() && !wildcards.empty()) { if (!wildcards.is_seq()) { // not an array => error - SPDLOG_LOGGER_ERROR(log_v2::config(), "{}: wildcard is not a sequence"); + SPDLOG_LOGGER_ERROR(config_logger, "{}: wildcard is not a sequence"); } else { for (auto wildcard : wildcards) { auto value = wildcard.val(); std::string_view str_value(value.data(), value.size()); - SPDLOG_LOGGER_INFO(log_v2::config(), "wildcard '{}' added to whitelist", + SPDLOG_LOGGER_INFO(config_logger, "wildcard '{}' added to whitelist", str_value); _wildcards.emplace_back(str_value); ret = true; @@ -185,7 +184,7 @@ bool whitelist::_read_file_content(const ryml_tree& file_content) { } if (regexps.valid() && !regexps.empty()) { if (!regexps.is_seq()) { // not an array => error - SPDLOG_LOGGER_ERROR(log_v2::config(), "{}: regex is not a sequence"); + SPDLOG_LOGGER_ERROR(config_logger, "{}: regex is not a sequence"); } else { for (auto re : regexps) { auto value = re.val(); @@ -194,13 +193,13 @@ bool whitelist::_read_file_content(const ryml_tree& file_content) { std::make_unique(str_value); if (to_push_back->error_code() == re2::RE2::ErrorCode::NoError) { // success compile regex - SPDLOG_LOGGER_INFO(log_v2::config(), "regexp '{}' added to whitelist", + SPDLOG_LOGGER_INFO(config_logger, "regexp '{}' added to whitelist", str_value); _regex.push_back(std::move(to_push_back)); ret = true; } else { // bad regex SPDLOG_LOGGER_ERROR( - log_v2::config(), "fail to parse regex {}: error: {} at {} ", + config_logger, "fail to parse regex {}: error: {} at {} ", str_value, to_push_back->error(), to_push_back->error_arg()); } } @@ -259,8 +258,8 @@ whitelist::e_refresh_result whitelist::parse_dir( return e_refresh_result::no_directory; } if ((dir_infos.st_mode & S_IFMT) != S_IFDIR) { - SPDLOG_LOGGER_ERROR(log_v2::config(), "{} is not a directory: {}", - directory, dir_infos.st_mode); + SPDLOG_LOGGER_ERROR(config_logger, "{} is not a directory: {}", directory, + dir_infos.st_mode); return e_refresh_result::no_directory; } @@ -268,7 +267,7 @@ whitelist::e_refresh_result whitelist::parse_dir( if (centengine_group) { if (dir_infos.st_uid || dir_infos.st_gid != centengine_group->gr_gid) { - SPDLOG_LOGGER_ERROR(log_v2::config(), + SPDLOG_LOGGER_ERROR(config_logger, "directory {} must be owned by root@centreon-engine", directory); } @@ -276,7 +275,7 @@ whitelist::e_refresh_result whitelist::parse_dir( if (dir_infos.st_mode & S_IRWXO || (dir_infos.st_mode & S_IRWXG) != S_IRGRP + S_IXGRP) { - SPDLOG_LOGGER_ERROR(log_v2::config(), + SPDLOG_LOGGER_ERROR(config_logger, "directory {} must have 750 right access", directory); } @@ -304,6 +303,7 @@ whitelist& whitelist::instance() { void whitelist::reload() { static constexpr std::string_view directories[] = { - "/etc/centreon-engine-whitelist", "/usr/share/centreon-engine/whitelist.conf.d"}; + "/etc/centreon-engine-whitelist", + "/usr/share/centreon-engine/whitelist.conf.d"}; _instance = std::make_unique(directories, directories + 2); } diff --git a/engine/src/contact.cc b/engine/src/contact.cc index 422c61d8264..0a2ac083a0a 100644 --- a/engine/src/contact.cc +++ b/engine/src/contact.cc @@ -1,5 +1,5 @@ /** - * Copyright 2017 - 2019 Centreon (https://www.centreon.com/) + * Copyright 2017 - 2024 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,6 @@ #include "com/centreon/engine/deleter/listmember.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/notification.hh" #include "com/centreon/engine/shared.hh" @@ -533,7 +532,7 @@ std::shared_ptr add_contact( // Make sure we have the data we need. if (name.empty()) { engine_logger(log_config_error, basic) << "Error: Contact name is empty"; - log_v2::config()->error("Error: Contact name is empty"); + config_logger->error("Error: Contact name is empty"); return nullptr; } @@ -542,8 +541,7 @@ std::shared_ptr add_contact( if (contact::contacts.count(id)) { engine_logger(log_config_error, basic) << "Error: Contact '" << name << "' has already been defined"; - log_v2::config()->error("Error: Contact '{}' has already been defined", - name); + config_logger->error("Error: Contact '{}' has already been defined", name); return nullptr; } @@ -842,14 +840,14 @@ bool contact::should_be_notified(notifier::notification_category cat, notifier::reason_type type, notifier const& notif) const { engine_logger(dbg_functions, basic) << "contact::should_be_notified()"; - log_v2::functions()->trace("contact::should_be_notified()"); + functions_logger->trace("contact::should_be_notified()"); /* Are notifications enabled? */ switch (notif.get_notifier_type()) { case notifier::service_notification: { if (!_service_notifications_enabled) { engine_logger(dbg_notifications, most) << "This contact shouldn't be notified from services."; - log_v2::notifications()->info( + notifications_logger->info( "This contact shouldn't be notified from services."); return false; } @@ -859,7 +857,7 @@ bool contact::should_be_notified(notifier::notification_category cat, std::time(nullptr), get_service_notification_period_ptr())) { engine_logger(dbg_notifications, most) << "This contact shouldn't be notified at this time."; - log_v2::notifications()->info( + notifications_logger->info( "This contact shouldn't be notified at this time."); return false; } @@ -868,7 +866,7 @@ bool contact::should_be_notified(notifier::notification_category cat, if (!_host_notifications_enabled) { engine_logger(dbg_notifications, most) << "This contact shouldn't be notified from hosts."; - log_v2::notifications()->info( + notifications_logger->info( "This contact shouldn't be notified from hosts."); return false; } @@ -878,7 +876,7 @@ bool contact::should_be_notified(notifier::notification_category cat, std::time(nullptr), get_host_notification_period_ptr())) { engine_logger(dbg_notifications, most) << "This contact shouldn't be notified at this time."; - log_v2::notifications()->info( + notifications_logger->info( "This contact shouldn't be notified at this time."); return false; } @@ -891,7 +889,7 @@ bool contact::_to_notify_normal(notifier::reason_type type __attribute__((unused)), notifier const& notif) const { engine_logger(dbg_functions, basic) << "contact::_to_notify_normal()"; - log_v2::functions()->trace("contact::_to_notify_normal()"); + functions_logger->trace("contact::_to_notify_normal()"); notifier::notifier_type nt{notif.get_notifier_type()}; int state{notif.get_current_state_int()}; @@ -910,7 +908,7 @@ bool contact::_to_notify_normal(notifier::reason_type type engine_logger(dbg_notifications, most) << "We shouldn't notify this contact about state " << state << " since it is not configured for this contact."; - log_v2::notifications()->info( + notifications_logger->info( "We shouldn't notify this contact about state {} since it is not " "configured for this contact.", state); @@ -924,7 +922,7 @@ bool contact::_to_notify_recovery(notifier::reason_type type __attribute__((unused)), notifier const& notif) const { engine_logger(dbg_functions, basic) << "contact::_to_notify_recovery()"; - log_v2::functions()->trace("contact::_to_notify_recovery()"); + functions_logger->trace("contact::_to_notify_recovery()"); notifier::notifier_type nt{notif.get_notifier_type()}; if (!notify_on(nt, notifier::ok) && !notify_on(nt, notifier::up)) { @@ -932,7 +930,7 @@ bool contact::_to_notify_recovery(notifier::reason_type type << "We shouldn't notify this contact about a " << (nt == notifier::service_notification ? "service" : "host") << " recovery."; - log_v2::notifications()->info( + notifications_logger->info( "We shouldn't notify this contact about a {} recovery.", (nt == notifier::service_notification ? "service" : "host")); return false; @@ -945,7 +943,7 @@ bool contact::_to_notify_recovery(notifier::reason_type type << "We shouldn't notify this contact about a " << (nt == notifier::service_notification ? "service" : "host") << " recovery because he has not been notified about the incident."; - log_v2::notifications()->info( + notifications_logger->info( "We shouldn't notify this contact about a {} recovery because he has " "not been notified about the incident.", (nt == notifier::service_notification ? "service" : "host")); @@ -961,11 +959,11 @@ bool contact::_to_notify_acknowledgement(notifier::reason_type type __attribute__((unused))) const { engine_logger(dbg_functions, basic) << "contact::_to_notify_acknowledgement()"; - log_v2::functions()->trace("contact::_to_notify_acknowledgement()"); + functions_logger->trace("contact::_to_notify_acknowledgement()"); engine_logger(dbg_notifications, most) << "** Checking if contact '" << get_name() << "' should be notified about a acknowledgement notification"; - log_v2::notifications()->info( + notifications_logger->info( "** Checking if contact '{}' should be notified about a acknowledgement " "notification", get_name()); @@ -975,11 +973,11 @@ bool contact::_to_notify_acknowledgement(notifier::reason_type type bool contact::_to_notify_flapping(notifier::reason_type type, notifier const& notif) const { engine_logger(dbg_functions, basic) << "contact::_to_notify_flapping()"; - log_v2::functions()->trace("contact::_to_notify_flapping()"); + functions_logger->trace("contact::_to_notify_flapping()"); engine_logger(dbg_notifications, most) << "** Checking if contact '" << get_name() << "' should be notified about a flapping notification"; - log_v2::notifications()->info( + notifications_logger->info( "** Checking if contact '{}' should be notified about a flapping " "notification", get_name()); @@ -997,7 +995,7 @@ bool contact::_to_notify_flapping(notifier::reason_type type, engine_logger(dbg_notifications, most) << "We shouldn't notify contact '" << _name << "' about " << notifier::tab_notification_str[type] << " notifier events."; - log_v2::notifications()->info( + notifications_logger->info( "We shouldn't notify contact '{}' about {} notifier events.", _name, notifier::tab_notification_str[type]); return false; @@ -1009,11 +1007,11 @@ bool contact::_to_notify_downtime(notifier::reason_type type __attribute__((unused)), notifier const& notif) const { engine_logger(dbg_functions, basic) << "contact::_to_notify_downtime()"; - log_v2::functions()->trace("contact::_to_notify_downtime()"); + functions_logger->trace("contact::_to_notify_downtime()"); engine_logger(dbg_notifications, most) << "** Checking if contact '" << get_name() << "' should be notified about a downtime notification"; - log_v2::notifications()->info( + notifications_logger->info( "** Checking if contact '{}' should be notified about a downtime " "notification", get_name()); @@ -1022,7 +1020,7 @@ bool contact::_to_notify_downtime(notifier::reason_type type if (!notify_on(nt, notifier::downtime)) { engine_logger(dbg_notifications, most) << "We shouldn't notify this contact about DOWNTIME notifier events."; - log_v2::notifications()->info( + notifications_logger->info( "We shouldn't notify this contact about DOWNTIME notifier events."); return false; } @@ -1034,11 +1032,11 @@ bool contact::_to_notify_custom(notifier::reason_type type notifier const& notif __attribute__((unused))) const { engine_logger(dbg_functions, basic) << "contact::_to_notify_custom()"; - log_v2::functions()->trace("contact::_to_notify_custom()"); + functions_logger->trace("contact::_to_notify_custom()"); engine_logger(dbg_notifications, most) << "** Checking if contact '" << _name << "' should be notified about a custom notification"; - log_v2::notifications()->info( + notifications_logger->info( "** Checking if contact '{}' should be notified about a custom " "notification", _name); @@ -1054,7 +1052,7 @@ void contact::resolve(int& w, int& e) { << "Error: Contact '" << _name << "' has no service " "notification commands defined!"; - log_v2::config()->error( + config_logger->error( "Error: Contact '{}' has no service " "notification commands defined!", _name); @@ -1067,7 +1065,7 @@ void contact::resolve(int& w, int& e) { << "Error: Contact '" << _name << "' has no host " "notification commands defined!"; - log_v2::config()->error( + config_logger->error( "Error: Contact '{}' has no host " "notification commands defined!", _name); @@ -1080,7 +1078,7 @@ void contact::resolve(int& w, int& e) { << "Warning: Contact '" << _name << "' has no service " "notification time period defined!"; - log_v2::config()->warn( + config_logger->warn( "Warning: Contact '{}' has no service " "notification time period defined!", _name); @@ -1095,7 +1093,7 @@ void contact::resolve(int& w, int& e) { << "Error: Service notification period '" << get_service_notification_period() << "' specified for contact '" << _name << "' is not defined anywhere!"; - log_v2::config()->error( + config_logger->error( "Error: Service notification period '{}' specified for contact '{}' " "is not defined anywhere!", get_service_notification_period(), _name); @@ -1112,7 +1110,7 @@ void contact::resolve(int& w, int& e) { << "Warning: Contact '" << _name << "' has no host " "notification time period defined!"; - log_v2::config()->warn( + config_logger->warn( "Warning: Contact '{}' has no host " "notification time period defined!", _name); @@ -1127,7 +1125,7 @@ void contact::resolve(int& w, int& e) { << "Error: Host notification period '" << get_host_notification_period() << "' specified for contact '" << _name << "' is not defined anywhere!"; - log_v2::config()->warn( + config_logger->warn( "Error: Host notification period '{}' specified for contact '{}' is " "not defined anywhere!", get_host_notification_period(), _name); @@ -1146,7 +1144,7 @@ void contact::resolve(int& w, int& e) { << "Warning: Host recovery notification option for contact '" << _name << "' doesn't make any sense - specify down " "and/or unreachable options as well"; - log_v2::config()->warn( + config_logger->warn( "Warning: Host recovery notification option for contact '{}' doesn't " "make any sense - specify down " "and/or unreachable options as well", @@ -1163,7 +1161,7 @@ void contact::resolve(int& w, int& e) { << _name << "' doesn't make any sense - specify critical " "and/or warning options as well"; - log_v2::config()->warn( + config_logger->warn( "Warning: Service recovery notification option for contact '{}' " "doesn't make any sense - specify critical " "and/or warning options as well", @@ -1176,7 +1174,7 @@ void contact::resolve(int& w, int& e) { engine_logger(log_verification_error, basic) << "Error: The name of contact '" << _name << "' contains one or more illegal characters."; - log_v2::config()->error( + config_logger->error( "Error: The name of contact '{}' contains one or more illegal " "characters.", _name); diff --git a/engine/src/contactgroup.cc b/engine/src/contactgroup.cc index 843e6a5a0d4..6cd17d3388c 100644 --- a/engine/src/contactgroup.cc +++ b/engine/src/contactgroup.cc @@ -1,21 +1,21 @@ /** -* Copyright 2011-2019 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2019,2024 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/configuration/contactgroup.hh" #include "com/centreon/engine/broker.hh" @@ -24,7 +24,6 @@ #include "com/centreon/engine/contactgroup.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/string.hh" @@ -34,12 +33,6 @@ using namespace com::centreon::engine::logging; contactgroup_map contactgroup::contactgroups; -/************************************** - * * - * Public Methods * - * * - **************************************/ - /** * Constructor. */ @@ -128,7 +121,7 @@ void contactgroup::resolve(int& w __attribute__((unused)), int& e) { engine_logger(log_verification_error, basic) << "Error: Contact '" << it->first << "' specified in contact group '" << _name << "' is not defined anywhere!"; - log_v2::config()->error( + config_logger->error( "Error: Contact '{}' specified in contact group '{}' is not defined " "anywhere!", it->first, _name); @@ -142,7 +135,7 @@ void contactgroup::resolve(int& w __attribute__((unused)), int& e) { engine_logger(log_verification_error, basic) << "Error: The name of contact group '" << _name << "' contains one or more illegal characters."; - log_v2::config()->error( + config_logger->error( "Error: The name of contact group '{}' contains one or more illegal " "characters.", _name); diff --git a/engine/src/dependency.cc b/engine/src/dependency.cc index 75e67a923d9..09f48ae5501 100644 --- a/engine/src/dependency.cc +++ b/engine/src/dependency.cc @@ -1,25 +1,26 @@ /** -* Copyright 2011-2019 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2024 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/dependency.hh" + #include "com/centreon/engine/exceptions/error.hh" -#include "com/centreon/engine/log_v2.hh" +#include "com/centreon/engine/globals.hh" #include "com/centreon/engine/logging/logger.hh" using namespace com::centreon::engine; @@ -42,8 +43,7 @@ dependency::dependency(std::string const& dependent_hostname, if (dependent_hostname.empty() || hostname.empty()) { engine_logger(log_config_error, basic) << "Error: NULL host name in host dependency definition"; - log_v2::config()->error( - "Error: NULL host name in host dependency definition"); + config_logger->error("Error: NULL host name in host dependency definition"); throw engine_error() << "Could not create execution " << "dependency of '" << dependent_hostname << "' on '" << hostname << "'"; diff --git a/engine/src/diagnostic.cc b/engine/src/diagnostic.cc index 59775f2abb1..e8a00107a18 100644 --- a/engine/src/diagnostic.cc +++ b/engine/src/diagnostic.cc @@ -1,28 +1,27 @@ /** -* Copyright 2013,2015 Merethis -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2013,2015 Merethis + * Copyright 2020-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/engine/diagnostic.hh" #include #include "com/centreon/engine/configuration/parser.hh" #include "com/centreon/engine/configuration/state.hh" #include "com/centreon/engine/exceptions/error.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/version.hh" #include "com/centreon/io/file_stream.hh" diff --git a/engine/src/downtimes/downtime_manager.cc b/engine/src/downtimes/downtime_manager.cc index 8f76e5b5909..20fbdc3ae50 100644 --- a/engine/src/downtimes/downtime_manager.cc +++ b/engine/src/downtimes/downtime_manager.cc @@ -1,5 +1,5 @@ /** - * Copyright 2019-2022 Centreon (https://www.centreon.com/) + * Copyright 2019-2024 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,7 +27,6 @@ #include "com/centreon/engine/events/loop.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" using namespace com::centreon::engine; @@ -43,14 +42,14 @@ using namespace com::centreon::engine::logging; * */ void downtime_manager::delete_downtime(uint64_t downtime_id) { - SPDLOG_LOGGER_TRACE(log_v2::functions(), "delete_downtime({})", downtime_id); + SPDLOG_LOGGER_TRACE(functions_logger, "delete_downtime({})", downtime_id); /* find the downtime we should remove */ for (auto it = _scheduled_downtimes.begin(), end = _scheduled_downtimes.end(); it != end; ++it) { if (it->second->get_downtime_id() == downtime_id) { engine_logger(dbg_downtime, basic) << "delete downtime(id: " << downtime_id << ")"; - SPDLOG_LOGGER_TRACE(log_v2::downtimes(), "delete downtime(id: {})", + SPDLOG_LOGGER_TRACE(downtimes_logger, "delete downtime(id: {})", downtime_id); _scheduled_downtimes.erase(it); break; @@ -67,15 +66,15 @@ int downtime_manager::unschedule_downtime(uint64_t downtime_id) { }); engine_logger(dbg_functions, basic) << "unschedule_downtime()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), "unschedule_downtime()"); + SPDLOG_LOGGER_TRACE(functions_logger, "unschedule_downtime()"); engine_logger(dbg_downtime, basic) << "unschedule downtime(id: " << downtime_id << ")"; - SPDLOG_LOGGER_TRACE(log_v2::downtimes(), "unschedule downtime(id: {})", + SPDLOG_LOGGER_TRACE(downtimes_logger, "unschedule downtime(id: {})", downtime_id); /* find the downtime entry in the list in memory */ if (found == _scheduled_downtimes.end()) { - SPDLOG_LOGGER_DEBUG(log_v2::downtimes(), "unknown downtime(id: {})", + SPDLOG_LOGGER_DEBUG(downtimes_logger, "unknown downtime(id: {})", downtime_id); return ERROR; } @@ -100,7 +99,7 @@ int downtime_manager::unschedule_downtime(uint64_t downtime_id) { for (uint64_t id : lst) { engine_logger(dbg_downtime, basic) << "Unschedule triggered downtime (id: " << id << ")"; - SPDLOG_LOGGER_TRACE(log_v2::downtimes(), + SPDLOG_LOGGER_TRACE(downtimes_logger, "Unschedule triggered downtime (id: {})", id); unschedule_downtime(id); } @@ -128,8 +127,7 @@ int downtime_manager::check_pending_flex_host_downtime(host* hst) { time_t current_time(0L); engine_logger(dbg_functions, basic) << "check_pending_flex_host_downtime()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), - "check_pending_flex_host_downtime()"); + SPDLOG_LOGGER_TRACE(functions_logger, "check_pending_flex_host_downtime()"); if (hst == nullptr) return ERROR; @@ -165,7 +163,7 @@ int downtime_manager::check_pending_flex_host_downtime(host* hst) { << "Flexible downtime (id=" << it->second->get_downtime_id() << ") for host '" << hst->name() << "' starting now..."; SPDLOG_LOGGER_TRACE( - log_v2::downtimes(), + downtimes_logger, "Flexible downtime (id={}) for host '{}' starting now...", it->second->get_downtime_id(), hst->name()); @@ -183,7 +181,7 @@ int downtime_manager::check_pending_flex_service_downtime(service* svc) { engine_logger(dbg_functions, basic) << "check_pending_flex_service_downtime()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), + SPDLOG_LOGGER_TRACE(functions_logger, "check_pending_flex_service_downtime()"); if (svc == nullptr) @@ -221,7 +219,7 @@ int downtime_manager::check_pending_flex_service_downtime(service* svc) { << ") for service '" << svc->description() << "' on host '" << svc->get_hostname() << "' starting now..."; SPDLOG_LOGGER_TRACE( - log_v2::downtimes(), + downtimes_logger, "Flexible downtime (id={}) for service '{}' on host '{}' starting " "now...", dt.get_downtime_id(), svc->description(), svc->get_hostname()); @@ -252,7 +250,7 @@ int downtime_manager::check_for_expired_downtime() { time_t current_time(0L); engine_logger(dbg_functions, basic) << "check_for_expired_downtime()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), "check_for_expired_downtime()"); + SPDLOG_LOGGER_TRACE(functions_logger, "check_for_expired_downtime()"); time(¤t_time); @@ -270,7 +268,7 @@ int downtime_manager::check_for_expired_downtime() { << (dt.get_type() == downtime::host_downtime ? "host" : "service") << " downtime (id=" << dt.get_downtime_id() << ")..."; SPDLOG_LOGGER_TRACE( - log_v2::downtimes(), "Expiring {} downtime (id={})...", + downtimes_logger, "Expiring {} downtime (id={})...", dt.get_type() == downtime::host_downtime ? "host" : "service", dt.get_downtime_id()); @@ -298,7 +296,7 @@ int downtime_manager:: << service_description << "', start time: " << start_time.second << ", comment: '" << comment << "')"; SPDLOG_LOGGER_TRACE( - log_v2::downtimes(), + downtimes_logger, "Delete downtimes (host: '{}', service description: '{}', start time: " "{}, comment: '{}')", hostname, service_description, start_time.second, comment); @@ -349,8 +347,7 @@ int downtime_manager:: } void downtime_manager::insert_downtime(std::shared_ptr dt) { engine_logger(dbg_functions, basic) << "downtime_manager::insert_downtime()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), - "downtime_manager::insert_downtime()"); + SPDLOG_LOGGER_TRACE(functions_logger, "downtime_manager::insert_downtime()"); time_t start{dt->get_start_time()}; _scheduled_downtimes.insert({start, dt}); } @@ -363,7 +360,7 @@ void downtime_manager::insert_downtime(std::shared_ptr dt) { void downtime_manager::initialize_downtime_data() { engine_logger(dbg_functions, basic) << "downtime_manager::initialize_downtime_data()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), + SPDLOG_LOGGER_TRACE(functions_logger, "downtime_manager::initialize_downtime_data()"); /* clean up the old downtime data */ xdddefault_validate_downtime_data(); @@ -518,7 +515,7 @@ int downtime_manager::schedule_downtime(downtime::type type, unsigned long duration, uint64_t* new_downtime_id) { engine_logger(dbg_functions, basic) << "schedule_downtime()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), "schedule_downtime()"); + SPDLOG_LOGGER_TRACE(functions_logger, "schedule_downtime()"); /* don't add old or invalid downtimes */ if (start_time >= end_time || end_time <= time(nullptr)) @@ -529,7 +526,7 @@ int downtime_manager::schedule_downtime(downtime::type type, << "SCHEDULE DOWNTIME ALERT : start time is out of range and setted " "to " "1/1/2100 00:00"; - log_v2::config()->warn( + config_logger->warn( "SCHEDULE DOWNTIME ALERT : start time is out of range and setted to " "1/1/2100 00:00"); start_time = 4102441200; @@ -539,7 +536,7 @@ int downtime_manager::schedule_downtime(downtime::type type, engine_logger(log_verification_error, basic) << "SCHEDULE DOWNTIME ALERT : end time is out of range and setted to " "1/1/2100 00:00"; - log_v2::config()->warn( + config_logger->warn( "SCHEDULE DOWNTIME ALERT : end time is out of range and setted to " "1/1/2100 00:00"); end_time = 4102441200; @@ -548,7 +545,7 @@ int downtime_manager::schedule_downtime(downtime::type type, if (duration > 31622400) { engine_logger(log_verification_error, basic) << "SCHEDULE DOWNTIME ALERT : is too long and setted to 366 days"; - log_v2::config()->warn( + config_logger->warn( "SCHEDULE DOWNTIME ALERT : is too long and setted to 366 days"); duration = 31622400; } @@ -594,12 +591,11 @@ int downtime_manager::register_downtime(downtime::type type, uint64_t downtime_id) { engine_logger(dbg_functions, basic) << "downtime_manager::register_downtime()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), + SPDLOG_LOGGER_TRACE(functions_logger, "downtime_manager::register_downtime()"); engine_logger(dbg_downtime, basic) << "register downtime(type: " << type << ", id: " << downtime_id << ")"; - SPDLOG_LOGGER_TRACE(log_v2::downtimes(), - "register downtime(type: {}, id: {})", + SPDLOG_LOGGER_TRACE(downtimes_logger, "register downtime(type: {}, id: {})", static_cast(type), downtime_id); /* find the downtime entry in memory */ std::shared_ptr temp_downtime{find_downtime(type, downtime_id)}; diff --git a/engine/src/downtimes/host_downtime.cc b/engine/src/downtimes/host_downtime.cc index f263b12bd93..f594e558b7d 100644 --- a/engine/src/downtimes/host_downtime.cc +++ b/engine/src/downtimes/host_downtime.cc @@ -23,7 +23,7 @@ #include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/downtimes/downtime_manager.hh" #include "com/centreon/engine/events/loop.hh" -#include "com/centreon/engine/log_v2.hh" +#include "com/centreon/engine/globals.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/statusdata.hh" #include "com/centreon/engine/string.hh" @@ -183,7 +183,7 @@ int host_downtime::unschedule() { << "HOST DOWNTIME ALERT: " << it->second->name() << ";CANCELLED; Scheduled downtime for host has been " "cancelled."; - log_v2::events()->info( + events_logger->info( "HOST DOWNTIME ALERT: {};CANCELLED; Scheduled downtime for host has " "been " "cancelled.", @@ -199,7 +199,7 @@ int host_downtime::unschedule() { int host_downtime::subscribe() { engine_logger(dbg_functions, basic) << "host_downtime::subscribe()"; - log_v2::functions()->trace("host_downtime::subscribe()"); + functions_logger->trace("host_downtime::subscribe()"); auto it = host::hosts_by_id.find(host_id()); @@ -242,11 +242,11 @@ int host_downtime::subscribe() { type_string, start_time_string, end_time_string, hours, minutes); engine_logger(dbg_downtime, basic) << "Scheduled Downtime Details:"; - log_v2::downtimes()->trace("Scheduled Downtime Details:"); + downtimes_logger->trace("Scheduled Downtime Details:"); engine_logger(dbg_downtime, basic) << " Type: Host Downtime\n" " Host: " << hst->name(); - log_v2::downtimes()->trace(" Type: Host Downtime ; Host: {}", hst->name()); + downtimes_logger->trace(" Type: Host Downtime ; Host: {}", hst->name()); engine_logger(dbg_downtime, basic) << " Fixed/Flex: " << (is_fixed() ? "Fixed\n" : "Flexible\n") << " Start: " << start_time_string @@ -262,7 +262,7 @@ int host_downtime::subscribe() { << "\n" " Trigger ID: " << get_triggered_by(); - log_v2::downtimes()->trace( + downtimes_logger->trace( " Fixed/Flex: {} Start: {} End: {} Duration: {}h " "{}m {}s Downtime ID: {} Trigger ID: ", is_fixed() ? "Fixed" : "Flexible", start_time_string, end_time_string, @@ -309,7 +309,7 @@ int host_downtime::handle() { int attr{0}; engine_logger(dbg_functions, basic) << "handle_downtime()"; - log_v2::functions()->trace("handle_downtime()"); + functions_logger->trace("handle_downtime()"); auto it_hst = host::hosts_by_id.find(host_id()); @@ -366,7 +366,7 @@ int host_downtime::handle() { << "Host '" << it_hst->second->name() << "' has exited from a period of scheduled downtime (id=" << get_downtime_id() << ")."; - log_v2::downtimes()->trace( + downtimes_logger->trace( "Host '{}' has exited from a period of scheduled downtime (id={}).", it_hst->second->name(), get_downtime_id()); @@ -375,7 +375,7 @@ int host_downtime::handle() { << "HOST DOWNTIME ALERT: " << it_hst->second->name() << ";STOPPED; Host has exited from a period of scheduled " "downtime"; - log_v2::events()->info( + events_logger->info( "HOST DOWNTIME ALERT: {};STOPPED; Host has exited from a period of " "scheduled " "downtime", @@ -442,7 +442,7 @@ int host_downtime::handle() { << "Host '" << it_hst->second->name() << "' has entered a period of scheduled downtime (id=" << get_downtime_id() << ")."; - log_v2::downtimes()->trace( + downtimes_logger->trace( "Host '{}' has entered a period of scheduled downtime (id={}).", it_hst->second->name(), get_downtime_id()); @@ -450,7 +450,7 @@ int host_downtime::handle() { engine_logger(log_info_message, basic) << "HOST DOWNTIME ALERT: " << it_hst->second->name() << ";STARTED; Host has entered a period of scheduled downtime"; - log_v2::events()->info( + events_logger->info( "HOST DOWNTIME ALERT: {};STARTED; Host has entered a period of " "scheduled downtime", it_hst->second->name()); diff --git a/engine/src/downtimes/service_downtime.cc b/engine/src/downtimes/service_downtime.cc index b24c9e0ed45..d5e1671e9dd 100644 --- a/engine/src/downtimes/service_downtime.cc +++ b/engine/src/downtimes/service_downtime.cc @@ -1,5 +1,5 @@ /** - * Copyright 2019 Centreon (https://www.centreon.com/) + * Copyright 2019-2024 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,7 @@ #include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/downtimes/downtime_manager.hh" #include "com/centreon/engine/events/loop.hh" -#include "com/centreon/engine/log_v2.hh" +#include "com/centreon/engine/globals.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/statusdata.hh" #include "com/centreon/engine/string.hh" @@ -164,7 +164,7 @@ void service_downtime::print(std::ostream& os) const { int service_downtime::unschedule() { engine_logger(dbg_functions, basic) << "service_downtime::unschedule()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), "service_downtime::unschedule()"); + SPDLOG_LOGGER_TRACE(functions_logger, "service_downtime::unschedule()"); auto found = service::services_by_id.find({host_id(), service_id()}); /* find the host or service associated with this downtime */ @@ -196,7 +196,7 @@ int service_downtime::unschedule() { << ";CANCELLED; Scheduled downtime " "for service has been cancelled."; SPDLOG_LOGGER_INFO( - log_v2::events(), + events_logger, "SERVICE DOWNTIME ALERT: {};{};CANCELLED; Scheduled downtime " "for service has been cancelled.", found->second->get_hostname(), found->second->description()); @@ -211,7 +211,7 @@ int service_downtime::unschedule() { int service_downtime::subscribe() { engine_logger(dbg_functions, basic) << "service_downtime::subscribe()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), "service_downtime::subscribe()"); + SPDLOG_LOGGER_TRACE(functions_logger, "service_downtime::subscribe()"); auto found = service::services_by_id.find({host_id(), service_id()}); @@ -249,17 +249,17 @@ int service_downtime::subscribe() { type_string, start_time_string, end_time_string, hours, minutes); engine_logger(dbg_downtime, basic) << "Scheduled Downtime Details:"; - SPDLOG_LOGGER_TRACE(log_v2::downtimes(), "Scheduled Downtime Details:"); + SPDLOG_LOGGER_TRACE(downtimes_logger, "Scheduled Downtime Details:"); engine_logger(dbg_downtime, basic) << " Type: Service Downtime\n" " Host: " << found->second->get_hostname() << "\n" " Service: " << found->second->description(); - SPDLOG_LOGGER_TRACE(log_v2::downtimes(), " Type: Service Downtime"); - SPDLOG_LOGGER_TRACE(log_v2::downtimes(), " Host: {}", + SPDLOG_LOGGER_TRACE(downtimes_logger, " Type: Service Downtime"); + SPDLOG_LOGGER_TRACE(downtimes_logger, " Host: {}", found->second->get_hostname()); - SPDLOG_LOGGER_TRACE(log_v2::downtimes(), " Service: {}", + SPDLOG_LOGGER_TRACE(downtimes_logger, " Service: {}", found->second->description()); engine_logger(dbg_downtime, basic) @@ -278,7 +278,7 @@ int service_downtime::subscribe() { " Trigger ID: " << get_triggered_by(); SPDLOG_LOGGER_TRACE( - log_v2::downtimes(), + downtimes_logger, " Fixed/Flex: {} Start: {} End: {} Duration: {}h " "{}m {}s Downtime ID: {} Trigger ID: {}", is_fixed() ? "Fixed" : "Flexible", start_time_string, end_time_string, @@ -324,13 +324,13 @@ int service_downtime::handle() { int attr(0); engine_logger(dbg_functions, basic) << "handle_downtime()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), "handle_downtime()"); + SPDLOG_LOGGER_TRACE(functions_logger, "handle_downtime()"); auto found = service::services_by_id.find({host_id(), service_id()}); /* find the host or service associated with this downtime */ if (found == service::services_by_id.end() || !found->second) { - SPDLOG_LOGGER_ERROR(log_v2::downtimes(), "{}:{} not found", host_id(), + SPDLOG_LOGGER_ERROR(downtimes_logger, "{}:{} not found", host_id(), service_id()); return ERROR; } @@ -388,7 +388,7 @@ int service_downtime::handle() { "scheduled downtime (id=" << get_downtime_id() << ")."; SPDLOG_LOGGER_TRACE( - log_v2::downtimes(), + downtimes_logger, "Service '{}' on host '{}' has exited from a period of " "scheduled downtime (id={}).", found->second->description(), found->second->get_hostname(), @@ -401,7 +401,7 @@ int service_downtime::handle() { << ";STOPPED; Service has exited from a period of scheduled " "downtime"; SPDLOG_LOGGER_INFO( - log_v2::events(), + events_logger, "SERVICE DOWNTIME ALERT: {};{};STOPPED; Service has exited from a " "period of scheduled " "downtime", @@ -470,7 +470,7 @@ int service_downtime::handle() { "downtime (id=" << get_downtime_id() << ")."; SPDLOG_LOGGER_TRACE( - log_v2::downtimes(), + downtimes_logger, "Service '{}' on host '{}' has entered a period of scheduled " "downtime (id={}).", found->second->description(), found->second->get_hostname(), @@ -483,7 +483,7 @@ int service_downtime::handle() { << ";STARTED; Service has entered a period of scheduled " "downtime"; SPDLOG_LOGGER_INFO( - log_v2::events(), + events_logger, "SERVICE DOWNTIME ALERT: {};{};STARTED; Service has entered a period " "of scheduled " "downtime", @@ -541,7 +541,7 @@ uint64_t service_downtime::service_id() const { } void service_downtime::schedule() { - SPDLOG_LOGGER_TRACE(log_v2::functions(), "service_downtime::schedule()"); + SPDLOG_LOGGER_TRACE(functions_logger, "service_downtime::schedule()"); /* send data to event broker */ broker_downtime_data(NEBTYPE_DOWNTIME_LOAD, NEBATTR_NONE, diff --git a/engine/src/escalation.cc b/engine/src/escalation.cc index 8ac795d52c3..69db6bfc3df 100644 --- a/engine/src/escalation.cc +++ b/engine/src/escalation.cc @@ -1,25 +1,25 @@ /** -* Copyright 2011-2019 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2024 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/escalation.hh" #include "com/centreon/engine/exceptions/error.hh" -#include "com/centreon/engine/log_v2.hh" +#include "com/centreon/engine/globals.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/timeperiod.hh" @@ -126,7 +126,7 @@ void escalation::resolve(int& w __attribute__((unused)), int& e) { engine_logger(log_verification_error, basic) << "Error: Escalation period '" << get_escalation_period() << "' specified in escalation is not defined anywhere!"; - log_v2::config()->error( + config_logger->error( "Error: Escalation period '{}' specified in escalation is not " "defined anywhere!", get_escalation_period()); @@ -149,7 +149,7 @@ void escalation::resolve(int& w __attribute__((unused)), int& e) { << "Error: Contact group '" << it->first << "' specified in escalation for this notifier is not defined " "anywhere!"; - log_v2::config()->error( + config_logger->error( "Error: Contact group '{}' specified in escalation for this notifier " "is not defined " "anywhere!", diff --git a/engine/src/events/loop.cc b/engine/src/events/loop.cc index cc12e203054..59cd5fe765a 100644 --- a/engine/src/events/loop.cc +++ b/engine/src/events/loop.cc @@ -30,7 +30,6 @@ #include "com/centreon/engine/configuration/extended_conf.hh" #include "com/centreon/engine/configuration/parser.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/statusdata.hh" #include "com/centreon/logging/engine.hh" @@ -63,11 +62,11 @@ void loop::clear() { void loop::run() { // Debug message. engine_logger(dbg_functions, basic) << "events::loop::run()"; - log_v2::functions()->trace("events::loop::run()"); + functions_logger->trace("events::loop::run()"); engine_logger(log_info_message, basic) << "Configuration loaded, main loop starting."; - log_v2::process()->info("Configuration loaded, main loop starting."); + process_logger->info("Configuration loaded, main loop starting."); // Initialize some time members. time(&_last_time); _last_status_update = 0L; @@ -94,7 +93,7 @@ loop::loop() : _need_reload(0), _reload_running(false) {} static void apply_conf(std::atomic* reloading) { engine_logger(log_info_message, more) << "Starting to reload configuration."; - log_v2::process()->info("Starting to reload configuration."); + process_logger->info("Starting to reload configuration."); try { configuration::state config; { @@ -106,14 +105,14 @@ static void apply_conf(std::atomic* reloading) { configuration::applier::state::instance().apply(config); engine_logger(log_info_message, basic) << "Configuration reloaded, main loop continuing."; - log_v2::process()->info("Configuration reloaded, main loop continuing."); + process_logger->info("Configuration reloaded, main loop continuing."); } catch (std::exception const& e) { engine_logger(log_config_error, most) << "Error: " << e.what(); - log_v2::config()->error("Error: {}", e.what()); + config_logger->error("Error: {}", e.what()); } *reloading = false; engine_logger(log_info_message, more) << "Reload configuration finished."; - log_v2::process()->info("Reload configuration finished."); + process_logger->info("Reload configuration finished."); } /** @@ -131,7 +130,7 @@ void loop::_dispatching() { engine_logger(log_runtime_error, basic) << "There aren't any events that need to be handled! " << "Exiting..."; - log_v2::runtime()->error( + runtime_logger->error( "There aren't any events that need to be handled! Exiting..."); break; } @@ -145,15 +144,15 @@ void loop::_dispatching() { // Start reload configuration. if (_need_reload) { engine_logger(log_info_message, most) << "Need reload."; - log_v2::process()->info("Need reload."); + process_logger->info("Need reload."); if (!reloading) { engine_logger(log_info_message, most) << "Reloading..."; - log_v2::process()->info("Reloading..."); + process_logger->info("Reloading..."); reloading = true; std::async(std::launch::async, apply_conf, &reloading); } else { engine_logger(log_info_message, most) << "Already reloading..."; - log_v2::process()->info("Already reloading..."); + process_logger->info("Already reloading..."); } _need_reload = 0; } @@ -182,35 +181,35 @@ void loop::_dispatching() { // Log messages about event lists. engine_logger(dbg_events, more) << "** Event Check Loop"; - log_v2::events()->debug("** Event Check Loop"); + events_logger->debug("** Event Check Loop"); if (!_event_list_high.empty()) { engine_logger(dbg_events, more) << "Next High Priority Event Time: " << my_ctime(&(*_event_list_high.begin())->run_time); - log_v2::events()->debug("Next High Priority Event Time: {}", - my_ctime(&(*_event_list_high.begin())->run_time)); + events_logger->debug("Next High Priority Event Time: {}", + my_ctime(&(*_event_list_high.begin())->run_time)); } else { engine_logger(dbg_events, more) << "No high priority events are scheduled..."; - log_v2::events()->debug("No high priority events are scheduled..."); + events_logger->debug("No high priority events are scheduled..."); } if (!_event_list_low.empty()) { engine_logger(dbg_events, more) << "Next Low Priority Event Time: " << my_ctime(&(*_event_list_low.begin())->run_time); - log_v2::events()->debug("Next Low Priority Event Time: {}", - my_ctime(&(*_event_list_low.begin())->run_time)); + events_logger->debug("Next Low Priority Event Time: {}", + my_ctime(&(*_event_list_low.begin())->run_time)); } else { engine_logger(dbg_events, more) << "No low priority events are scheduled..."; - log_v2::events()->debug("No low priority events are scheduled..."); + events_logger->debug("No low priority events are scheduled..."); } engine_logger(dbg_events, more) << "Current/Max Service Checks: " << currently_running_service_checks << '/' << config->max_parallel_service_checks(); - log_v2::events()->debug("Current/Max Service Checks: {}/{}", - currently_running_service_checks, - config->max_parallel_service_checks()); + events_logger->debug("Current/Max Service Checks: {}/{}", + currently_running_service_checks, + config->max_parallel_service_checks()); // Update status information occassionally - NagVis watches the // NDOUtils DB to see if Engine is alive. @@ -264,7 +263,7 @@ void loop::_dispatching() { << ") has been reached! Nudging " << temp_service->get_hostname() << ":" << temp_service->description() << " by " << nudge_seconds << " seconds..."; - log_v2::events()->trace( + events_logger->trace( "**WARNING** Max concurrent service checks ({}/{}) has been " "reached! Nudging {}:{} by {} seconds...", currently_running_service_checks, @@ -279,7 +278,7 @@ void loop::_dispatching() { << ") has been reached. Nudging " << temp_service->get_hostname() << ":" << temp_service->description() << " by " << nudge_seconds << " seconds..."; - log_v2::runtime()->warn( + runtime_logger->warn( "\tMax concurrent service checks ({}/{}) has been reached. " "Nudging {}:{} by {} seconds...", currently_running_service_checks, @@ -294,7 +293,7 @@ void loop::_dispatching() { engine_logger(dbg_events | dbg_checks, more) << "We're not executing service checks right now, " << "so we'll skip this event."; - log_v2::events()->debug( + events_logger->debug( "We're not executing service checks right now, so we'll skip " "this event."); run_event = false; @@ -352,7 +351,7 @@ void loop::_dispatching() { engine_logger(dbg_events | dbg_checks, more) << "We're not executing host checks right now, " << "so we'll skip this event."; - log_v2::events()->debug( + events_logger->debug( "We're not executing host checks right now, so we'll skip this " "event."); run_event = false; @@ -397,7 +396,7 @@ void loop::_dispatching() { // Handle the event. engine_logger(dbg_events, more) << "Running event..."; - log_v2::events()->debug("Running event..."); + events_logger->debug("Running event..."); temp_event->handle_timed_event(); // Reschedule the event if necessary. @@ -408,7 +407,7 @@ void loop::_dispatching() { else { engine_logger(dbg_events, most) << "Did not execute scheduled event. Idling for a bit..."; - log_v2::events()->debug( + events_logger->debug( "Did not execute scheduled event. Idling for a bit..."); uint64_t d = static_cast(config->sleep_time() * 1000000000); std::this_thread::sleep_for(std::chrono::nanoseconds(d)); @@ -421,7 +420,7 @@ void loop::_dispatching() { current_time < (*_event_list_low.begin())->run_time)) { engine_logger(dbg_events, most) << "No events to execute at the moment. Idling for a bit..."; - log_v2::events()->debug( + events_logger->debug( "No events to execute at the moment. Idling for a bit..."); // Check for external commands if we're supposed to check as @@ -482,7 +481,7 @@ void loop::adjust_check_scheduling() { com::centreon::engine::service* svc(nullptr); engine_logger(dbg_functions, basic) << "adjust_check_scheduling()"; - log_v2::functions()->trace("adjust_check_scheduling()"); + functions_logger->trace("adjust_check_scheduling()"); /* TODO: - Track host check overhead on a per-host basis @@ -642,7 +641,7 @@ void loop::compensate_for_system_time_change(unsigned long last_time, long time_difference = current_time - last_time; engine_logger(dbg_functions, basic) << "compensate_for_system_time_change()"; - log_v2::functions()->trace("compensate_for_system_time_change()"); + functions_logger->trace("compensate_for_system_time_change()"); // we moved back in time... if (time_difference < 0) { @@ -650,9 +649,8 @@ void loop::compensate_for_system_time_change(unsigned long last_time, engine_logger(dbg_events, basic) << "Detected a backwards time change of " << days << "d " << hours << "h " << minutes << "m " << seconds << "s."; - log_v2::events()->trace( - "Detected a backwards time change of {}d {}h {}m {}s.", days, hours, - minutes, seconds); + events_logger->trace("Detected a backwards time change of {}d {}h {}m {}s.", + days, hours, minutes, seconds); } // we moved into the future... else { @@ -660,9 +658,8 @@ void loop::compensate_for_system_time_change(unsigned long last_time, engine_logger(dbg_events, basic) << "Detected a forwards time change of " << days << "d " << hours << "h " << minutes << "m " << seconds << "s."; - log_v2::events()->trace( - "Detected a forwards time change of {}d {}h {}m {}s.", days, hours, - minutes, seconds); + events_logger->trace("Detected a forwards time change of {}d {}h {}m {}s.", + days, hours, minutes, seconds); } // log the time change. @@ -671,7 +668,7 @@ void loop::compensate_for_system_time_change(unsigned long last_time, << minutes << "m " << seconds << "s (" << (time_difference < 0 ? "backwards" : "forwards") << " in time) has been detected. Compensating..."; - log_v2::runtime()->warn( + runtime_logger->warn( "Warning: A system time change of {}d {}h {}m {}s ({} in time) has been " "detected. Compensating...", days, hours, minutes, seconds, @@ -809,7 +806,7 @@ void loop::compensate_for_system_time_change(unsigned long last_time, void loop::add_event(std::unique_ptr&& event, loop::priority priority) { engine_logger(dbg_functions, basic) << "add_event()"; - log_v2::functions()->trace("add_event()"); + functions_logger->trace("add_event()"); timed_event_list* list; @@ -845,7 +842,7 @@ void loop::add_event(std::unique_ptr&& event, void loop::remove_downtime(uint64_t downtime_id) { engine_logger(dbg_functions, basic) << "loop::remove_downtime()"; - log_v2::functions()->trace("loop::remove_downtime()"); + functions_logger->trace("loop::remove_downtime()"); for (auto it = _event_list_high.begin(), end = _event_list_high.end(); it != end; ++it) { @@ -870,7 +867,7 @@ void loop::remove_downtime(uint64_t downtime_id) { void loop::remove_event(timed_event_list::iterator& it, loop::priority priority) { engine_logger(dbg_functions, basic) << "loop::remove_event()"; - log_v2::functions()->trace("loop::remove_event()"); + functions_logger->trace("loop::remove_event()"); if (priority == loop::low) _event_list_low.erase(it); @@ -886,7 +883,7 @@ void loop::remove_event(timed_event_list::iterator& it, */ void loop::remove_event(timed_event* evt, loop::priority priority) { engine_logger(dbg_functions, basic) << "loop::remove_event()"; - log_v2::functions()->trace("loop::remove_event()"); + functions_logger->trace("loop::remove_event()"); timed_event_list* list; if (priority == loop::low) list = &_event_list_low; @@ -923,7 +920,7 @@ timed_event_list::iterator loop::find_event(loop::priority priority, timed_event_list* list; engine_logger(dbg_functions, basic) << "resort_event_list()"; - log_v2::functions()->trace("resort_event_list()"); + functions_logger->trace("resort_event_list()"); // move current event list to temp list. if (priority == loop::low) @@ -948,7 +945,7 @@ timed_event_list::iterator loop::find_event(loop::priority priority, void loop::reschedule_event(std::unique_ptr&& event, loop::priority priority) { engine_logger(dbg_functions, basic) << "reschedule_event()"; - log_v2::functions()->trace("reschedule_event()"); + functions_logger->trace("reschedule_event()"); // reschedule recurring events... if (event->recurring) { @@ -987,7 +984,7 @@ void loop::resort_event_list(loop::priority priority) { timed_event_list* list; engine_logger(dbg_functions, basic) << "resort_event_list()"; - log_v2::functions()->trace("resort_event_list()"); + functions_logger->trace("resort_event_list()"); // move current event list to temp list. if (priority == loop::low) diff --git a/engine/src/events/sched_info.cc b/engine/src/events/sched_info.cc index 3229b077115..34275aebf0f 100644 --- a/engine/src/events/sched_info.cc +++ b/engine/src/events/sched_info.cc @@ -1,28 +1,27 @@ /** -* Copyright 2007-2008 Ethan Galstad -* Copyright 2007,2010 Andreas Ericsson -* Copyright 2010 Max Schubert -* Copyright 2011-2013 Merethis -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2007-2008 Ethan Galstad + * Copyright 2007,2010 Andreas Ericsson + * Copyright 2010 Max Schubert + * Copyright 2011-2013 Merethis + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/events/sched_info.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/statusdata.hh" #include "com/centreon/engine/string.hh" diff --git a/engine/src/events/timed_event.cc b/engine/src/events/timed_event.cc index e6a67052cfc..e30946218a6 100644 --- a/engine/src/events/timed_event.cc +++ b/engine/src/events/timed_event.cc @@ -1,24 +1,24 @@ /** -* Copyright 2007-2008 Ethan Galstad -* Copyright 2007,2010 Andreas Ericsson -* Copyright 2010 Max Schubert -* Copyright 2011-2013,2016 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2007-2008 Ethan Galstad + * Copyright 2007,2010 Andreas Ericsson + * Copyright 2010 Max Schubert + * Copyright 2011-2013,2016 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/checks/checker.hh" @@ -27,7 +27,6 @@ #include "com/centreon/engine/events/loop.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/objects.hh" #include "com/centreon/engine/retention/dump.hh" @@ -106,7 +105,7 @@ void timed_event::_exec_event_service_check() { << "** Service Check Event ==> Host: '" << svc->get_hostname() << "', Service: '" << svc->description() << "', Options: " << event_options << ", Latency: " << latency << " sec"; - log_v2::events()->trace( + events_logger->trace( "** Service Check Event ==> Host: '{}', Service: '{}', Options: {}, " "Latency: {} sec", svc->get_hostname(), svc->description(), event_options, latency); @@ -121,7 +120,7 @@ void timed_event::_exec_event_service_check() { */ void timed_event::_exec_event_command_check() { engine_logger(dbg_events, basic) << "** External Command Check Event"; - log_v2::events()->trace("** External Command Check Event"); + events_logger->trace("** External Command Check Event"); // send data to event broker. broker_external_command(NEBTYPE_EXTERNALCOMMAND_CHECK, CMD_NONE, NULL, NULL); @@ -133,7 +132,7 @@ void timed_event::_exec_event_command_check() { */ void timed_event::_exec_event_enginerpc_check() { engine_logger(dbg_events, basic) << "** EngineRPC Command Check Event"; - log_v2::events()->trace("** EngineRPC Command Check Event"); + events_logger->trace("** EngineRPC Command Check Event"); // send data to event broker. command_manager::instance().execute(); @@ -151,7 +150,7 @@ void timed_event::_exec_event_log_rotation() {} */ void timed_event::_exec_event_program_shutdown() { engine_logger(dbg_events, basic) << "** Program Shutdown Event"; - log_v2::events()->trace("** Program Shutdown Event"); + events_logger->trace("** Program Shutdown Event"); // set the shutdown flag. sigshutdown = true; @@ -159,8 +158,7 @@ void timed_event::_exec_event_program_shutdown() { // log the shutdown. engine_logger(log_process_info, basic) << "PROGRAM_SHUTDOWN event encountered, shutting down..."; - log_v2::process()->info( - "PROGRAM_SHUTDOWN event encountered, shutting down..."); + process_logger->info("PROGRAM_SHUTDOWN event encountered, shutting down..."); } /** @@ -169,7 +167,7 @@ void timed_event::_exec_event_program_shutdown() { */ void timed_event::_exec_event_program_restart() { engine_logger(dbg_events, basic) << "** Program Restart Event"; - log_v2::events()->trace("** Program Restart Event"); + events_logger->trace("** Program Restart Event"); // reload configuration. sighup = true; @@ -177,7 +175,7 @@ void timed_event::_exec_event_program_restart() { // log the restart. engine_logger(log_process_info, basic) << "PROGRAM_RESTART event encountered, restarting..."; - log_v2::process()->info("PROGRAM_RESTART event encountered, restarting..."); + process_logger->info("PROGRAM_RESTART event encountered, restarting..."); } /** @@ -186,14 +184,14 @@ void timed_event::_exec_event_program_restart() { */ void timed_event::_exec_event_check_reaper() { engine_logger(dbg_events, basic) << "** Check Result Reaper"; - log_v2::events()->trace("** Check Result Reaper"); + events_logger->trace("** Check Result Reaper"); // reap host and service check results. try { checks::checker::instance().reap(); } catch (std::exception const& e) { engine_logger(log_runtime_error, basic) << "Error: " << e.what(); - log_v2::runtime()->error("Error: {}", e.what()); + runtime_logger->error("Error: {}", e.what()); } } @@ -204,7 +202,7 @@ void timed_event::_exec_event_check_reaper() { void timed_event::_exec_event_orphan_check() { engine_logger(dbg_events, basic) << "** Orphaned Host and Service Check Event"; - log_v2::events()->trace("** Orphaned Host and Service Check Event"); + events_logger->trace("** Orphaned Host and Service Check Event"); // check for orphaned hosts and services. if (config->check_orphaned_hosts()) @@ -219,7 +217,7 @@ void timed_event::_exec_event_orphan_check() { */ void timed_event::_exec_event_retention_save() { engine_logger(dbg_events, basic) << "** Retention Data Save Event"; - log_v2::events()->trace("** Retention Data Save Event"); + events_logger->trace("** Retention Data Save Event"); // save state retention data. retention::dump::save(config->state_retention_file()); @@ -231,7 +229,7 @@ void timed_event::_exec_event_retention_save() { */ void timed_event::_exec_event_status_save() { engine_logger(dbg_events, basic) << "** Status Data Save Event"; - log_v2::events()->trace("** Status Data Save Event"); + events_logger->trace("** Status Data Save Event"); // save all status data (program, host, and service). update_all_status_data(); @@ -243,7 +241,7 @@ void timed_event::_exec_event_status_save() { */ void timed_event::_exec_event_scheduled_downtime() { engine_logger(dbg_events, basic) << "** Scheduled Downtime Event"; - log_v2::events()->trace("** Scheduled Downtime Event"); + events_logger->trace("** Scheduled Downtime Event"); // process scheduled downtime info. if (event_data) { @@ -259,7 +257,7 @@ void timed_event::_exec_event_scheduled_downtime() { */ void timed_event::_exec_event_sfreshness_check() { engine_logger(dbg_events, basic) << "** Service Result Freshness Check Event"; - log_v2::events()->trace("** Service Result Freshness Check Event"); + events_logger->trace("** Service Result Freshness Check Event"); // check service result freshness. service::check_result_freshness(); @@ -271,7 +269,7 @@ void timed_event::_exec_event_sfreshness_check() { */ void timed_event::_exec_event_expire_downtime() { engine_logger(dbg_events, basic) << "** Expire Downtime Event"; - log_v2::events()->trace("** Expire Downtime Event"); + events_logger->trace("** Expire Downtime Event"); // check for expired scheduled downtime entries. downtime_manager::instance().check_for_expired_downtime(); @@ -293,7 +291,7 @@ void timed_event::_exec_event_host_check() { engine_logger(dbg_events, basic) << "** Host Check Event ==> Host: '" << hst->name() << "', Options: " << event_options << ", Latency: " << latency << " sec"; - log_v2::events()->trace( + events_logger->trace( "** Host Check Event ==> Host: '{}', Options: {}, Latency: {} sec", hst->name(), event_options, latency); @@ -307,7 +305,7 @@ void timed_event::_exec_event_host_check() { */ void timed_event::_exec_event_hfreshness_check() { engine_logger(dbg_events, basic) << "** Host Result Freshness Check Event"; - log_v2::events()->trace("** Host Result Freshness Check Event"); + events_logger->trace("** Host Result Freshness Check Event"); // check host result freshness. host::check_result_freshness(); @@ -319,7 +317,7 @@ void timed_event::_exec_event_hfreshness_check() { */ void timed_event::_exec_event_reschedule_checks() { engine_logger(dbg_events, basic) << "** Reschedule Checks Event"; - log_v2::events()->trace("** Reschedule Checks Event"); + events_logger->trace("** Reschedule Checks Event"); // adjust scheduling of host and service checks. events::loop::instance().adjust_check_scheduling(); @@ -331,7 +329,7 @@ void timed_event::_exec_event_reschedule_checks() { */ void timed_event::_exec_event_expire_comment() { engine_logger(dbg_events, basic) << "** Expire Comment Event"; - log_v2::events()->trace("** Expire Comment Event"); + events_logger->trace("** Expire Comment Event"); // check for expired comment. comment::remove_if_expired_comment((unsigned long)event_data); @@ -343,7 +341,7 @@ void timed_event::_exec_event_expire_comment() { */ void timed_event::_exec_event_expire_host_ack() { engine_logger(dbg_events, basic) << "** Expire Host Acknowledgement Event"; - log_v2::events()->trace("** Expire Host Acknowledgement Event"); + events_logger->trace("** Expire Host Acknowledgement Event"); static_cast(event_data)->check_for_expired_acknowledgement(); } @@ -353,7 +351,7 @@ void timed_event::_exec_event_expire_host_ack() { */ void timed_event::_exec_event_expire_service_ack() { engine_logger(dbg_events, basic) << "** Expire Service Acknowledgement Event"; - log_v2::events()->trace("** Expire Service Acknowledgement Event"); + events_logger->trace("** Expire Service Acknowledgement Event"); static_cast(event_data)->check_for_expired_acknowledgement(); } @@ -364,7 +362,7 @@ void timed_event::_exec_event_expire_service_ack() { */ void timed_event::_exec_event_user_function() { engine_logger(dbg_events, basic) << "** User Function Event"; - log_v2::events()->trace("** User Function Event"); + events_logger->trace("** User Function Event"); // run a user-defined function. if (event_data) { @@ -390,7 +388,7 @@ void timed_event::_exec_event_user_function() { */ time_t adjust_timestamp_for_time_change(int64_t time_difference, time_t ts) { engine_logger(dbg_functions, basic) << "adjust_timestamp_for_time_change()"; - log_v2::functions()->trace("adjust_timestamp_for_time_change()"); + functions_logger->trace("adjust_timestamp_for_time_change()"); // we shouldn't do anything with epoch or invalid values. if (ts == (time_t)0 || ts == (time_t)-1) @@ -433,7 +431,7 @@ int timed_event::handle_timed_event() { &timed_event::_exec_event_enginerpc_check}; engine_logger(dbg_functions, basic) << "handle_timed_event()"; - log_v2::functions()->trace("handle_timed_event()"); + functions_logger->trace("handle_timed_event()"); // send event data to broker. broker_timed_event(NEBTYPE_TIMEDEVENT_EXECUTE, NEBFLAG_NONE, NEBATTR_NONE, @@ -441,8 +439,8 @@ int timed_event::handle_timed_event() { engine_logger(dbg_events, basic) << "** Timed Event ** Type: " << event_type << ", Run Time: " << my_ctime(&run_time); - log_v2::events()->trace("** Timed Event ** Type: {}, Run Time: {}", - event_type, my_ctime(&run_time)); + events_logger->trace("** Timed Event ** Type: {}, Run Time: {}", event_type, + my_ctime(&run_time)); // how should we handle the event? if (event_type < tab_exec_event.size()) diff --git a/engine/src/flapping.cc b/engine/src/flapping.cc index 15dcb1e1f9f..680752b89db 100644 --- a/engine/src/flapping.cc +++ b/engine/src/flapping.cc @@ -1,28 +1,27 @@ /** -* Copyright 2001-2009 Ethan Galstad -* Copyright 2011-2019 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2001-2009 Ethan Galstad + * Copyright 2011-2024 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/flapping.hh" #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/comment.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/statusdata.hh" @@ -38,7 +37,7 @@ void enable_flap_detection_routines() { unsigned long attr = MODATTR_FLAP_DETECTION_ENABLED; engine_logger(dbg_functions, basic) << "enable_flap_detection_routines()"; - log_v2::functions()->trace("enable_flap_detection_routines()"); + functions_logger->trace("enable_flap_detection_routines()"); /* bail out if we're already set */ if (config->enable_flap_detection()) @@ -76,7 +75,7 @@ void disable_flap_detection_routines() { unsigned long attr = MODATTR_FLAP_DETECTION_ENABLED; engine_logger(dbg_functions, basic) << "disable_flap_detection_routines()"; - log_v2::functions()->trace("disable_flap_detection_routines()"); + functions_logger->trace("disable_flap_detection_routines()"); /* bail out if we're already set */ if (!config->enable_flap_detection()) diff --git a/engine/src/globals.cc b/engine/src/globals.cc index feb2c0f3619..e00e0736d06 100644 --- a/engine/src/globals.cc +++ b/engine/src/globals.cc @@ -1,33 +1,35 @@ /** -* Copyright 1999-2009 Ethan Galstad -* Copyright 2009-2010 Nagios Core Development Team and Community -*Contributors -* Copyright 2011-2013,2016-2017 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 1999-2009 Ethan Galstad + * Copyright 2009-2010 Nagios Core Development Team and Community + *Contributors + * Copyright 2011-2013,2016-2024 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/globals.hh" #include "com/centreon/engine/logging/logger.hh" +#include "common/log_v2/log_v2.hh" #include "nagios.h" using namespace com::centreon::engine; +using com::centreon::common::log_v2::log_v2; -configuration::state* config(NULL); +configuration::state* config = nullptr; char const* sigs[] = {"EXIT", "HUP", "INT", "QUIT", "ILL", "TRAP", "ABRT", "BUS", "FPE", "KILL", "USR1", "SEGV", @@ -38,6 +40,19 @@ char const* sigs[] = {"EXIT", "HUP", "INT", "QUIT", "ILL", "TRAP", com::centreon::engine::restart_stats restart_apply_stats; +std::shared_ptr checks_logger; +std::shared_ptr commands_logger; +std::shared_ptr config_logger; +std::shared_ptr downtimes_logger; +std::shared_ptr eventbroker_logger; +std::shared_ptr events_logger; +std::shared_ptr external_command_logger; +std::shared_ptr functions_logger; +std::shared_ptr macros_logger; +std::shared_ptr notifications_logger; +std::shared_ptr process_logger; +std::shared_ptr runtime_logger; + char* config_file(NULL); char* debug_file(NULL); char* global_host_event_handler(NULL); @@ -116,3 +131,18 @@ unsigned long modified_service_process_attributes(MODATTR_NONE); unsigned long next_event_id(1); unsigned long next_notification_id(1); unsigned long next_problem_id(1); + +void init_loggers() { + checks_logger = log_v2::instance().get(log_v2::CHECKS); + commands_logger = log_v2::instance().get(log_v2::COMMANDS); + config_logger = log_v2::instance().get(log_v2::CONFIG); + downtimes_logger = log_v2::instance().get(log_v2::DOWNTIMES); + eventbroker_logger = log_v2::instance().get(log_v2::EVENTBROKER); + events_logger = log_v2::instance().get(log_v2::EVENTS); + external_command_logger = log_v2::instance().get(log_v2::EXTERNAL_COMMAND); + functions_logger = log_v2::instance().get(log_v2::FUNCTIONS); + macros_logger = log_v2::instance().get(log_v2::MACROS); + notifications_logger = log_v2::instance().get(log_v2::NOTIFICATIONS); + process_logger = log_v2::instance().get(log_v2::PROCESS); + runtime_logger = log_v2::instance().get(log_v2::RUNTIME); +} diff --git a/engine/src/host.cc b/engine/src/host.cc index 801b86f26a2..6a055cbb067 100644 --- a/engine/src/host.cc +++ b/engine/src/host.cc @@ -1,5 +1,5 @@ /** - * Copyright 2011 - 2020 Centreon + * Copyright 2011 - 2024 Centreon * * This file is part of Centreon Engine. * @@ -22,8 +22,6 @@ #include -#include "com/centreon/engine/log_v2.hh" - #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/checks/checker.hh" #include "com/centreon/engine/configuration/applier/state.hh" @@ -267,14 +265,14 @@ host::host(uint64_t host_id, if (name.empty() || address.empty()) { engine_logger(log_config_error, basic) << "Error: Host name or address is nullptr"; - log_v2::config()->error("Error: Host name or address is nullptr"); + config_logger->error("Error: Host name or address is nullptr"); throw engine_error() << "Could not register host '" << name << "'"; } if (host_id == 0) { engine_logger(log_config_error, basic) << "Error: Host must contain a host id " "because it comes from a database"; - log_v2::config()->error( + config_logger->error( "Error: Host must contain a host id " "because it comes from a database"); throw engine_error() << "Could not register host '" << name << "'"; @@ -285,7 +283,7 @@ host::host(uint64_t host_id, if (host_exists(id)) { engine_logger(log_config_error, basic) << "Error: Host '" << name << "' has already been defined"; - log_v2::config()->error("Error: Host '{}' has already been defined", name); + config_logger->error("Error: Host '{}' has already been defined", name); throw engine_error() << "Could not register host '" << name << "'"; } @@ -325,7 +323,7 @@ void host::add_parent_host(const std::string& host_name) { if (host_name.empty()) { engine_logger(log_config_error, basic) << "add child link called with bad host_name"; - log_v2::config()->error("add child link called with bad host_name"); + config_logger->error("add child link called with bad host_name"); throw engine_error() << "add child link called with bad host_name"; } @@ -333,8 +331,8 @@ void host::add_parent_host(const std::string& host_name) { if (name() == host_name) { engine_logger(log_config_error, basic) << "Error: Host '" << name() << "' cannot be a child/parent of itself"; - log_v2::config()->error( - "Error: Host '{}' cannot be a child/parent of itself", name()); + config_logger->error("Error: Host '{}' cannot be a child/parent of itself", + name()); throw engine_error() << "host is child/parent itself"; } @@ -1200,9 +1198,8 @@ int host::log_event() { engine_logger(log_options, basic) << "HOST ALERT: " << name() << ";" << state << ";" << state_type << ";" << get_current_attempt() << ";" << get_plugin_output(); - SPDLOG_LOGGER_INFO(log_v2::events(), "HOST ALERT: {};{};{};{};{}", name(), - state, state_type, get_current_attempt(), - get_plugin_output()); + SPDLOG_LOGGER_INFO(events_logger, "HOST ALERT: {};{};{};{};{}", name(), state, + state_type, get_current_attempt(), get_plugin_output()); return OK; } @@ -1218,8 +1215,7 @@ int host::handle_async_check_result_3x( struct timeval end_time_hires; engine_logger(dbg_functions, basic) << "handle_async_host_check_result_3x()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), - "handle_async_host_check_result_3x()"); + SPDLOG_LOGGER_TRACE(functions_logger, "handle_async_host_check_result_3x()"); /* get the current time */ time_t current_time = std::time(nullptr); @@ -1235,9 +1231,8 @@ int host::handle_async_check_result_3x( engine_logger(dbg_checks, more) << "** Handling async check result for host '" << name() << "'..."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), - "** Handling async check result for host '{}'...", - name()); + SPDLOG_LOGGER_DEBUG( + checks_logger, "** Handling async check result for host '{}'...", name()); engine_logger(dbg_checks, most) << "\tCheck Type: " @@ -1258,27 +1253,27 @@ int host::handle_async_check_result_3x( << "\n" << "\tOutput: " << queued_check_result.get_output(); - SPDLOG_LOGGER_DEBUG(log_v2::checks(), "Check Type: {}", + SPDLOG_LOGGER_DEBUG(checks_logger, "Check Type: {}", queued_check_result.get_check_type() == check_active ? "Active" : "Passive"); - SPDLOG_LOGGER_DEBUG(log_v2::checks(), "Check Options: {}", + SPDLOG_LOGGER_DEBUG(checks_logger, "Check Options: {}", queued_check_result.get_check_options()); SPDLOG_LOGGER_DEBUG( - log_v2::checks(), "Reschedule Check?: {}", + checks_logger, "Reschedule Check?: {}", queued_check_result.get_reschedule_check() ? "Yes" : "No"); SPDLOG_LOGGER_DEBUG( - log_v2::checks(), "Should Reschedule Current Host Check?: {}", + checks_logger, "Should Reschedule Current Host Check?: {}", queued_check_result.get_reschedule_check() ? "Yes" : "No"); - SPDLOG_LOGGER_DEBUG(log_v2::checks(), "Exited OK?: {}", + SPDLOG_LOGGER_DEBUG(checks_logger, "Exited OK?: {}", queued_check_result.get_exited_ok() ? "Yes" : "No"); - SPDLOG_LOGGER_DEBUG(log_v2::checks(), "Exec Time: {:.3f}", + SPDLOG_LOGGER_DEBUG(checks_logger, "Exec Time: {:.3f}", execution_time); - SPDLOG_LOGGER_DEBUG(log_v2::checks(), "Latency: {}", + SPDLOG_LOGGER_DEBUG(checks_logger, "Latency: {}", queued_check_result.get_latency()); - SPDLOG_LOGGER_DEBUG(log_v2::checks(), "return Status: {}", + SPDLOG_LOGGER_DEBUG(checks_logger, "return Status: {}", queued_check_result.get_return_code()); - SPDLOG_LOGGER_DEBUG(log_v2::checks(), "Output: {}", + SPDLOG_LOGGER_DEBUG(checks_logger, "Output: {}", queued_check_result.get_output()); /* decrement the number of host checks still out there... */ if (queued_check_result.get_check_type() == check_active && @@ -1294,7 +1289,7 @@ int host::handle_async_check_result_3x( << "Discarding passive host check result because passive host " "checks are disabled globally."; SPDLOG_LOGGER_TRACE( - log_v2::checks(), + checks_logger, "Discarding passive host check result because passive host " "checks are disabled globally."); @@ -1305,7 +1300,7 @@ int host::handle_async_check_result_3x( << "Discarding passive host check result because passive checks " "are disabled for this host."; SPDLOG_LOGGER_TRACE( - log_v2::checks(), + checks_logger, "Discarding passive host check result because passive checks " "are disabled for this host."); return ERROR; @@ -1333,7 +1328,7 @@ int host::handle_async_check_result_3x( << "Discarding host freshness check result because the host is " "currently fresh (race condition avoided)."; SPDLOG_LOGGER_TRACE( - log_v2::checks(), + checks_logger, "Discarding host freshness check result because the host is " "currently fresh (race condition avoided)."); return OK; @@ -1436,7 +1431,7 @@ int host::handle_async_check_result_3x( << "Perf Data:\n" << (get_perf_data().empty() ? "nullptr" : get_perf_data()); SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "Parsing check output... Short Output: {} Long Output: {} " "Perf Data: {}", get_plugin_output().empty() ? "nullptr" : get_plugin_output(), @@ -1457,7 +1452,7 @@ int host::handle_async_check_result_3x( engine_logger(log_runtime_warning, basic) << "Warning: Check of host '" << name() << "' did not exit properly!"; - SPDLOG_LOGGER_WARN(log_v2::runtime(), + SPDLOG_LOGGER_WARN(runtime_logger, "Warning: Check of host '{}' did not exit properly!", name()); @@ -1481,7 +1476,7 @@ int host::handle_async_check_result_3x( "exists." : ""); SPDLOG_LOGGER_WARN( - log_v2::runtime(), + runtime_logger, "Warning: return (code of {} for check of host '{}' was out of " "bounds.", queued_check_result.get_return_code(), name(), @@ -1543,7 +1538,7 @@ int host::handle_async_check_result_3x( << "** Async check result for host '" << name() << "' handled: new state=" << get_current_state(); SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "** Async check result for host '{}' handled: new state={}", name(), static_cast(get_current_state())); @@ -1568,13 +1563,13 @@ int host::run_scheduled_check(int check_options, double latency) { bool time_is_valid = true; engine_logger(dbg_functions, basic) << "run_scheduled_host_check_3x()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), "run_scheduled_host_check_3x()"); + SPDLOG_LOGGER_TRACE(functions_logger, "run_scheduled_host_check_3x()"); engine_logger(dbg_checks, basic) << "Attempting to run scheduled check of host '" << name() << "': check options=" << check_options << ", latency=" << latency; SPDLOG_LOGGER_TRACE( - log_v2::checks(), + checks_logger, "Attempting to run scheduled check of host '{}': check options={}, " "latency={}", name(), check_options, latency); @@ -1587,7 +1582,7 @@ int host::run_scheduled_check(int check_options, double latency) { if (result == ERROR) { engine_logger(dbg_checks, more) << "Unable to run scheduled host check at this time"; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "Unable to run scheduled host check at this time"); /* only attempt to (re)schedule checks that should get checked... */ @@ -1624,7 +1619,7 @@ int host::run_scheduled_check(int check_options, double latency) { "rescheduled properly. Scheduling check for next week... " << " next_check " << get_next_check(); SPDLOG_LOGGER_WARN( - log_v2::runtime(), + runtime_logger, "Warning: Check of host '{}' could not be rescheduled properly. " "Scheduling check for next week... next_check {}", name(), get_next_check()); @@ -1633,7 +1628,7 @@ int host::run_scheduled_check(int check_options, double latency) { << "Unable to find any valid times to reschedule the next" " host check!"; SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "Unable to find any valid times to reschedule the next host " "check!"); } @@ -1644,8 +1639,7 @@ int host::run_scheduled_check(int check_options, double latency) { engine_logger(dbg_checks, more) << "Rescheduled next host check for " << my_ctime(&next_valid_time); - SPDLOG_LOGGER_DEBUG(log_v2::checks(), - "Rescheduled next host check for {}", + SPDLOG_LOGGER_DEBUG(checks_logger, "Rescheduled next host check for {}", my_ctime(&next_valid_time)); } } @@ -1677,7 +1671,7 @@ int host::run_async_check(int check_options, << "host::run_async_check, check_options=" << check_options << ", latency=" << latency << ", scheduled_check=" << scheduled_check << ", reschedule_check=" << reschedule_check; - SPDLOG_LOGGER_TRACE(log_v2::functions(), + SPDLOG_LOGGER_TRACE(functions_logger, "host::run_async_check, check_options={}, latency={}, " "scheduled_check={}, reschedule_check={}", check_options, latency, scheduled_check, @@ -1688,7 +1682,7 @@ int host::run_async_check(int check_options, engine_logger(log_runtime_error, basic) << "Error: Attempt to run active check on host '" << name() << "' with no check command"; - log_v2::runtime()->error( + runtime_logger->error( "Error: Attempt to run active check on host '{}' with no check command", name()); return ERROR; @@ -1696,8 +1690,8 @@ int host::run_async_check(int check_options, engine_logger(dbg_checks, basic) << "** Running async check of host '" << name() << "'..."; - SPDLOG_LOGGER_TRACE(log_v2::checks(), - "** Running async check of host '{}'...", name()); + SPDLOG_LOGGER_TRACE(checks_logger, "** Running async check of host '{}'...", + name()); // Check if the host is viable now. if (!verify_check_viability(check_options, time_is_valid, preferred_time)) @@ -1716,7 +1710,7 @@ int host::run_async_check(int check_options, << "A check of this host (" << name() << ") is already being executed, so we'll pass for the moment..."; SPDLOG_LOGGER_TRACE( - log_v2::checks(), + checks_logger, "A check of this host ({}) is already being executed, so we'll pass " "for the moment...", name()); @@ -1733,7 +1727,7 @@ int host::run_async_check(int check_options, engine_logger(log_runtime_error, basic) << "Error: Some broker module cancelled check of host '" << name() << "'"; - log_v2::runtime()->error( + runtime_logger->error( "Error: Some broker module cancelled check of host '{}'", name()); return ERROR; } @@ -1743,7 +1737,7 @@ int host::run_async_check(int check_options, << "Some broker module overrode check of host '" << name() << "' so we'll bail out"; SPDLOG_LOGGER_TRACE( - log_v2::functions(), + functions_logger, "Some broker module overrode check of host '{}' so we'll bail out", name()); return OK; @@ -1751,7 +1745,7 @@ int host::run_async_check(int check_options, // Checking starts. engine_logger(dbg_functions, basic) << "Checking host '" << name() << "'..."; - SPDLOG_LOGGER_TRACE(log_v2::functions(), "Checking host '{}'...", name()); + SPDLOG_LOGGER_TRACE(functions_logger, "Checking host '{}'...", name()); // Clear check options. if (scheduled_check) @@ -1824,12 +1818,12 @@ int host::run_async_check(int check_options, // allowed by whitelist? if (!is_whitelist_allowed(processed_cmd)) { - SPDLOG_LOGGER_ERROR(log_v2::commands(), + SPDLOG_LOGGER_ERROR(commands_logger, "host {}: this command cannot be executed because of " "security restrictions on the poller. A whitelist has " "been defined, and it does not include this command.", name()); - SPDLOG_LOGGER_DEBUG(log_v2::commands(), + SPDLOG_LOGGER_DEBUG(commands_logger, "host {}: command not allowed by whitelist {}", name(), processed_cmd); run_failure(configuration::command_blacklist_output); @@ -1840,8 +1834,8 @@ int host::run_async_check(int check_options, retry = false; try { // Run command. - uint64_t id = cmd->run(processed_cmd, *macros, - config->host_check_timeout(), check_result_info); + cmd->run(processed_cmd, *macros, config->host_check_timeout(), + check_result_info); } catch (com::centreon::exceptions::interruption const& e) { retry = true; } catch (std::exception const& e) { @@ -1850,7 +1844,7 @@ int host::run_async_check(int check_options, engine_logger(log_runtime_warning, basic) << "Error: Host check command execution failed: " << e.what(); - SPDLOG_LOGGER_WARN(log_v2::runtime(), + SPDLOG_LOGGER_WARN(runtime_logger, "Error: Host check command execution failed: {}", e.what()); } @@ -1873,7 +1867,7 @@ bool host::schedule_check(time_t check_time, uint32_t options, bool no_update_status_now) { engine_logger(dbg_functions, basic) << "schedule_host_check()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), "schedule_host_check()"); + SPDLOG_LOGGER_TRACE(functions_logger, "schedule_host_check()"); engine_logger(dbg_checks, basic) << "Scheduling a " @@ -1881,7 +1875,7 @@ bool host::schedule_check(time_t check_time, << ", active check of host '" << name() << "' @ " << my_ctime(&check_time); SPDLOG_LOGGER_TRACE( - log_v2::checks(), "Scheduling a {}, active check of host '{}' @ {}", + checks_logger, "Scheduling a {}, active check of host '{}' @ {}", options & CHECK_OPTION_FORCE_EXECUTION ? "forced" : "non-forced", name(), my_ctime(&check_time)); @@ -1889,7 +1883,7 @@ bool host::schedule_check(time_t check_time, if (!active_checks_enabled() && !(options & CHECK_OPTION_FORCE_EXECUTION)) { engine_logger(dbg_checks, basic) << "Active checks are disabled for this host."; - SPDLOG_LOGGER_TRACE(log_v2::checks(), + SPDLOG_LOGGER_TRACE(checks_logger, "Active checks are disabled for this host."); return false; } @@ -1915,7 +1909,7 @@ bool host::schedule_check(time_t check_time, engine_logger(dbg_checks, most) << "Found another host check event for this host @ " << my_ctime(&temp_event->run_time); - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "Found another host check event for this host @ {}", my_ctime(&temp_event->run_time)); /* use the originally scheduled check unless we decide otherwise */ @@ -1931,7 +1925,7 @@ bool host::schedule_check(time_t check_time, << "New host check event is forced and occurs before the " "existing event, so the new event be used instead."; SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "New host check event is forced and occurs before the " "existing event, so the new event be used instead."); use_original_event = false; @@ -1947,7 +1941,7 @@ bool host::schedule_check(time_t check_time, << "New host check event is forced, so it will be used " "instead of the existing event."; SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "New host check event is forced, so it will be used " "instead of the existing event."); } @@ -1960,7 +1954,7 @@ bool host::schedule_check(time_t check_time, << "New host check event occurs before the existing (older) " "event, so it will be used instead."; SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "New host check event occurs before the existing (older) " "event, so it will be used instead."); } @@ -1971,7 +1965,7 @@ bool host::schedule_check(time_t check_time, << "New host check event occurs after the existing event, " "so we'll ignore it."; SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "New host check event occurs after the existing event, " "so we'll ignore it."); } @@ -1986,7 +1980,7 @@ bool host::schedule_check(time_t check_time, engine_logger(dbg_checks, most) << "Keeping original host check event (ignoring the new one)."; SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "Keeping original host check event at {:%Y-%m-%dT%H:%M:%S} (ignoring " "the new one at {:%Y-%m-%dT%H:%M:%S}).", fmt::localtime(get_next_check()), fmt::localtime(check_time)); @@ -1999,7 +1993,7 @@ bool host::schedule_check(time_t check_time, /* use the new event */ if (!use_original_event) { engine_logger(dbg_checks, most) << "Scheduling new host check event."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), "Scheduling new host check event."); + SPDLOG_LOGGER_DEBUG(checks_logger, "Scheduling new host check event."); /* set the next host check time */ set_next_check(check_time); @@ -2040,11 +2034,11 @@ void host::check_for_flapping(bool update, double high_curve_value = 1.25; engine_logger(dbg_functions, basic) << "host::check_for_flapping()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), "host::check_for_flapping()"); + SPDLOG_LOGGER_TRACE(functions_logger, "host::check_for_flapping()"); engine_logger(dbg_flapping, more) << "Checking host '" << name() << "' for flapping..."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), "Checking host '{}' for flapping...", + SPDLOG_LOGGER_DEBUG(checks_logger, "Checking host '{}' for flapping...", name()); time(¤t_time); @@ -2134,7 +2128,7 @@ void host::check_for_flapping(bool update, << com::centreon::logging::setprecision(2) << "LFT=" << low_threshold << ", HFT=" << high_threshold << ", CPC=" << curved_percent_change << ", PSC=" << curved_percent_change << "%"; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), "LFT={:.2f}, HFT={}, CPC={}, PSC={}%", + SPDLOG_LOGGER_DEBUG(checks_logger, "LFT={:.2f}, HFT={}, CPC={}, PSC={}%", low_threshold, high_threshold, curved_percent_change, curved_percent_change); @@ -2165,7 +2159,7 @@ void host::check_for_flapping(bool update, engine_logger(dbg_flapping, more) << "Host " << (is_flapping ? "is" : "is not") << " flapping (" << curved_percent_change << "% state change)."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), "Host {} flapping ({}% state change).", + SPDLOG_LOGGER_DEBUG(checks_logger, "Host {} flapping ({}% state change).", is_flapping ? "is" : "is not", curved_percent_change); /* did the host just start flapping? */ @@ -2183,11 +2177,11 @@ void host::set_flap(double percent_change, double low_threshold [[maybe_unused]], bool allow_flapstart_notification) { engine_logger(dbg_functions, basic) << "set_host_flap()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), "set_host_flap()"); + SPDLOG_LOGGER_TRACE(functions_logger, "set_host_flap()"); engine_logger(dbg_flapping, more) << "Host '" << name() << "' started flapping!"; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), "Host '{}' started flapping!", name()); + SPDLOG_LOGGER_DEBUG(checks_logger, "Host '{}' started flapping!", name()); /* log a notice - this one is parsed by the history CGI */ engine_logger(log_runtime_warning, basic) @@ -2196,7 +2190,7 @@ void host::set_flap(double percent_change, << ";STARTED; Host appears to have started flapping (" << percent_change << "% change > " << high_threshold << "% threshold)"; SPDLOG_LOGGER_WARN( - log_v2::runtime(), + runtime_logger, "HOST FLAPPING ALERT: {};STARTED; Host appears to have started flapping " "({:.1f}% change > {:.1f}% threshold)", name(), percent_change, high_threshold); @@ -2235,11 +2229,11 @@ void host::clear_flap(double percent_change, double high_threshold [[maybe_unused]], double low_threshold) { engine_logger(dbg_functions, basic) << "host::clear_flap()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), "host::clear_flap()"); + SPDLOG_LOGGER_TRACE(functions_logger, "host::clear_flap()"); engine_logger(dbg_flapping, basic) << "Host '" << name() << "' stopped flapping."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), "Host '{}' stopped flapping.", name()); + SPDLOG_LOGGER_DEBUG(checks_logger, "Host '{}' stopped flapping.", name()); /* log a notice - this one is parsed by the history CGI */ engine_logger(log_info_message, basic) @@ -2248,7 +2242,7 @@ void host::clear_flap(double percent_change, << ";STOPPED; Host appears to have stopped flapping (" << percent_change << "% change < " << low_threshold << "% threshold)"; SPDLOG_LOGGER_INFO( - log_v2::events(), + events_logger, "HOST FLAPPING ALERT: {};STOPPED; Host appears to have stopped flapping " "({:.1f}% change < {:.1f}% threshold)", name(), percent_change, low_threshold); @@ -2286,7 +2280,7 @@ void host::check_for_expired_acknowledgement() { if (last_acknowledgement() + acknowledgement_timeout() >= now) { engine_logger(log_info_message, basic) << "Acknowledgement of host '" << name() << "' just expired"; - SPDLOG_LOGGER_INFO(log_v2::events(), + SPDLOG_LOGGER_INFO(events_logger, "Acknowledgement of host '{}' just expired", name()); set_acknowledgement(AckType::NONE); update_status(); @@ -2302,7 +2296,7 @@ int host::handle_state() { time_t current_time; engine_logger(dbg_functions, basic) << "handle_host_state()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), "handle_host_state()"); + SPDLOG_LOGGER_TRACE(functions_logger, "handle_host_state()"); /* get current time */ time(¤t_time); @@ -2465,7 +2459,7 @@ bool host::verify_check_viability(int check_options, int check_interval = 0; engine_logger(dbg_functions, basic) << "check_host_check_viability_3x()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), "check_host_check_viability_3x()"); + SPDLOG_LOGGER_TRACE(functions_logger, "check_host_check_viability_3x()"); /* get the check interval to use if we need to reschedule the check */ if (this->get_state_type() == soft && @@ -2544,11 +2538,10 @@ int host::notify_contact(nagios_macros* mac, int neb_result; engine_logger(dbg_functions, basic) << "notify_contact_of_host()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), "notify_contact_of_host()"); + SPDLOG_LOGGER_TRACE(functions_logger, "notify_contact_of_host()"); engine_logger(dbg_notifications, most) << "** Notifying contact '" << cntct->get_name() << "'"; - log_v2::notifications()->debug("** Notifying contact '{}'", - cntct->get_name()); + notifications_logger->debug("** Notifying contact '{}'", cntct->get_name()); /* get start time */ gettimeofday(&start_time, nullptr); @@ -2592,7 +2585,7 @@ int host::notify_contact(nagios_macros* mac, engine_logger(dbg_notifications, most) << "Raw notification command: " << raw_command; - log_v2::notifications()->debug("Raw notification command: {}", raw_command); + notifications_logger->debug("Raw notification command: {}", raw_command); /* process any macros contained in the argument */ process_macros_r(mac, raw_command, processed_command, macro_options); @@ -2603,8 +2596,8 @@ int host::notify_contact(nagios_macros* mac, engine_logger(dbg_notifications, most) << "Processed notification command: " << processed_command; - log_v2::notifications()->trace("Processed notification command: {}", - processed_command); + notifications_logger->trace("Processed notification command: {}", + processed_command); /* log the notification to program log file */ if (config->log_notifications()) { @@ -2636,10 +2629,10 @@ int host::notify_contact(nagios_macros* mac, << "HOST NOTIFICATION: " << cntct->get_name() << ';' << this->name() << ';' << host_notification_state << ";" << cmd->get_name() << ';' << this->get_plugin_output() << info; - log_v2::notifications()->info("HOST NOTIFICATION: {};{};{};{};{};{}", - cntct->get_name(), this->name(), - host_notification_state, cmd->get_name(), - this->get_plugin_output(), info); + notifications_logger->info("HOST NOTIFICATION: {};{};{};{};{};{}", + cntct->get_name(), this->name(), + host_notification_state, cmd->get_name(), + this->get_plugin_output(), info); } /* run the notification command */ @@ -2651,9 +2644,8 @@ int host::notify_contact(nagios_macros* mac, engine_logger(log_runtime_error, basic) << "Error: can't execute host notification '" << cntct->get_name() << "' : " << e.what(); - log_v2::runtime()->error( - "Error: can't execute host notification '{}' : {}", cntct->get_name(), - e.what()); + runtime_logger->error("Error: can't execute host notification '{}' : {}", + cntct->get_name(), e.what()); } /* check to see if the notification timed out */ @@ -2663,7 +2655,7 @@ int host::notify_contact(nagios_macros* mac, << "' host notification command '" << processed_command << "' timed out after " << config->notification_timeout() << " seconds"; - log_v2::notifications()->info( + notifications_logger->info( "Warning: Contact '{}' host notification command '{}' timed out " "after {} seconds", cntct->get_name(), processed_command, config->notification_timeout()); @@ -2708,11 +2700,11 @@ void host::disable_flap_detection() { unsigned long attr = MODATTR_FLAP_DETECTION_ENABLED; engine_logger(dbg_functions, basic) << "disable_host_flap_detection()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), "disable_host_flap_detection()"); + SPDLOG_LOGGER_TRACE(functions_logger, "disable_host_flap_detection()"); engine_logger(dbg_functions, more) << "Disabling flap detection for host '" << name() << "'."; - log_v2::functions()->debug("Disabling flap detection for host '{}'.", name()); + functions_logger->debug("Disabling flap detection for host '{}'.", name()); /* nothing to do... */ if (!flap_detection_enabled()) @@ -2737,12 +2729,12 @@ void host::enable_flap_detection() { unsigned long attr = MODATTR_FLAP_DETECTION_ENABLED; engine_logger(dbg_functions, basic) << "host::enable_flap_detection()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), "host::enable_flap_detection()"); + SPDLOG_LOGGER_TRACE(functions_logger, "host::enable_flap_detection()"); engine_logger(dbg_flapping, more) << "Enabling flap detection for host '" << name() << "'."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), - "Enabling flap detection for host '{}'.", name()); + SPDLOG_LOGGER_DEBUG(checks_logger, "Enabling flap detection for host '{}'.", + name()); /* nothing to do... */ if (flap_detection_enabled()) @@ -2776,7 +2768,7 @@ bool host::is_valid_escalation_for_notification(escalation const* e, engine_logger(dbg_functions, basic) << "host::is_valid_escalation_for_notification()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), + SPDLOG_LOGGER_TRACE(functions_logger, "host::is_valid_escalation_for_notification()"); /* get the current time */ @@ -2844,7 +2836,7 @@ bool host::is_result_fresh(time_t current_time, int log_this) { engine_logger(dbg_checks, most) << "Checking freshness of host '" << name() << "'..."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), "Checking freshness of host '{}'...", + SPDLOG_LOGGER_DEBUG(checks_logger, "Checking freshness of host '{}'...", name()); /* use user-supplied freshness threshold or auto-calculate a freshness @@ -2864,7 +2856,7 @@ bool host::is_result_fresh(time_t current_time, int log_this) { engine_logger(dbg_checks, most) << "Freshness thresholds: host=" << get_freshness_threshold() << ", use=" << freshness_threshold; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), "Freshness thresholds: host={}, use={}", + SPDLOG_LOGGER_DEBUG(checks_logger, "Freshness thresholds: host={}, use={}", get_freshness_threshold(), freshness_threshold); /* calculate expiration time */ @@ -2891,7 +2883,7 @@ bool host::is_result_fresh(time_t current_time, int log_this) { << "HBC: " << has_been_checked() << ", PS: " << program_start << ", ES: " << event_start << ", LC: " << get_last_check() << ", CT: " << current_time << ", ET: " << expiration_time; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "HBC: {}, PS: {}, ES: {}, LC: {}, CT: {}, ET: {}", has_been_checked(), program_start, event_start, get_last_check(), current_time, expiration_time); @@ -2913,7 +2905,7 @@ bool host::is_result_fresh(time_t current_time, int log_this) { << "s). I'm forcing an immediate check of" " the host."; SPDLOG_LOGGER_WARN( - log_v2::runtime(), + runtime_logger, "Warning: The results of host '{}' are stale by {}d {}h {}m {}s " "(threshold={}d {}h {}m {}s). I'm forcing an immediate check of the " "host.", @@ -2928,7 +2920,7 @@ bool host::is_result_fresh(time_t current_time, int log_this) { << "s). " "Forcing an immediate check of the host..."; SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "Check results for host '{}' are stale by {}d {}h {}m {}s " "(threshold={}d {}h {}m {}s). Forcing an immediate check of the " "host...", @@ -2939,8 +2931,8 @@ bool host::is_result_fresh(time_t current_time, int log_this) { } else engine_logger(dbg_checks, more) << "Check results for host '" << this->name() << "' are fresh."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), - "Check results for host '{}' are fresh.", this->name()); + SPDLOG_LOGGER_DEBUG(checks_logger, "Check results for host '{}' are fresh.", + this->name()); return true; } @@ -2950,7 +2942,7 @@ bool host::is_result_fresh(time_t current_time, int log_this) { void host::handle_flap_detection_disabled() { engine_logger(dbg_functions, basic) << "handle_host_flap_detection_disabled()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), + SPDLOG_LOGGER_TRACE(functions_logger, "handle_host_flap_detection_disabled()"); /* if the host was flapping, remove the flapping indicator */ if (get_is_flapping()) { @@ -2966,7 +2958,7 @@ void host::handle_flap_detection_disabled() { << "HOST FLAPPING ALERT: " << this->name() << ";DISABLED; Flap detection has been disabled"; SPDLOG_LOGGER_INFO( - log_v2::events(), + events_logger, "HOST FLAPPING ALERT: {};DISABLED; Flap detection has been disabled", this->name()); @@ -2986,7 +2978,7 @@ int host::perform_on_demand_check(enum host::host_state* check_return_code, int use_cached_result, unsigned long check_timestamp_horizon) { engine_logger(dbg_functions, basic) << "perform_on_demand_host_check()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), "perform_on_demand_host_check()"); + SPDLOG_LOGGER_TRACE(functions_logger, "perform_on_demand_host_check()"); perform_on_demand_check_3x(check_return_code, check_options, use_cached_result, check_timestamp_horizon); @@ -3001,11 +2993,11 @@ int host::perform_on_demand_check_3x(host::host_state* check_result_code, int result = OK; engine_logger(dbg_functions, basic) << "perform_on_demand_host_check_3x()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), "perform_on_demand_host_check_3x()"); + SPDLOG_LOGGER_TRACE(functions_logger, "perform_on_demand_host_check_3x()"); engine_logger(dbg_checks, basic) << "** On-demand check for host '" << name() << "'..."; - SPDLOG_LOGGER_TRACE(log_v2::checks(), "** On-demand check for host '{}'...", + SPDLOG_LOGGER_TRACE(checks_logger, "** On-demand check for host '{}'...", name()); /* check the status of the host */ @@ -3026,7 +3018,7 @@ int host::run_sync_check_3x(enum host::host_state* check_result_code, << ", use_cached_result=" << use_cached_result << ", check_timestamp_horizon=" << check_timestamp_horizon; SPDLOG_LOGGER_TRACE( - log_v2::functions(), + functions_logger, "run_sync_host_check_3x: hst={}, check_options={}, use_cached_result={}, " "check_timestamp_horizon={}", (void*)this, check_options, use_cached_result, check_timestamp_horizon); @@ -3037,7 +3029,7 @@ int host::run_sync_check_3x(enum host::host_state* check_result_code, check_timestamp_horizon); } catch (std::exception const& e) { engine_logger(log_runtime_error, basic) << "Error: " << e.what(); - log_v2::runtime()->error("Error: {}", e.what()); + runtime_logger->error("Error: {}", e.what()); return ERROR; } return OK; @@ -3063,7 +3055,7 @@ int host::process_check_result_3x(enum host::host_state new_state, bool has_parent; engine_logger(dbg_functions, basic) << "process_host_check_result_3x()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), "process_host_check_result_3x()"); + SPDLOG_LOGGER_TRACE(functions_logger, "process_host_check_result_3x()"); engine_logger(dbg_checks, more) << "HOST: " << name() << ", ATTEMPT=" << get_current_attempt() << "/" @@ -3072,7 +3064,7 @@ int host::process_check_result_3x(enum host::host_state new_state, << ", STATE TYPE=" << (get_state_type() == hard ? "HARD" : "SOFT") << ", OLD STATE=" << get_current_state() << ", NEW STATE=" << new_state; SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "HOST: {}, ATTEMPT={}/{}, CHECK TYPE={}, STATE TYPE={}, OLD STATE={}, " "NEW STATE={}", name(), get_current_attempt(), max_check_attempts(), @@ -3093,15 +3085,14 @@ int host::process_check_result_3x(enum host::host_state new_state, engine_logger(log_passive_check, basic) << "PASSIVE HOST CHECK: " << name() << ";" << new_state << ";" << get_plugin_output(); - SPDLOG_LOGGER_DEBUG(log_v2::checks(), "PASSIVE HOST CHECK: {};{};{}", - name(), static_cast(new_state), - get_plugin_output()); + SPDLOG_LOGGER_DEBUG(checks_logger, "PASSIVE HOST CHECK: {};{};{}", name(), + static_cast(new_state), get_plugin_output()); } /******* HOST WAS DOWN/UNREACHABLE INITIALLY *******/ if (_current_state != host::state_up) { engine_logger(dbg_checks, more) << "Host was DOWN/UNREACHABLE."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), "Host was DOWN/UNREACHABLE."); + SPDLOG_LOGGER_DEBUG(checks_logger, "Host was DOWN/UNREACHABLE."); /***** HOST IS NOW UP *****/ /* the host just recovered! */ @@ -3121,7 +3112,7 @@ int host::process_check_result_3x(enum host::host_state new_state, << "Host experienced a " << (get_state_type() == hard ? "HARD" : "SOFT") << " recovery (it's now UP)."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "Host experienced a {} recovery (it's now UP).", get_state_type() == hard ? "HARD" : "SOFT"); @@ -3133,7 +3124,7 @@ int host::process_check_result_3x(enum host::host_state new_state, * somewhere and we should catch the recovery as soon as possible */ engine_logger(dbg_checks, more) << "Propagating checks to parent host(s)..."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "Propagating checks to parent host(s)..."); for (host_map_unsafe::iterator it{parent_hosts.begin()}, @@ -3144,7 +3135,7 @@ int host::process_check_result_3x(enum host::host_state new_state, if (it->second->get_current_state() != host::state_up) { engine_logger(dbg_checks, more) << "Check of parent host '" << it->first << "' queued."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "Check of parent host '{}' queued.", it->first); check_hostlist.push_back(it->second); } @@ -3155,7 +3146,7 @@ int host::process_check_result_3x(enum host::host_state new_state, * result of this recovery) switch to UP or DOWN states */ engine_logger(dbg_checks, more) << "Propagating checks to child host(s)..."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "Propagating checks to child host(s)..."); for (host_map_unsafe::iterator it{child_hosts.begin()}, @@ -3166,8 +3157,8 @@ int host::process_check_result_3x(enum host::host_state new_state, if (it->second->get_current_state() != host::state_up) { engine_logger(dbg_checks, more) << "Check of child host '" << it->first << "' queued."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), - "Check of child host '{}' queued.", it->first); + SPDLOG_LOGGER_DEBUG(checks_logger, "Check of child host '{}' queued.", + it->first); check_hostlist.push_back(it->second); } } @@ -3177,7 +3168,7 @@ int host::process_check_result_3x(enum host::host_state new_state, /* we're still in a problem state... */ else { engine_logger(dbg_checks, more) << "Host is still DOWN/UNREACHABLE."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), "Host is still DOWN/UNREACHABLE."); + SPDLOG_LOGGER_DEBUG(checks_logger, "Host is still DOWN/UNREACHABLE."); /* set the state type */ /* we've maxed out on the retries */ @@ -3209,13 +3200,13 @@ int host::process_check_result_3x(enum host::host_state new_state, /******* HOST WAS UP INITIALLY *******/ else { engine_logger(dbg_checks, more) << "Host was UP."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), "Host was UP."); + SPDLOG_LOGGER_DEBUG(checks_logger, "Host was UP."); /***** HOST IS STILL UP *****/ /* either the host never went down since last check */ if (new_state == host::state_up) { engine_logger(dbg_checks, more) << "Host is still UP."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), "Host is still UP."); + SPDLOG_LOGGER_DEBUG(checks_logger, "Host is still UP."); /* set the current state */ _current_state = host::state_up; @@ -3227,12 +3218,12 @@ int host::process_check_result_3x(enum host::host_state new_state, /***** HOST IS NOW DOWN/UNREACHABLE *****/ else { engine_logger(dbg_checks, more) << "Host is now DOWN/UNREACHABLE."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), "Host is now DOWN/UNREACHABLE."); + SPDLOG_LOGGER_DEBUG(checks_logger, "Host is now DOWN/UNREACHABLE."); /***** SPECIAL CASE FOR HOSTS WITH MAX_ATTEMPTS==1 *****/ if (max_check_attempts() == 1) { engine_logger(dbg_checks, more) << "Max attempts = 1!."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), "Max attempts = 1!."); + SPDLOG_LOGGER_DEBUG(checks_logger, "Max attempts = 1!."); /* set the state type */ set_state_type(hard); @@ -3255,7 +3246,7 @@ int host::process_check_result_3x(enum host::host_state new_state, << "** WARNING: Max attempts = 1, so we have to run serial " "checks of all parent hosts!"; SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "** WARNING: Max attempts = 1, so we have to run serial " "checks of all parent hosts!"); @@ -3269,7 +3260,7 @@ int host::process_check_result_3x(enum host::host_state new_state, engine_logger(dbg_checks, more) << "Running serial check parent host '" << it->first << "'..."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "Running serial check parent host '{}'...", it->first); @@ -3282,7 +3273,7 @@ int host::process_check_result_3x(enum host::host_state new_state, if (parent_state == host::state_up) { engine_logger(dbg_checks, more) << "Parent host is UP, so this one is DOWN."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "Parent host is UP, so this one is DOWN."); /* set the current state */ @@ -3296,7 +3287,7 @@ int host::process_check_result_3x(enum host::host_state new_state, if (parent_hosts.empty()) { engine_logger(dbg_checks, more) << "Host has no parents, so it's DOWN."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "Host has no parents, so it's DOWN."); _current_state = host::state_down; } else { @@ -3304,7 +3295,7 @@ int host::process_check_result_3x(enum host::host_state new_state, engine_logger(dbg_checks, more) << "No parents were UP, so this host is UNREACHABLE."; SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "No parents were UP, so this host is UNREACHABLE."); _current_state = host::state_unreachable; } @@ -3323,7 +3314,7 @@ int host::process_check_result_3x(enum host::host_state new_state, engine_logger(dbg_checks, more) << "Propagating check to immediate non-UNREACHABLE child hosts..."; SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "Propagating check to immediate non-UNREACHABLE child hosts..."); for (host_map_unsafe::iterator it{child_hosts.begin()}, @@ -3334,7 +3325,7 @@ int host::process_check_result_3x(enum host::host_state new_state, if (it->second->get_current_state() != host::state_unreachable) { engine_logger(dbg_checks, more) << "Check of child host '" << it->first << "' queued."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "Check of child host '{}' queued.", it->first); check_hostlist.push_back(it->second); } @@ -3367,7 +3358,7 @@ int host::process_check_result_3x(enum host::host_state new_state, engine_logger(dbg_checks, more) << "Propagating checks to immediate parent hosts that " "are UP..."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "Propagating checks to immediate parent hosts that " "are UP..."); @@ -3380,7 +3371,7 @@ int host::process_check_result_3x(enum host::host_state new_state, check_hostlist.push_back(it->second); engine_logger(dbg_checks, more) << "Check of host '" << it->first << "' queued."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), "Check of host '{}' queued.", + SPDLOG_LOGGER_DEBUG(checks_logger, "Check of host '{}' queued.", it->first); } } @@ -3390,7 +3381,7 @@ int host::process_check_result_3x(enum host::host_state new_state, engine_logger(dbg_checks, more) << "Propagating checks to immediate non-UNREACHABLE " "child hosts..."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "Propagating checks to immediate non-UNREACHABLE " "child hosts..."); @@ -3402,7 +3393,7 @@ int host::process_check_result_3x(enum host::host_state new_state, if (it->second->get_current_state() != host::state_unreachable) { engine_logger(dbg_checks, more) << "Check of child host '" << it->first << "' queued."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "Check of child host '{}' queued.", it->first); check_hostlist.push_back(it->second); } @@ -3419,7 +3410,7 @@ int host::process_check_result_3x(enum host::host_state new_state, << "Propagating predictive dependency checks to hosts this " "one depends on..."; SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "Propagating predictive dependency checks to hosts this " "one depends on..."); @@ -3433,8 +3424,7 @@ int host::process_check_result_3x(enum host::host_state new_state, master_host = (host*)temp_dependency->master_host_ptr; engine_logger(dbg_checks, more) << "Check of host '" << master_host->name() << "' queued."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), - "Check of host '{}' queued.", + SPDLOG_LOGGER_DEBUG(checks_logger, "Check of host '{}' queued.", master_host->name()); check_hostlist.push_back(master_host); } @@ -3450,7 +3440,7 @@ int host::process_check_result_3x(enum host::host_state new_state, << ", Type=" << (get_state_type() == hard ? "HARD" : "SOFT") << ", Final State=" << _current_state; SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "Pre-handle_host_state() Host: {}, Attempt={}/{}, Type={}, Final " "State={}", name(), get_current_attempt(), max_check_attempts(), @@ -3466,7 +3456,7 @@ int host::process_check_result_3x(enum host::host_state new_state, << ", Type=" << (get_state_type() == hard ? "HARD" : "SOFT") << ", Final State=" << _current_state; SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "Post-handle_host_state() Host: {}, Attempt={}/{}, Type={}, Final " "State={}", name(), get_current_attempt(), max_check_attempts(), @@ -3499,7 +3489,7 @@ int host::process_check_result_3x(enum host::host_state new_state, if (reschedule_check) { engine_logger(dbg_checks, more) << "Rescheduling next check of host at " << my_ctime(&next_check); - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "Rescheduling next check of host: {} of last check at " "{:%Y-%m-%dT%H:%M:%S} and next " "check at {:%Y-%m-%dT%H:%M:%S}", @@ -3564,7 +3554,7 @@ int host::process_check_result_3x(enum host::host_state new_state, << ", USECACHEDRESULT: " << use_cached_result << ", ISEXECUTING: " << temp_host->get_is_executing(); SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "ASYNC CHECK OF HOST: {}, CURRENTTIME: {}, LASTHOSTCHECK: {}, " "CACHEDTIMEHORIZON: {}, USECACHEDRESULT: {}, ISEXECUTING: {}", temp_host->name(), current_time, temp_host->get_last_check(), @@ -3598,11 +3588,11 @@ enum host::host_state host::determine_host_reachability( bool is_host_present = false; engine_logger(dbg_functions, basic) << "determine_host_reachability()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), "determine_host_reachability()"); + SPDLOG_LOGGER_TRACE(functions_logger, "determine_host_reachability()"); engine_logger(dbg_checks, most) << "Determining state of host '" << name() << "': current state=" << new_state; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "Determining state of host '{}': current state= {}", name(), static_cast(new_state)); @@ -3611,7 +3601,7 @@ enum host::host_state host::determine_host_reachability( state = host::state_up; engine_logger(dbg_checks, most) << "Host is UP, no state translation needed."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "Host is UP, no state translation needed."); } @@ -3619,8 +3609,7 @@ enum host::host_state host::determine_host_reachability( else if (parent_hosts.size() == 0) { state = host::state_down; engine_logger(dbg_checks, most) << "Host has no parents, so it is DOWN."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), - "Host has no parents, so it is DOWN."); + SPDLOG_LOGGER_DEBUG(checks_logger, "Host has no parents, so it is DOWN."); } /* check all parent hosts to see if we're DOWN or UNREACHABLE */ @@ -3638,7 +3627,7 @@ enum host::host_state host::determine_host_reachability( state = host::state_down; engine_logger(dbg_checks, most) << "At least one parent (" << it->first << ") is up, so host is DOWN."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "At least one parent ({}) is up, so host is DOWN.", it->first); break; @@ -3649,7 +3638,7 @@ enum host::host_state host::determine_host_reachability( state = host::state_unreachable; engine_logger(dbg_checks, most) << "No parents were up, so host is UNREACHABLE."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "No parents were up, so host is UNREACHABLE."); } } @@ -3675,8 +3664,7 @@ std::list& host::get_parent_groups() { */ bool host::authorized_by_dependencies(dependency::types dependency_type) const { engine_logger(dbg_functions, basic) << "host::authorized_by_dependencies()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), - "host::authorized_by_dependencies()"); + SPDLOG_LOGGER_TRACE(functions_logger, "host::authorized_by_dependencies()"); auto p(hostdependency::hostdependencies.equal_range(name())); for (hostdependency_mmap::const_iterator it{p.first}, end{p.second}; @@ -3729,18 +3717,17 @@ void host::check_result_freshness() { time_t current_time = 0L; engine_logger(dbg_functions, basic) << "check_host_result_freshness()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), "check_host_result_freshness()"); + SPDLOG_LOGGER_TRACE(functions_logger, "check_host_result_freshness()"); engine_logger(dbg_checks, most) << "Attempting to check the freshness of host check results..."; SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "Attempting to check the freshness of host check results..."); /* bail out if we're not supposed to be checking freshness */ if (!config->check_host_freshness()) { engine_logger(dbg_checks, most) << "Host freshness checking is disabled."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), - "Host freshness checking is disabled."); + SPDLOG_LOGGER_DEBUG(checks_logger, "Host freshness checking is disabled."); return; } @@ -3797,7 +3784,7 @@ void host::check_result_freshness() { */ void host::adjust_check_attempt(bool is_active) { engine_logger(dbg_functions, basic) << "adjust_host_check_attempt_3x()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), "adjust_host_check_attempt_3x()"); + SPDLOG_LOGGER_TRACE(functions_logger, "adjust_host_check_attempt_3x()"); engine_logger(dbg_checks, most) << "Adjusting check attempt number for host '" << name() @@ -3806,7 +3793,7 @@ void host::adjust_check_attempt(bool is_active) { << ", state=" << static_cast(_current_state) << ", state type=" << get_state_type(); SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "Adjusting check attempt number for host '{}': current attempt= {}/{}, " "state= {}, state type= {}", name(), get_current_attempt(), max_check_attempts(), @@ -3828,7 +3815,7 @@ void host::adjust_check_attempt(bool is_active) { engine_logger(dbg_checks, most) << "New check attempt number = " << get_current_attempt(); - SPDLOG_LOGGER_DEBUG(log_v2::checks(), "New check attempt number = {}", + SPDLOG_LOGGER_DEBUG(checks_logger, "New check attempt number = {}", get_current_attempt()); } @@ -3838,7 +3825,7 @@ void host::check_for_orphaned() { time_t expected_time = 0L; engine_logger(dbg_functions, basic) << "check_for_orphaned_hosts()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), "check_for_orphaned_hosts()"); + SPDLOG_LOGGER_TRACE(functions_logger, "check_for_orphaned_hosts()"); /* get the current time */ time(¤t_time); @@ -3871,7 +3858,7 @@ void host::check_for_orphaned() { << "' looks like it was orphaned (results never came back). " "I'm scheduling an immediate check of the host..."; SPDLOG_LOGGER_WARN( - log_v2::runtime(), + runtime_logger, "Warning: The check of host '{}' looks like it was orphaned (results " "never came back). " "I'm scheduling an immediate check of the host...", @@ -3881,7 +3868,7 @@ void host::check_for_orphaned() { << "Host '" << it->second->name() << "' was orphaned, so we're scheduling an immediate check..."; SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "Host '{}' was orphaned, so we're scheduling an immediate check...", it->second->name()); @@ -3929,7 +3916,7 @@ void host::resolve(int& w, int& e) { engine_logger(log_verification_error, basic) << "Error: Host '" << name() << "' has problem in its notifier part: " << e.what(); - log_v2::config()->error( + config_logger->error( "Error: Host '{}' has problem in its notifier part: {}", name(), e.what()); } @@ -3945,7 +3932,7 @@ void host::resolve(int& w, int& e) { engine_logger(log_verification_error, basic) << "Warning: Host '" << name() << "' has no services associated with it!"; - log_v2::config()->warn( + config_logger->warn( "Warning: Host '{}' has no services associated with it!", name()); ++w; } else { @@ -3956,7 +3943,7 @@ void host::resolve(int& w, int& e) { engine_logger(log_verification_error, basic) << "Error: Host '" << name() << "' has a service '" << it->first.second << "' that does not exist!"; - log_v2::config()->error( + config_logger->error( "Error: Host '{}' has a service '{}' that does not exist!", name(), it->first.second); ++errors; @@ -3976,9 +3963,8 @@ void host::resolve(int& w, int& e) { << "' is not a " "valid parent for host '" << name() << "'!"; - log_v2::config()->error( - "Error: '{}' is not a valid parent for host '{}'!", it->first, - name()); + config_logger->error("Error: '{}' is not a valid parent for host '{}'!", + it->first, name()); errors++; } else { it->second = it_host->second.get(); @@ -3992,7 +3978,7 @@ void host::resolve(int& w, int& e) { engine_logger(log_verification_error, basic) << "Error: The name of host '" << name() << "' contains one or more illegal characters."; - log_v2::config()->error( + config_logger->error( "Error: The name of host '{}' contains one or more illegal characters.", name()); errors++; @@ -4006,7 +3992,7 @@ void host::resolve(int& w, int& e) { << get_display_name() << "' definition doesn't make any sense - specify down and/or " "unreachable options as well"; - log_v2::config()->warn( + config_logger->warn( "Warning: Recovery notification option in host '{}' definition doesn't " "make any sense - specify down and/or " "unreachable options as well", diff --git a/engine/src/hostdependency.cc b/engine/src/hostdependency.cc index 26ed61ad034..15390f5e731 100644 --- a/engine/src/hostdependency.cc +++ b/engine/src/hostdependency.cc @@ -1,28 +1,27 @@ /** -* Copyright 2011-2019 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2024 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/hostdependency.hh" #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/shared.hh" #include "com/centreon/engine/string.hh" @@ -237,7 +236,7 @@ void hostdependency::resolve(int& w, int& e) { << "Error: Dependent host specified in host dependency for " "host '" << _dependent_hostname << "' is not defined anywhere!"; - log_v2::config()->error( + config_logger->error( "Error: Dependent host specified in host dependency for " "host '{}' is not defined anywhere!", _dependent_hostname); @@ -252,7 +251,7 @@ void hostdependency::resolve(int& w, int& e) { engine_logger(log_verification_error, basic) << "Error: Host specified in host dependency for host '" << _dependent_hostname << "' is not defined anywhere!"; - log_v2::config()->error( + config_logger->error( "Error: Host specified in host dependency for host '{}' is not defined " "anywhere!", _dependent_hostname); @@ -266,7 +265,7 @@ void hostdependency::resolve(int& w, int& e) { engine_logger(log_verification_error, basic) << "Error: Host dependency definition for host '" << _dependent_hostname << "' is circular (it depends on itself)!"; - log_v2::config()->error( + config_logger->error( "Error: Host dependency definition for host '{}' is circular (it " "depends on itself)!", _dependent_hostname); @@ -283,7 +282,7 @@ void hostdependency::resolve(int& w, int& e) { << "Error: Dependency period '" << this->get_dependency_period() << "' specified in host dependency for host '" << _dependent_hostname << "' is not defined anywhere!"; - log_v2::config()->error( + config_logger->error( "Error: Dependency period '{}' specified in host dependency for host " "'{}' is not defined anywhere!", this->get_dependency_period(), _dependent_hostname); diff --git a/engine/src/hostescalation.cc b/engine/src/hostescalation.cc index d5f4f5ba300..f74633f07b6 100644 --- a/engine/src/hostescalation.cc +++ b/engine/src/hostescalation.cc @@ -1,28 +1,27 @@ /** -* Copyright 2011-2019 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2024 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/hostescalation.hh" #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/shared.hh" #include "com/centreon/engine/string.hh" @@ -79,7 +78,7 @@ std::string const& hostescalation::get_hostname() const { */ bool hostescalation::is_viable(int state, uint32_t notification_number) const { engine_logger(dbg_functions, basic) << "serviceescalation::is_viable()"; - log_v2::functions()->trace("serviceescalation::is_viable()"); + functions_logger->trace("serviceescalation::is_viable()"); bool retval{escalation::is_viable(state, notification_number)}; if (retval) { @@ -106,7 +105,7 @@ void hostescalation::resolve(int& w, int& e) { engine_logger(log_verification_error, basic) << "Error: Host '" << this->get_hostname() << "' specified in host escalation is not defined anywhere!"; - log_v2::config()->error( + config_logger->error( "Error: Host '{}' specified in host escalation is not defined " "anywhere!", this->get_hostname()); @@ -122,7 +121,7 @@ void hostescalation::resolve(int& w, int& e) { } catch (std::exception const& ee) { engine_logger(log_verification_error, basic) << "Error: Notifier escalation error: " << ee.what(); - log_v2::config()->error("Error: Notifier escalation error: {}", ee.what()); + config_logger->error("Error: Notifier escalation error: {}", ee.what()); } // Add errors. diff --git a/engine/src/hostgroup.cc b/engine/src/hostgroup.cc index fdf70339488..54a911fb717 100644 --- a/engine/src/hostgroup.cc +++ b/engine/src/hostgroup.cc @@ -1,28 +1,27 @@ /** -* Copyright 2011-2019 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2024 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/hostgroup.hh" #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/shared.hh" #include "com/centreon/engine/string.hh" @@ -60,7 +59,7 @@ hostgroup::hostgroup(uint64_t id, // Make sure we have the data we need. if (name.empty()) { engine_logger(log_config_error, basic) << "Error: Hostgroup name is NULL"; - log_v2::config()->error("Error: Hostgroup name is NULL"); + config_logger->error("Error: Hostgroup name is NULL"); throw(engine_error() << "Could not register host group '" << name << "'"); } @@ -69,8 +68,8 @@ hostgroup::hostgroup(uint64_t id, if (found != hostgroup::hostgroups.end()) { engine_logger(log_config_error, basic) << "Error: Hostgroup '" << name << "' has already been defined"; - log_v2::config()->error("Error: Hostgroup '{}' has already been defined", - name); + config_logger->error("Error: Hostgroup '{}' has already been defined", + name); throw(engine_error() << "Could not register host group '" << name << "'"); } } @@ -168,7 +167,7 @@ void hostgroup::resolve(int& w, int& e) { engine_logger(log_verification_error, basic) << "Error: Host '" << it->first << "' specified in host group '" << get_group_name() << "' is not defined anywhere!"; - log_v2::config()->error( + config_logger->error( "Error: Host '{}' specified in host group '{}' is not defined " "anywhere!", it->first, get_group_name()); @@ -195,7 +194,7 @@ void hostgroup::resolve(int& w, int& e) { engine_logger(log_verification_error, basic) << "Error: The name of hostgroup '" << get_group_name() << "' contains one or more illegal characters."; - log_v2::config()->error( + config_logger->error( "Error: The name of hostgroup '{}' contains one or more illegal " "characters.", get_group_name()); diff --git a/engine/src/log_v2.cc b/engine/src/log_v2.cc deleted file mode 100644 index 699f0d8bc97..00000000000 --- a/engine/src/log_v2.cc +++ /dev/null @@ -1,250 +0,0 @@ -/** -* Copyright 2021-2022 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ - -#include "com/centreon/engine/log_v2.hh" -#include -#include -#include -#include -#include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/logging/broker_sink.hh" - -using namespace com::centreon::engine; -using namespace spdlog; - -std::shared_ptr log_v2::_instance; - -void log_v2::load(const std::shared_ptr& io_context) { - _instance.reset(new log_v2(io_context)); -} - -std::shared_ptr log_v2::instance() { - return _instance; -} - -log_v2::log_v2(const std::shared_ptr& io_context) - : log_v2_base("engine"), - _running{false}, - _flush_timer(*io_context), - _flush_timer_active(true), - _io_context(io_context) { - auto stdout_sink = std::make_shared(); - auto create_logger = [&](const std::string& name, level::level_enum lvl) { - spdlog::drop(name); - auto log = std::make_shared(name, this, stdout_sink); - log->set_level(lvl); - log->flush_on(lvl); - log->set_pattern("[%Y-%m-%dT%H:%M:%S.%e%z] [%n] [%l] %v"); - spdlog::register_logger(log); - return log; - }; - - _log[log_v2::log_functions] = create_logger("functions", level::err); - _log[log_v2::log_config] = create_logger("configuration", level::info); - _log[log_v2::log_events] = create_logger("events", level::info); - _log[log_v2::log_checks] = create_logger("checks", level::info); - _log[log_v2::log_notifications] = create_logger("notifications", level::err); - _log[log_v2::log_eventbroker] = create_logger("eventbroker", level::err); - _log[log_v2::log_external_command] = - create_logger("external_command", level::err); - _log[log_v2::log_commands] = create_logger("commands", level::err); - _log[log_v2::log_downtimes] = create_logger("downtimes", level::err); - _log[log_v2::log_comments] = create_logger("comments", level::err); - _log[log_v2::log_macros] = create_logger("macros", level::err); - _log[log_v2::log_process] = create_logger("process", level::info); - _log[log_v2::log_runtime] = create_logger("runtime", level::err); - - _log[log_v2::log_process]->info("{} : log started", _log_name); - - _running = true; -} - -log_v2::~log_v2() noexcept { - _log[log_v2::log_runtime]->info("log finished"); - _running = false; - for (auto& l : _log) - l.reset(); -} - -void log_v2::apply(const configuration::state& config) { - if (verify_config || test_scheduling) - return; - - _running = false; - std::vector sinks; - spdlog::sink_ptr sink_to_flush; - if (config.log_v2_enabled()) { - if (config.log_v2_logger() == "file") { - if (config.log_file() != "") { - _file_path = config.log_file(); - sink_to_flush = std::make_shared(_file_path); - } else { - log_v2::config()->error("log_file name is empty"); - sink_to_flush = std::make_shared(); - } - } else if (config.log_v2_logger() == "syslog") - sink_to_flush = std::make_shared("centreon-engine", - 0, 0, true); - if (sink_to_flush) { - sinks.push_back(sink_to_flush); - } - auto broker_sink = std::make_shared(); - broker_sink->set_level(spdlog::level::info); - sinks.push_back(broker_sink); - } else - sinks.push_back(std::make_shared()); - - auto create_logger = [&](const std::string& name, level::level_enum lvl) { - spdlog::drop(name); - auto log = - std::make_shared(name, this, begin(sinks), end(sinks)); - log->set_level(lvl); - if (config.log_flush_period()) - log->flush_on(level::warn); - else - log->flush_on(level::trace); - - if (config.log_pid()) { - if (config.log_file_line()) { - log->set_pattern("[%Y-%m-%dT%H:%M:%S.%e%z] [%s:%#] [%n] [%l] [%P] %v"); - } else { - log->set_pattern("[%Y-%m-%dT%H:%M:%S.%e%z] [%n] [%l] [%P] %v"); - } - } else { - if (config.log_file_line()) { - log->set_pattern("[%Y-%m-%dT%H:%M:%S.%e%z] [%s:%#] [%n] [%l] %v"); - } else { - log->set_pattern("[%Y-%m-%dT%H:%M:%S.%e%z] [%n] [%l] %v"); - } - } - spdlog::register_logger(log); - return log; - }; - - _log[log_functions] = - create_logger("functions", level::from_str(config.log_level_functions())); - _log[log_config] = create_logger("configuration", - level::from_str(config.log_level_config())); - _log[log_events] = - create_logger("events", level::from_str(config.log_level_events())); - _log[log_checks] = - create_logger("checks", level::from_str(config.log_level_checks())); - _log[log_notifications] = create_logger( - "notifications", level::from_str(config.log_level_notifications())); - _log[log_eventbroker] = create_logger( - "eventbroker", level::from_str(config.log_level_eventbroker())); - _log[log_external_command] = create_logger( - "external_command", level::from_str(config.log_level_external_command())); - _log[log_commands] = - create_logger("commands", level::from_str(config.log_level_commands())); - _log[log_downtimes] = - create_logger("downtimes", level::from_str(config.log_level_downtimes())); - _log[log_comments] = - create_logger("comments", level::from_str(config.log_level_comments())); - _log[log_macros] = - create_logger("macros", level::from_str(config.log_level_macros())); - _log[log_process] = - create_logger("process", level::from_str(config.log_level_process())); - _log[log_runtime] = - create_logger("runtime", level::from_str(config.log_level_runtime())); - - _flush_interval = std::chrono::seconds( - config.log_flush_period() > 0 ? config.log_flush_period() : 2); - - if (sink_to_flush) { - start_flush_timer(sink_to_flush); - } else { - std::lock_guard l(_flush_timer_m); - _flush_timer.cancel(); - } - _running = true; -} - -void log_v2::set_flush_interval(unsigned second_flush_interval) { - log_v2_base::set_flush_interval(second_flush_interval); - if (second_flush_interval) { - for (auto logger : _log) { - logger->flush_on(level::warn); - } - } else { - for (auto logger : _log) { - logger->flush_on(level::trace); - } - } -} - -/** - * @brief logs are written periodicaly to disk - * - * @param sink - */ -void log_v2::start_flush_timer(spdlog::sink_ptr sink) { - std::lock_guard l(_flush_timer_m); - _flush_timer.expires_after(_flush_interval); - _flush_timer.async_wait( - [me = _instance, sink](const boost::system::error_code& err) { - if (err || !me->_flush_timer_active) { - return; - } - if (me->get_flush_interval().count() > 0) { - sink->flush(); - } - me->start_flush_timer(sink); - }); -} - -/** - * @brief stop flush timer - * - */ -void log_v2::stop_flush_timer() { - std::lock_guard l(_flush_timer_m); - _flush_timer_active = false; - _flush_timer.cancel(); -} - -/** - * @brief this private static method is used to access a specific logger - * - * @param log_type - * @param log_str - * @return std::shared_ptr - */ -std::shared_ptr log_v2::get_logger(logger log_type, - const char* log_str) { - if (_running) - return _log[log_type]; - else { - auto null_sink = std::make_shared(); - return std::make_shared(log_str, null_sink); - } -} - -/** - * @brief Check if the given level makes part of the available levels. - * - * @param level A level as a string - * - * @return A boolean. - */ - -bool log_v2::contains_level(const std::string& level_name) { - auto level = level::from_str(level_name); - // ignore unrecognized level names - return !(level == level::off && level_name != "off"); -} diff --git a/engine/src/macros.cc b/engine/src/macros.cc index eab699b58d9..451c3756464 100644 --- a/engine/src/macros.cc +++ b/engine/src/macros.cc @@ -1,27 +1,26 @@ /** -* Copyright 1999-2010 Ethan Galstad -* Copyright 2011-201016 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 1999-2010 Ethan Galstad + * Copyright 2011-2024 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/macros.hh" #include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/shared.hh" #include "com/centreon/engine/string.hh" @@ -390,8 +389,8 @@ int grab_standard_hostgroup_macro_r(nagios_macros* mac, default: engine_logger(dbg_macros, basic) << "UNHANDLED HOSTGROUP MACRO #" << macro_type << "! THIS IS A BUG!"; - log_v2::macros()->trace("UNHANDLED HOSTGROUP MACRO #{}! THIS IS A BUG!", - macro_type); + macros_logger->trace("UNHANDLED HOSTGROUP MACRO #{}! THIS IS A BUG!", + macro_type); return ERROR; } @@ -471,8 +470,8 @@ int grab_standard_servicegroup_macro_r(nagios_macros* mac, default: engine_logger(dbg_macros, basic) << "UNHANDLED SERVICEGROUP MACRO #" << macro_type << "! THIS IS A BUG!"; - log_v2::macros()->trace( - "UNHANDLED SERVICEGROUP MACRO #{}! THIS IS A BUG!", macro_type); + macros_logger->trace("UNHANDLED SERVICEGROUP MACRO #{}! THIS IS A BUG!", + macro_type); return ERROR; } @@ -561,8 +560,8 @@ int grab_standard_contact_macro_r(nagios_macros* mac, default: engine_logger(dbg_macros, basic) << "UNHANDLED CONTACT MACRO #" << macro_type << "! THIS IS A BUG!"; - log_v2::macros()->trace("UNHANDLED CONTACT MACRO #{}! THIS IS A BUG!", - macro_type); + macros_logger->trace("UNHANDLED CONTACT MACRO #{}! THIS IS A BUG!", + macro_type); return ERROR; } return OK; @@ -623,8 +622,8 @@ int grab_standard_contactgroup_macro( default: engine_logger(dbg_macros, basic) << "UNHANDLED CONTACTGROUP MACRO #" << macro_type << "! THIS IS A BUG!"; - log_v2::macros()->trace( - "UNHANDLED CONTACTGROUP MACRO #{}! THIS IS A BUG!", macro_type); + macros_logger->trace("UNHANDLED CONTACTGROUP MACRO #{}! THIS IS A BUG!", + macro_type); return ERROR; } return OK; diff --git a/engine/src/macros/grab_host.cc b/engine/src/macros/grab_host.cc index dfcbe71301f..c611278d665 100644 --- a/engine/src/macros/grab_host.cc +++ b/engine/src/macros/grab_host.cc @@ -1,26 +1,26 @@ /** -* Copyright 1999-2010 Ethan Galstad -* Copyright 2011-2013,2016 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 1999-2010 Ethan Galstad + * Copyright 2011-2013,2016 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/macros/grab_host.hh" -#include "com/centreon/engine/log_v2.hh" +#include "com/centreon/engine/globals.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/macros/clear_host.hh" #include "com/centreon/engine/macros/clear_hostgroup.hh" @@ -458,8 +458,8 @@ int grab_standard_host_macro_r(nagios_macros* mac, else { engine_logger(dbg_macros, basic) << "UNHANDLED HOST MACRO #" << macro_type << "! THIS IS A BUG!"; - log_v2::macros()->trace("UNHANDLED HOST MACRO #{}! THIS IS A BUG!", - macro_type); + macros_logger->trace("UNHANDLED HOST MACRO #{}! THIS IS A BUG!", + macro_type); retval = ERROR; } } else diff --git a/engine/src/macros/grab_service.cc b/engine/src/macros/grab_service.cc index f5e4bf2e831..e5fa0c775b0 100644 --- a/engine/src/macros/grab_service.cc +++ b/engine/src/macros/grab_service.cc @@ -1,26 +1,26 @@ /** -* Copyright 1999-2010 Ethan Galstad -* Copyright 2011-2013,2016 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 1999-2010 Ethan Galstad + * Copyright 2011-2013,2016 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/macros/grab_service.hh" -#include "com/centreon/engine/log_v2.hh" +#include "com/centreon/engine/globals.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/macros/clear_service.hh" #include "com/centreon/engine/macros/clear_servicegroup.hh" @@ -418,8 +418,8 @@ int grab_standard_service_macro_r(nagios_macros* mac, else { engine_logger(dbg_macros, basic) << "UNHANDLED SERVICE MACRO #" << macro_type << "! THIS IS A BUG!"; - log_v2::macros()->trace("UNHANDLED SERVICE MACRO #{}! THIS IS A BUG!", - macro_type); + macros_logger->trace("UNHANDLED SERVICE MACRO #{}! THIS IS A BUG!", + macro_type); retval = ERROR; } } else diff --git a/engine/src/macros/grab_value.cc b/engine/src/macros/grab_value.cc index 2b5a84a451a..4db663943a7 100644 --- a/engine/src/macros/grab_value.cc +++ b/engine/src/macros/grab_value.cc @@ -1,28 +1,27 @@ /** -* Copyright 1999-2010 Ethan Galstad -* Copyright 2011-2020 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 1999-2010 Ethan Galstad + * Copyright 2011-2020 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/macros/grab_value.hh" #include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/macros.hh" #include "com/centreon/engine/string.hh" @@ -953,7 +952,7 @@ int grab_macro_value_r(nagios_macros* mac, if (strcmp(macro_x_names[x].c_str(), buf) == 0) { engine_logger(dbg_macros, most) << " macros[" << x << "] (" << macro_x_names[x] << ") match."; - log_v2::macros()->trace(" macros[{}] ({}) match.", x, macro_x_names[x]); + macros_logger->trace(" macros[{}] ({}) match.", x, macro_x_names[x]); /* get the macro value */ result = grab_macrox_value_r(mac, x, arg[0] ? arg[0] : "", @@ -967,7 +966,7 @@ int grab_macro_value_r(nagios_macros* mac, *clean_options |= (STRIP_ILLEGAL_MACRO_CHARS | ESCAPE_MACRO_CHARS); engine_logger(dbg_macros, most) << " New clean options: " << *clean_options; - log_v2::macros()->trace(" New clean options: {}", *clean_options); + macros_logger->trace(" New clean options: {}", *clean_options); } break; } @@ -981,7 +980,7 @@ int grab_macro_value_r(nagios_macros* mac, strncmp(macro_name.c_str(), "ARG", 3) == 0) { /* which arg do we want? */ if (!absl::SimpleAtoi(macro_name.c_str() + 3, &x)) { - log_v2::macros()->error( + macros_logger->error( "Error: could not grab macro value : '{}' must be a positive integer", macro_name.c_str() + 3); return ERROR; @@ -1001,7 +1000,7 @@ int grab_macro_value_r(nagios_macros* mac, strncmp(macro_name.c_str(), "USER", 4) == 0) { /* which macro do we want? */ if (!absl::SimpleAtoi(macro_name.c_str() + 4, &x)) { - log_v2::macros()->error( + macros_logger->error( "Error: could not grab macro value : '{}' must be a positive integer", macro_name.c_str() + 4); return ERROR; @@ -1023,7 +1022,7 @@ int grab_macro_value_r(nagios_macros* mac, strncmp(macro_name.c_str(), "CONTACTADDRESS", 14) == 0) { /* which address do we want? */ if (!absl::SimpleAtoi(macro_name.c_str() + 14, &x)) { - log_v2::macros()->error( + macros_logger->error( "Error: could not grab macro value : '{}' must be a positive integer", macro_name.c_str() + 14); return ERROR; @@ -1107,8 +1106,8 @@ int grab_macro_value_r(nagios_macros* mac, else { engine_logger(dbg_macros, basic) << " WARNING: Could not find a macro matching '" << macro_name << "'!"; - log_v2::macros()->trace(" WARNING: Could not find a macro matching '{}'!", - macro_name); + macros_logger->trace(" WARNING: Could not find a macro matching '{}'!", + macro_name); result = ERROR; } @@ -1146,8 +1145,7 @@ int grab_macrox_value_r(nagios_macros* mac, retval = ERROR; engine_logger(dbg_macros, basic) << "UNHANDLED MACRO #" << macro_type << "! THIS IS A BUG!"; - log_v2::macros()->trace("UNHANDLED MACRO #{}! THIS IS A BUG!", - macro_type); + macros_logger->trace("UNHANDLED MACRO #{}! THIS IS A BUG!", macro_type); } else { retval = (*it->second)(mac, macro_type, arg1, arg2, output, free_macro); } diff --git a/engine/src/macros/process.cc b/engine/src/macros/process.cc index a575d06605d..93177d5bfff 100644 --- a/engine/src/macros/process.cc +++ b/engine/src/macros/process.cc @@ -1,25 +1,25 @@ /** -* Copyright 1999-2010 Ethan Galstad -* Copyright 2011-2013 Merethis -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 1999-2010 Ethan Galstad + * Copyright 2011-2013 Merethis + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/macros/process.hh" -#include "com/centreon/engine/log_v2.hh" +#include "com/centreon/engine/globals.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/macros.hh" #include "com/centreon/engine/string.hh" @@ -44,7 +44,7 @@ int process_macros_r(nagios_macros* mac, int macro_options = 0; engine_logger(dbg_functions, basic) << "process_macros_r()"; - log_v2::functions()->trace("process_macros_r()"); + functions_logger->trace("process_macros_r()"); output_buffer = ""; @@ -54,8 +54,8 @@ int process_macros_r(nagios_macros* mac, engine_logger(dbg_macros, more) << "**** BEGIN MACRO PROCESSING ***********\n" "Processing: '" << input_buffer << "'"; - log_v2::macros()->trace("**** BEGIN MACRO PROCESSING **** Processing: '{}'", - input_buffer); + macros_logger->trace("**** BEGIN MACRO PROCESSING **** Processing: '{}'", + input_buffer); for (std::string::const_iterator it{input_buffer.begin()}, end{input_buffer.end()}; @@ -85,7 +85,7 @@ int process_macros_r(nagios_macros* mac, << " Processed '" << token.c_str() << "', To '" << token_resolved << "', Clean Options: " << clean_options << ", Free: " << free_macro; - log_v2::macros()->trace( + macros_logger->trace( " Processed '{}', To '{}', Clean Options: {}, Free: {}", token, token_resolved, clean_options, free_macro); @@ -94,7 +94,7 @@ int process_macros_r(nagios_macros* mac, engine_logger(dbg_macros, basic) << " WARNING: An error occurred processing macro '" << token << "'!"; - log_v2::macros()->trace( + macros_logger->trace( " WARNING: An error occurred processing macro '{}'!", token); } @@ -104,7 +104,7 @@ int process_macros_r(nagios_macros* mac, << " Processed '" << token << "', Clean Options: " << clean_options << ", Free: " << free_macro; - log_v2::macros()->trace( + macros_logger->trace( " Processed '{}', Clean Options: {}, Free: {}", token, clean_options, free_macro); @@ -115,7 +115,7 @@ int process_macros_r(nagios_macros* mac, << " Cleaning options: global=" << options << ", local=" << clean_options << ", effective=" << macro_options; - log_v2::macros()->trace( + macros_logger->trace( " Cleaning options: global={}, local={}, effective={}", options, clean_options, macro_options); @@ -134,7 +134,7 @@ int process_macros_r(nagios_macros* mac, << " Cleaned macro. Running output (" << output_buffer.length() << "): '" << output_buffer << "'"; - log_v2::macros()->trace( + macros_logger->trace( " Cleaned macro. Running output ({}): '{}'", output_buffer.length(), output_buffer); } @@ -147,7 +147,7 @@ int process_macros_r(nagios_macros* mac, engine_logger(dbg_macros, basic) << " Uncleaned macro. Running output (" << output_buffer.length() << "): '" << output_buffer << "'"; - log_v2::macros()->trace( + macros_logger->trace( " Uncleaned macro. Running output ({}): '{}'", output_buffer.length(), output_buffer); } @@ -157,7 +157,7 @@ int process_macros_r(nagios_macros* mac, engine_logger(dbg_macros, basic) << " Just finished macro. Running output (" << output_buffer.length() << "): '" << output_buffer << "'"; - log_v2::macros()->trace( + macros_logger->trace( " Just finished macro. Running output ({}): '{}'", output_buffer.length(), output_buffer); } @@ -173,7 +173,7 @@ int process_macros_r(nagios_macros* mac, engine_logger(dbg_macros, more) << " Done. Final output: '" << output_buffer << "'\n" "**** END MACRO PROCESSING *************"; - log_v2::macros()->trace( + macros_logger->trace( " Done. Final output: '{}' **** END MACRO PROCESSING ****", output_buffer); return OK; diff --git a/engine/src/main.cc b/engine/src/main.cc index b0171ca7648..3f86a4cecc7 100644 --- a/engine/src/main.cc +++ b/engine/src/main.cc @@ -1,7 +1,7 @@ /** * Copyright 1999-2009 Ethan Galstad * Copyright 2009-2010 Nagios Core Development Team and Community Contributors - * Copyright 2011-2021 Centreon + * Copyright 2011-2024 Centreon * * This file is part of Centreon Engine. * @@ -55,7 +55,6 @@ namespace asio = boost::asio; #include "com/centreon/engine/enginerpc.hh" #include "com/centreon/engine/events/loop.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging.hh" #include "com/centreon/engine/logging/broker.hh" #include "com/centreon/engine/logging/logger.hh" @@ -70,8 +69,10 @@ namespace asio = boost::asio; #include "com/centreon/engine/version.hh" #include "com/centreon/io/directory_entry.hh" #include "com/centreon/logging/engine.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::engine; +using com::centreon::common::log_v2::log_v2; std::shared_ptr g_io_context( std::make_shared()); @@ -116,9 +117,15 @@ int main(int argc, char* argv[]) { config = new configuration::state; // Hack to instanciate the logger. - log_v2::load(g_io_context); + log_v2::load("centengine"); + auto config_logger = log_v2::instance().get(log_v2::CONFIG); + auto process_logger = log_v2::instance().get(log_v2::PROCESS); + init_loggers(); configuration::applier::logging::instance(); - com::centreon::common::pool::load(g_io_context, log_v2::runtime()); + com::centreon::common::pool::load(g_io_context, runtime_logger); + + config_logger->info("Configuration mechanism used: legacy"); + config = new configuration::state; logging::broker backend_broker_log; @@ -171,9 +178,9 @@ int main(int argc, char* argv[]) { } // Invalid argument count. - if ((argc < 2) + if (argc < 2 // Main configuration file not on command line. - || (optind >= argc)) + || optind >= argc) error = true; else { // Config file is last argument specified. @@ -294,8 +301,8 @@ int main(int argc, char* argv[]) { << " services.\n Checked " << timeperiod::timeperiods.size() << " time periods.\n\n Total Warnings: " << config_warnings << "\n Total Errors: " << config_errors << std::endl; - retval = (config_errors ? EXIT_FAILURE : EXIT_SUCCESS); - } catch (std::exception const& e) { + retval = config_errors ? EXIT_FAILURE : EXIT_SUCCESS; + } catch (const std::exception& e) { std::cout << "Error while processing a config file: " << e.what() << std::endl; @@ -392,8 +399,8 @@ int main(int argc, char* argv[]) { retention::parser p; try { p.parse(config.state_retention_file(), state); - } catch (std::exception const& e) { - log_v2::config()->error("{}", e.what()); + } catch (const std::exception& e) { + config_logger->error("{}", e.what()); engine_logger(logging::log_config_error, logging::basic) << e.what(); } @@ -452,18 +459,17 @@ int main(int argc, char* argv[]) { engine_logger(logging::log_info_message, logging::basic) << "Event loop start at " << string::ctime(event_start); - log_v2::config()->info("Event loop start at {}", - string::ctime(event_start)); + config_logger->info("Event loop start at {}", + string::ctime(event_start)); // Start monitoring all services (doesn't return until a // restart or shutdown signal is encountered). com::centreon::engine::events::loop::instance().run(); if (sigshutdown) { - log_v2::instance()->stop_flush_timer(); engine_logger(logging::log_process_info, logging::basic) << "Caught SIG" << sigs[sig_id] << ", shutting down ..."; - SPDLOG_LOGGER_INFO(log_v2::process(), - "Caught SIG {}, shutting down ...", sigs[sig_id]); + SPDLOG_LOGGER_INFO(process_logger, "Caught SIG {}, shutting down ...", + sigs[sig_id]); } // Send program data to broker. broker_program_state(NEBTYPE_PROCESS_EVENTLOOPEND, NEBFLAG_NONE); @@ -481,7 +487,7 @@ int main(int argc, char* argv[]) { if (sigshutdown) { engine_logger(logging::log_process_info, logging::basic) << "Successfully shutdown ... (PID=" << getpid() << ")"; - SPDLOG_LOGGER_INFO(log_v2::process(), + SPDLOG_LOGGER_INFO(process_logger, "Successfully shutdown ... (PID={})", getpid()); } @@ -490,7 +496,7 @@ int main(int argc, char* argv[]) { // Log. engine_logger(logging::log_runtime_error, logging::basic) << "Error: " << e.what(); - SPDLOG_LOGGER_ERROR(log_v2::process(), "Error: {}", e.what()); + SPDLOG_LOGGER_ERROR(process_logger, "Error: {}", e.what()); // Send program data to broker. broker_program_state(NEBTYPE_PROCESS_SHUTDOWN, NEBFLAG_PROCESS_INITIATED); @@ -505,7 +511,7 @@ int main(int argc, char* argv[]) { } catch (std::exception const& e) { engine_logger(logging::log_runtime_error, logging::basic) << "Error: " << e.what(); - SPDLOG_LOGGER_ERROR(log_v2::process(), "Error: {}", e.what()); + SPDLOG_LOGGER_ERROR(process_logger, "Error: {}", e.what()); } // Unload singletons and global objects. diff --git a/engine/src/nebmods.cc b/engine/src/nebmods.cc index 6b5f7fbeb8a..528dbc0097b 100644 --- a/engine/src/nebmods.cc +++ b/engine/src/nebmods.cc @@ -1,27 +1,26 @@ /** -* Copyright 2002-2008 Ethan Galstad -* Copyright 2011-2013,2016-2017 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2002-2008 Ethan Galstad + * Copyright 2011-2013,2016-2024 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/nebmods.hh" #include "com/centreon/engine/broker/loader.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/neberrors.hh" #include "com/centreon/engine/utils.hh" @@ -62,14 +61,14 @@ int neb_add_module(char const* filename, loader::instance().add_module(filename, args); engine_logger(dbg_eventbroker, basic) << "Added module: name='" << filename << "', args='" << args << "'"; - log_v2::eventbroker()->trace("Added module: name='{}', args='{}'", filename, - args); + eventbroker_logger->trace("Added module: name='{}', args='{}'", filename, + args); } catch (...) { engine_logger(dbg_eventbroker, basic) << "Counld not add module: name='" << filename << "', args='" << args << "'"; - log_v2::eventbroker()->trace("Counld not add module: name='{}', args='{}'", - filename, args); + eventbroker_logger->trace("Counld not add module: name='{}', args='{}'", + filename, args); return ERROR; } return OK; @@ -79,10 +78,10 @@ int neb_add_module(char const* filename, int neb_free_module_list() { try { engine_logger(dbg_eventbroker, basic) << "unload all modules success."; - log_v2::eventbroker()->trace("unload all modules success."); + eventbroker_logger->trace("unload all modules success."); } catch (...) { engine_logger(dbg_eventbroker, basic) << "unload all modules failed."; - log_v2::eventbroker()->trace("unload all modules failed."); + eventbroker_logger->trace("unload all modules failed."); return ERROR; } return OK; @@ -113,7 +112,7 @@ int neb_load_all_modules() { ++unloaded; } catch (...) { engine_logger(dbg_eventbroker, basic) << "Could not load all modules"; - log_v2::eventbroker()->trace("Could not load all modules"); + eventbroker_logger->trace("Could not load all modules"); return -1; } return unloaded; @@ -135,20 +134,20 @@ int neb_load_module(void* mod) { engine_logger(log_info_message, basic) << "Event broker module '" << module->get_filename() << "' initialized successfully"; - log_v2::events()->info("Event broker module '{}' initialized successfully", - module->get_filename()); + events_logger->info("Event broker module '{}' initialized successfully", + module->get_filename()); } catch (std::exception const& e) { engine_logger(log_runtime_error, basic) << "Error: Could not load module '" << module->get_filename() << "': " << e.what(); - log_v2::runtime()->error("Error: Could not load module '{}': {}", - module->get_filename(), e.what()); + runtime_logger->error("Error: Could not load module '{}': {}", + module->get_filename(), e.what()); return ERROR; } catch (...) { engine_logger(log_runtime_error, basic) << "Error: Could not load module '" << module->get_filename() << "'"; - log_v2::runtime()->error("Error: Could not load module '{}'", - module->get_filename()); + runtime_logger->error("Error: Could not load module '{}'", + module->get_filename()); return ERROR; } return OK; @@ -171,18 +170,18 @@ int neb_reload_all_modules() { } engine_logger(dbg_eventbroker, basic) << "All modules got successfully reloaded"; - log_v2::eventbroker()->trace("All modules got successfully reloaded"); + eventbroker_logger->trace("All modules got successfully reloaded"); } retval = OK; } catch (std::exception const& e) { engine_logger(log_runtime_error, basic) << "Warning: Module reloading failed: " << e.what(); - log_v2::runtime()->error("Warning: Module reloading failed: {}", e.what()); + runtime_logger->error("Warning: Module reloading failed: {}", e.what()); retval = ERROR; } catch (...) { engine_logger(log_runtime_error, basic) << "Warning: Module reloading failed: unknown error"; - log_v2::runtime()->error("Warning: Module reloading failed: unknown error"); + runtime_logger->error("Warning: Module reloading failed: unknown error"); retval = ERROR; } return retval; @@ -199,13 +198,13 @@ int neb_reload_module(void* mod) { engine_logger(dbg_eventbroker, basic) << "Attempting to reload module '" << module->get_filename() << "'"; - log_v2::eventbroker()->trace("Attempting to reload module '{}'", - module->get_filename()); + eventbroker_logger->trace("Attempting to reload module '{}'", + module->get_filename()); module->reload(); engine_logger(dbg_eventbroker, basic) << "Module '" << module->get_filename() << "' reloaded successfully"; - log_v2::eventbroker()->trace("Module '{}' reloaded successfully", - module->get_filename()); + eventbroker_logger->trace("Module '{}' reloaded successfully", + module->get_filename()); return OK; } @@ -231,17 +230,17 @@ int neb_unload_all_modules(int flags, int reason) { ldr.unload_modules(); engine_logger(dbg_eventbroker, basic) << "All modules got successfully unloaded"; - log_v2::eventbroker()->trace("All modules got successfully unloaded"); + eventbroker_logger->trace("All modules got successfully unloaded"); retval = OK; } catch (std::exception const& e) { engine_logger(log_runtime_error, basic) << "Error: Module unloading failed: " << e.what(); - log_v2::runtime()->error("Error: Module unloading failed: {}", e.what()); + runtime_logger->error("Error: Module unloading failed: {}", e.what()); retval = ERROR; } catch (...) { engine_logger(log_runtime_error, basic) << "Error: unloading of all modules failed"; - log_v2::runtime()->error("Error: unloading of all modules failed"); + runtime_logger->error("Error: unloading of all modules failed"); retval = ERROR; } return retval; @@ -260,8 +259,8 @@ int neb_unload_module(handle* module, int flags, int reason) { engine_logger(dbg_eventbroker, basic) << "Attempting to unload module '" << module->get_filename() << "'"; - log_v2::eventbroker()->trace("Attempting to unload module '{}'", - module->get_filename()); + eventbroker_logger->trace("Attempting to unload module '{}'", + module->get_filename()); module->close(); @@ -270,14 +269,14 @@ int neb_unload_module(handle* module, int flags, int reason) { engine_logger(dbg_eventbroker, basic) << "Module '" << module->get_filename() << "' unloaded successfully"; - log_v2::eventbroker()->trace("Module '{}' unloaded successfully", - module->get_filename()); + eventbroker_logger->trace("Module '{}' unloaded successfully", + module->get_filename()); engine_logger(log_info_message, basic) << "Event broker module '" << module->get_filename() << "' deinitialized successfully"; - log_v2::events()->info("Event broker module '{}' deinitialized successfully", - module->get_filename()); + events_logger->info("Event broker module '{}' deinitialized successfully", + module->get_filename()); return OK; } @@ -329,12 +328,12 @@ int neb_set_module_info(void* hnd, int type, const char* data) { engine_logger(dbg_eventbroker, basic) << "set module info success: filename='" << module->get_filename() << "', type='" << type << "'"; - log_v2::eventbroker()->trace( + eventbroker_logger->trace( "set module info success: filename='{}', type='{}'", module->get_filename(), type); } catch (...) { engine_logger(dbg_eventbroker, basic) << "Counld not set module info."; - log_v2::eventbroker()->trace("Counld not set module info."); + eventbroker_logger->trace("Counld not set module info."); return ERROR; } diff --git a/engine/src/notification.cc b/engine/src/notification.cc index 3da262525db..2e32df5fe25 100644 --- a/engine/src/notification.cc +++ b/engine/src/notification.cc @@ -1,5 +1,5 @@ /** - * Copyright 2019 Centreon (https://www.centreon.com/) + * Copyright 2019-2024 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,7 @@ #include "com/centreon/engine/notification.hh" #include "com/centreon/engine/broker.hh" -#include "com/centreon/engine/log_v2.hh" +#include "com/centreon/engine/globals.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/macros.hh" #include "com/centreon/engine/macros/defines.hh" @@ -206,7 +206,7 @@ int notification::execute(std::unordered_set const& to_notify) { engine_logger(dbg_notifications, basic) << contacts_notified << " contacts were notified."; - log_v2::notifications()->trace(" contacts were notified."); + notifications_logger->trace(" contacts were notified."); return OK; } diff --git a/engine/src/notifier.cc b/engine/src/notifier.cc index cc854ce3aec..9f99a71a7fa 100644 --- a/engine/src/notifier.cc +++ b/engine/src/notifier.cc @@ -26,7 +26,6 @@ #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" #include "com/centreon/engine/hostescalation.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/macros.hh" #include "com/centreon/engine/neberrors.hh" @@ -162,7 +161,7 @@ notifier::notifier(notifier::notifier_type notifier_type, << "Error: Invalid notification_interval value for notifier '" << display_name << "'"; SPDLOG_LOGGER_ERROR( - log_v2::config(), + config_logger, "Error: Invalid notification_interval value for notifier '{}'", display_name); throw engine_error() << "Could not register notifier '" << display_name @@ -213,7 +212,7 @@ void notifier::set_last_problem_id(unsigned long last_problem_id) noexcept { * @param num The notification number. */ void notifier::set_notification_number(int num) { - SPDLOG_LOGGER_TRACE(log_v2::notifications(), + SPDLOG_LOGGER_TRACE(notifications_logger, "_notification_number set_notification_number: {} => {}", _notification_number, num); /* set the notification number */ @@ -228,7 +227,7 @@ bool notifier::_is_notification_viable_normal(reason_type type notification_option options) { engine_logger(dbg_functions, basic) << "notifier::is_notification_viable_normal()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), + SPDLOG_LOGGER_TRACE(functions_logger, "notifier::is_notification_viable_normal()"); /* forced notifications bust through everything */ @@ -240,7 +239,7 @@ bool notifier::_is_notification_viable_normal(reason_type type if (options & notification_option_forced) { engine_logger(dbg_notifications, more) << "This is a forced notification, so we'll send it out."; - SPDLOG_LOGGER_DEBUG(log_v2::notifications(), + SPDLOG_LOGGER_DEBUG(notifications_logger, "This is a forced notification, so we'll send it out."); return true; } @@ -250,7 +249,7 @@ bool notifier::_is_notification_viable_normal(reason_type type engine_logger(dbg_notifications, more) << "Notifications are disabled, so notifications will " "not be sent out."; - SPDLOG_LOGGER_DEBUG(log_v2::notifications(), + SPDLOG_LOGGER_DEBUG(notifications_logger, "Notifications are disabled, so notifications will " "not be sent out."); return false; @@ -261,7 +260,7 @@ bool notifier::_is_notification_viable_normal(reason_type type engine_logger(dbg_notifications, more) << "Notifications are temporarily disabled for " "this notifier, so we won't send one out."; - SPDLOG_LOGGER_DEBUG(log_v2::notifications(), + SPDLOG_LOGGER_DEBUG(notifications_logger, "Notifications are temporarily disabled for " "this notifier, so we won't send one out."); return false; @@ -274,7 +273,7 @@ bool notifier::_is_notification_viable_normal(reason_type type << "This notifier is currently in a scheduled downtime, so " "we won't send notifications."; SPDLOG_LOGGER_DEBUG( - log_v2::notifications(), + notifications_logger, "This notifier is currently in a scheduled downtime, so " "we won't send notifications."); return false; @@ -289,7 +288,7 @@ bool notifier::_is_notification_viable_normal(reason_type type engine_logger(dbg_notifications, more) << "This notifier shouldn't have notifications sent out " "at this time."; - SPDLOG_LOGGER_DEBUG(log_v2::notifications(), + SPDLOG_LOGGER_DEBUG(notifications_logger, "This notifier shouldn't have notifications sent out " "at this time."); return false; @@ -300,7 +299,7 @@ bool notifier::_is_notification_viable_normal(reason_type type engine_logger(dbg_notifications, more) << "This notifier is flapping, so we won't send notifications."; SPDLOG_LOGGER_DEBUG( - log_v2::notifications(), + notifications_logger, "This notifier is flapping, so we won't send notifications."); return false; } @@ -310,7 +309,7 @@ bool notifier::_is_notification_viable_normal(reason_type type engine_logger(dbg_notifications, more) << "This is a volatile service notification, so it is sent."; SPDLOG_LOGGER_DEBUG( - log_v2::notifications(), + notifications_logger, "This is a volatile service notification, so it is sent."); return true; } @@ -319,7 +318,7 @@ bool notifier::_is_notification_viable_normal(reason_type type engine_logger(dbg_notifications, more) << "This notifier is in soft state, so we won't send notifications."; SPDLOG_LOGGER_DEBUG( - log_v2::notifications(), + notifications_logger, "This notifier is in soft state, so we won't send notifications."); return false; } @@ -329,7 +328,7 @@ bool notifier::_is_notification_viable_normal(reason_type type << "This notifier problem has been acknowledged, so we won't send " "notifications."; SPDLOG_LOGGER_DEBUG( - log_v2::notifications(), + notifications_logger, "This notifier problem has been acknowledged, so we won't send " "notifications."); return false; @@ -339,7 +338,7 @@ bool notifier::_is_notification_viable_normal(reason_type type engine_logger(dbg_notifications, more) << "We don't send a normal notification when the state is ok/up"; SPDLOG_LOGGER_DEBUG( - log_v2::notifications(), + notifications_logger, "We don't send a normal notification when the state is ok/up"); return false; } @@ -350,7 +349,7 @@ bool notifier::_is_notification_viable_normal(reason_type type << get_current_state_as_string() << ": not configured for that or, for a service, its host may be down"; SPDLOG_LOGGER_DEBUG( - log_v2::notifications(), + notifications_logger, "This notifier is unable to notify the state {}: not configured for " "that or, for a service, its host may be down", get_current_state_as_string()); @@ -366,7 +365,7 @@ bool notifier::_is_notification_viable_normal(reason_type type "won't send notification until timestamp " << (_first_notification_delay * config->interval_length()); SPDLOG_LOGGER_DEBUG( - log_v2::notifications(), + notifications_logger, "This notifier is configured with a first notification delay, we " "won't send notification until timestamp {}", _first_notification_delay * config->interval_length()); @@ -378,7 +377,7 @@ bool notifier::_is_notification_viable_normal(reason_type type << "This notifier won't send any notification since it depends on" " another notifier that has already sent one"; SPDLOG_LOGGER_DEBUG( - log_v2::notifications(), + notifications_logger, "This notifier won't send any notification since it depends on" " another notifier that has already sent one"); return false; @@ -395,7 +394,7 @@ bool notifier::_is_notification_viable_normal(reason_type type << " so, since the notification interval is 0, it won't be sent" << " anymore"; SPDLOG_LOGGER_DEBUG( - log_v2::notifications(), + notifications_logger, "This notifier problem has already been sent at {} so, since the " "notification interval is 0, it won't be sent anymore", _last_notification); @@ -409,7 +408,7 @@ bool notifier::_is_notification_viable_normal(reason_type type << " so it won't be sent until " << (notification_interval * config->interval_length()); SPDLOG_LOGGER_DEBUG( - log_v2::notifications(), + notifications_logger, "This notifier problem has been sent at {} so it won't be sent " "until {}", _last_notification, @@ -428,7 +427,7 @@ bool notifier::_is_notification_viable_recovery(reason_type type __attribute__((unused))) { engine_logger(dbg_functions, basic) << "notifier::is_notification_viable_recovery()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), + SPDLOG_LOGGER_TRACE(functions_logger, "notifier::is_notification_viable_recovery()"); bool retval{true}; bool send_later{false}; @@ -438,7 +437,7 @@ bool notifier::_is_notification_viable_recovery(reason_type type engine_logger(dbg_notifications, more) << "Notifications are disabled, so notifications will " "not be sent out."; - SPDLOG_LOGGER_DEBUG(log_v2::notifications(), + SPDLOG_LOGGER_DEBUG(notifications_logger, "Notifications are disabled, so notifications will " "not be sent out."); retval = false; @@ -448,7 +447,7 @@ bool notifier::_is_notification_viable_recovery(reason_type type engine_logger(dbg_notifications, more) << "Notifications are temporarily disabled for " "this notifier, so we won't send one out."; - SPDLOG_LOGGER_DEBUG(log_v2::notifications(), + SPDLOG_LOGGER_DEBUG(notifications_logger, "Notifications are temporarily disabled for " "this notifier, so we won't send one out."); retval = false; @@ -462,16 +461,13 @@ bool notifier::_is_notification_viable_recovery(reason_type type // timeperiod into account for recovery if (!check_time_against_period_for_notif(now, tp)) { if (config->use_send_recovery_notifications_anyways()) { - SPDLOG_LOGGER_DEBUG(log_v2::notifications(), + SPDLOG_LOGGER_DEBUG(notifications_logger, "send_recovery_notifications_anyways flag enabled, " "recovery notification is viable even if we are " "out of timeperiod at this time."); } else { - engine_logger(dbg_notifications, more) - << "This notifier shouldn't have notifications sent out " - "at this time."; SPDLOG_LOGGER_DEBUG( - log_v2::notifications(), + notifications_logger, "This notifier shouldn't have notifications sent out " "at this time."); retval = false; @@ -486,7 +482,7 @@ bool notifier::_is_notification_viable_recovery(reason_type type << "This notifier is currently in a scheduled downtime, so " "we won't send notifications."; SPDLOG_LOGGER_DEBUG( - log_v2::notifications(), + notifications_logger, "This notifier is currently in a scheduled downtime, so " "we won't send notifications."); retval = false; @@ -497,7 +493,7 @@ bool notifier::_is_notification_viable_recovery(reason_type type engine_logger(dbg_notifications, more) << "This notifier is flapping, so we won't send notifications."; SPDLOG_LOGGER_DEBUG( - log_v2::notifications(), + notifications_logger, "This notifier is flapping, so we won't send notifications."); retval = false; send_later = true; @@ -505,7 +501,7 @@ bool notifier::_is_notification_viable_recovery(reason_type type engine_logger(dbg_notifications, more) << "This notifier is in soft state, so we won't send notifications."; SPDLOG_LOGGER_DEBUG( - log_v2::notifications(), + notifications_logger, "This notifier is in soft state, so we won't send notifications."); retval = false; send_later = true; @@ -515,7 +511,7 @@ bool notifier::_is_notification_viable_recovery(reason_type type engine_logger(dbg_notifications, more) << "This notifier state is not UP/OK to send a recovery notification"; SPDLOG_LOGGER_DEBUG( - log_v2::notifications(), + notifications_logger, "This notifier state is not UP/OK to send a recovery notification"); retval = false; send_later = true; @@ -523,7 +519,7 @@ bool notifier::_is_notification_viable_recovery(reason_type type engine_logger(dbg_notifications, more) << "This notifier is not configured to send a recovery notification"; SPDLOG_LOGGER_DEBUG( - log_v2::notifications(), + notifications_logger, "This notifier is not configured to send a recovery notification"); retval = false; send_later = false; @@ -536,7 +532,7 @@ bool notifier::_is_notification_viable_recovery(reason_type type << " so it won't be sent until " << (get_last_hard_state_change() + _recovery_notification_delay); SPDLOG_LOGGER_DEBUG( - log_v2::notifications(), + notifications_logger, "This notifier is configured with a recovery notification delay. " "It won't send any recovery notification until timestamp " "so it won't be sent until {}", @@ -549,7 +545,7 @@ bool notifier::_is_notification_viable_recovery(reason_type type "announce a problem. So no recovery" << " notification will be sent"; SPDLOG_LOGGER_DEBUG( - log_v2::notifications(), + notifications_logger, "No notification has been sent to " "announce a problem. So no recovery notification will be sent"); retval = false; @@ -558,7 +554,7 @@ bool notifier::_is_notification_viable_recovery(reason_type type << "We should not send a notification " "since no normal notification has" " been sent before"; - SPDLOG_LOGGER_DEBUG(log_v2::notifications(), + SPDLOG_LOGGER_DEBUG(notifications_logger, "We should not send a notification " "since no normal notification has" " been sent before"); @@ -570,7 +566,7 @@ bool notifier::_is_notification_viable_recovery(reason_type type if (!send_later) { _notification[cat_normal].reset(); SPDLOG_LOGGER_TRACE( - log_v2::notifications(), + notifications_logger, " _notification_number _is_notification_viable_recovery: {} => 0", _notification_number); _notification_number = 0; @@ -585,13 +581,13 @@ bool notifier::_is_notification_viable_acknowledgement( notification_option options) { engine_logger(dbg_functions, basic) << "notifier::is_notification_viable_acknowledgement()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), + SPDLOG_LOGGER_TRACE(functions_logger, "notifier::is_notification_viable_acknowledgement()"); /* forced notifications bust through everything */ if (options & notification_option_forced) { engine_logger(dbg_notifications, more) << "This is a forced notification, so we'll send it out."; - SPDLOG_LOGGER_DEBUG(log_v2::notifications(), + SPDLOG_LOGGER_DEBUG(notifications_logger, "This is a forced notification, so we'll send it out."); return true; } @@ -601,7 +597,7 @@ bool notifier::_is_notification_viable_acknowledgement( engine_logger(dbg_notifications, more) << "Notifications are disabled, so notifications will " "not be sent out."; - SPDLOG_LOGGER_DEBUG(log_v2::notifications(), + SPDLOG_LOGGER_DEBUG(notifications_logger, "Notifications are disabled, so notifications will " "not be sent out."); return false; @@ -612,7 +608,7 @@ bool notifier::_is_notification_viable_acknowledgement( engine_logger(dbg_notifications, more) << "Notifications are temporarily disabled for " "this notifier, so we won't send one out."; - SPDLOG_LOGGER_DEBUG(log_v2::notifications(), + SPDLOG_LOGGER_DEBUG(notifications_logger, "Notifications are temporarily disabled for " "this notifier, so we won't send one out."); return false; @@ -622,7 +618,7 @@ bool notifier::_is_notification_viable_acknowledgement( engine_logger(dbg_notifications, more) << "The notifier is currently OK/UP, so we " "won't send an acknowledgement."; - SPDLOG_LOGGER_DEBUG(log_v2::notifications(), + SPDLOG_LOGGER_DEBUG(notifications_logger, "The notifier is currently OK/UP, so we " "won't send an acknowledgement."); return false; @@ -634,13 +630,13 @@ bool notifier::_is_notification_viable_flapping(reason_type type, notification_option options) { engine_logger(dbg_functions, basic) << "notifier::is_notification_viable_flapping()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), + SPDLOG_LOGGER_TRACE(functions_logger, "notifier::is_notification_viable_flapping()"); /* forced notifications bust through everything */ if (options & notification_option_forced) { engine_logger(dbg_notifications, more) << "This is a forced notification, so we'll send it out."; - SPDLOG_LOGGER_DEBUG(log_v2::notifications(), + SPDLOG_LOGGER_DEBUG(notifications_logger, "This is a forced notification, so we'll send it out."); return true; } @@ -650,7 +646,7 @@ bool notifier::_is_notification_viable_flapping(reason_type type, engine_logger(dbg_notifications, more) << "Notifications are disabled, so notifications will " "not be sent out."; - SPDLOG_LOGGER_DEBUG(log_v2::notifications(), + SPDLOG_LOGGER_DEBUG(notifications_logger, "Notifications are disabled, so notifications will " "not be sent out."); return false; @@ -661,7 +657,7 @@ bool notifier::_is_notification_viable_flapping(reason_type type, engine_logger(dbg_notifications, more) << "Notifications are temporarily disabled for " "this notifier, so we won't send one out."; - SPDLOG_LOGGER_DEBUG(log_v2::notifications(), + SPDLOG_LOGGER_DEBUG(notifications_logger, "Notifications are temporarily disabled for " "this notifier, so we won't send one out."); return false; @@ -681,7 +677,7 @@ bool notifier::_is_notification_viable_flapping(reason_type type, << "We shouldn't notify about " << tab_notification_str[type] << " events for this notifier."; SPDLOG_LOGGER_DEBUG( - log_v2::notifications(), + notifications_logger, "We shouldn't notify about {} events for this notifier.", tab_notification_str[type]); return false; @@ -694,7 +690,7 @@ bool notifier::_is_notification_viable_flapping(reason_type type, << "A flapping notification is already running, we can not send " "a start notification now."; SPDLOG_LOGGER_DEBUG( - log_v2::notifications(), + notifications_logger, "A flapping notification is already running, we can not send " "a start notification now."); return false; @@ -707,7 +703,7 @@ bool notifier::_is_notification_viable_flapping(reason_type type, << "A stop or cancellation flapping notification can only be sent " "after a start flapping notification."; SPDLOG_LOGGER_DEBUG( - log_v2::notifications(), + notifications_logger, "A stop or cancellation flapping notification can only be sent " "after a start flapping notification."); return false; @@ -720,7 +716,7 @@ bool notifier::_is_notification_viable_flapping(reason_type type, engine_logger(dbg_notifications, more) << "We shouldn't notify about a " << tab_notification_str[type] << " event: already sent."; - SPDLOG_LOGGER_DEBUG(log_v2::notifications(), + SPDLOG_LOGGER_DEBUG(notifications_logger, "We shouldn't notify about a {} event: already sent.", tab_notification_str[type]); return false; @@ -731,7 +727,7 @@ bool notifier::_is_notification_viable_flapping(reason_type type, engine_logger(dbg_notifications, more) << "We shouldn't notify about FLAPPING " "events during scheduled downtime."; - SPDLOG_LOGGER_DEBUG(log_v2::notifications(), + SPDLOG_LOGGER_DEBUG(notifications_logger, "We shouldn't notify about FLAPPING " "events during scheduled downtime."); return false; @@ -744,14 +740,14 @@ bool notifier::_is_notification_viable_downtime(reason_type type notification_option options) { engine_logger(dbg_functions, basic) << "notifier::is_notification_viable_downtime()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), + SPDLOG_LOGGER_TRACE(functions_logger, "notifier::is_notification_viable_downtime()"); /* forced notifications bust through everything */ if (options & notification_option_forced) { engine_logger(dbg_notifications, more) << "This is a forced notification, so we'll send it out."; - SPDLOG_LOGGER_DEBUG(log_v2::notifications(), + SPDLOG_LOGGER_DEBUG(notifications_logger, "This is a forced notification, so we'll send it out."); return true; } @@ -761,7 +757,7 @@ bool notifier::_is_notification_viable_downtime(reason_type type engine_logger(dbg_notifications, more) << "Notifications are disabled, so notifications will " "not be sent out."; - SPDLOG_LOGGER_DEBUG(log_v2::notifications(), + SPDLOG_LOGGER_DEBUG(notifications_logger, "Notifications are disabled, so notifications will " "not be sent out."); return false; @@ -772,7 +768,7 @@ bool notifier::_is_notification_viable_downtime(reason_type type engine_logger(dbg_notifications, more) << "Notifications are temporarily disabled for " "this notifier, so we won't send one out."; - SPDLOG_LOGGER_DEBUG(log_v2::notifications(), + SPDLOG_LOGGER_DEBUG(notifications_logger, "Notifications are temporarily disabled for " "this notifier, so we won't send one out."); return false; @@ -782,7 +778,7 @@ bool notifier::_is_notification_viable_downtime(reason_type type engine_logger(dbg_notifications, more) << "Notifications are disabled, so notifications won't be sent out."; SPDLOG_LOGGER_DEBUG( - log_v2::notifications(), + notifications_logger, "Notifications are disabled, so notifications won't be sent out."); return false; } @@ -792,7 +788,7 @@ bool notifier::_is_notification_viable_downtime(reason_type type engine_logger(dbg_notifications, more) << "We shouldn't notify about DOWNTIME events for this notifier."; SPDLOG_LOGGER_DEBUG( - log_v2::notifications(), + notifications_logger, "We shouldn't notify about DOWNTIME events for this notifier."); return false; } @@ -804,7 +800,7 @@ bool notifier::_is_notification_viable_downtime(reason_type type engine_logger(dbg_notifications, more) << "We shouldn't notify about DOWNTIME " "events during scheduled downtime."; - SPDLOG_LOGGER_DEBUG(log_v2::notifications(), + SPDLOG_LOGGER_DEBUG(notifications_logger, "We shouldn't notify about DOWNTIME " "events during scheduled downtime."); return false; @@ -817,13 +813,13 @@ bool notifier::_is_notification_viable_custom(reason_type type notification_option options) { engine_logger(dbg_functions, basic) << "notifier::is_notification_viable_custom()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), + SPDLOG_LOGGER_TRACE(functions_logger, "notifier::is_notification_viable_custom()"); /* forced notifications bust through everything */ if (options & notification_option_forced) { engine_logger(dbg_notifications, more) << "This is a forced notification, so we'll send it out."; - SPDLOG_LOGGER_DEBUG(log_v2::notifications(), + SPDLOG_LOGGER_DEBUG(notifications_logger, "This is a forced notification, so we'll send it out."); return true; } @@ -833,7 +829,7 @@ bool notifier::_is_notification_viable_custom(reason_type type engine_logger(dbg_notifications, more) << "Notifications are disabled, so notifications will " "not be sent out."; - SPDLOG_LOGGER_DEBUG(log_v2::notifications(), + SPDLOG_LOGGER_DEBUG(notifications_logger, "Notifications are disabled, so notifications will " "not be sent out."); return false; @@ -844,7 +840,7 @@ bool notifier::_is_notification_viable_custom(reason_type type engine_logger(dbg_notifications, more) << "Notifications are temporarily disabled for " "this notifier, so we won't send one out."; - SPDLOG_LOGGER_DEBUG(log_v2::notifications(), + SPDLOG_LOGGER_DEBUG(notifications_logger, "Notifications are temporarily disabled for " "this notifier, so we won't send one out."); return false; @@ -855,7 +851,7 @@ bool notifier::_is_notification_viable_custom(reason_type type engine_logger(dbg_notifications, more) << "We shouldn't send a CUSTOM notification during scheduled downtime."; SPDLOG_LOGGER_DEBUG( - log_v2::notifications(), + notifications_logger, "We shouldn't send a CUSTOM notification during scheduled downtime."); return false; } @@ -964,7 +960,7 @@ int notifier::notify(notifier::reason_type type, std::string const& not_data, notification_option options) { engine_logger(dbg_functions, basic) << "notifier::notify()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), "notifier::notify({})", + SPDLOG_LOGGER_TRACE(functions_logger, "notifier::notify({})", static_cast(type)); notification_category cat{get_category(type)}; @@ -975,7 +971,7 @@ int notifier::notify(notifier::reason_type type, /* For a first notification, we store what type of notification we try to * send and we fix the notification number to 1. */ if (type != reason_recovery) { - SPDLOG_LOGGER_TRACE(log_v2::notifications(), + SPDLOG_LOGGER_TRACE(notifications_logger, "_notification_number notify: {} -> {}", _notification_number, _notification_number + 1); ++_notification_number; @@ -1030,7 +1026,7 @@ int notifier::notify(notifier::reason_type type, /* In case of an acknowledgement, we must keep the _notification_number * otherwise the recovery notification won't be sent when needed. */ if (cat != cat_acknowledgement && cat != cat_downtime) { - SPDLOG_LOGGER_TRACE(log_v2::notifications(), + SPDLOG_LOGGER_TRACE(notifications_logger, "_notification_number notify: {} => 0", _notification_number); _notification_number = 0; @@ -1394,7 +1390,7 @@ void notifier::resolve(int& w, int& e) { << "' specified for host '" << get_display_name() << "' not defined anywhere"; SPDLOG_LOGGER_ERROR( - log_v2::config(), + config_logger, "Error: Event handler command '{}' specified for host '{}' not " "defined anywhere", cmd_name, get_display_name()); @@ -1418,7 +1414,7 @@ void notifier::resolve(int& w, int& e) { << "' specified for host '" << get_display_name() << "' is not defined anywhere!"; SPDLOG_LOGGER_ERROR( - log_v2::config(), + config_logger, "Error: Notifier check command '{}' specified for host '{}' is not " "defined anywhere!", cmd_name, get_display_name()); @@ -1433,7 +1429,7 @@ void notifier::resolve(int& w, int& e) { << "Warning: Notifier '" << get_display_name() << "' has no check time period defined!"; SPDLOG_LOGGER_WARN( - log_v2::config(), + config_logger, "Warning: Notifier '{}' has no check time period defined!", get_display_name()); warnings++; @@ -1448,7 +1444,7 @@ void notifier::resolve(int& w, int& e) { << "' specified for host '" << get_display_name() << "' is not defined anywhere!"; SPDLOG_LOGGER_ERROR( - log_v2::config(), + config_logger, "Error: Check period '{}' specified for host '{}' is not defined " "anywhere!", check_period(), get_display_name()); @@ -1469,7 +1465,7 @@ void notifier::resolve(int& w, int& e) { << "Error: Contact '" << it->first << "' specified in notifier '" << get_display_name() << "' is not defined anywhere!"; SPDLOG_LOGGER_ERROR( - log_v2::config(), + config_logger, "Error: Contact '{}' specified in notifier '{}' is not defined " "anywhere!", it->first, get_display_name()); @@ -1492,7 +1488,7 @@ void notifier::resolve(int& w, int& e) { << "Error: Contact group '" << it->first << "' specified in host '" << get_display_name() << "' is not defined anywhere!"; SPDLOG_LOGGER_ERROR( - log_v2::config(), + config_logger, "Error: Contact group '{}' specified in host '{}' is not defined " "anywhere!", it->first, get_display_name()); @@ -1512,7 +1508,7 @@ void notifier::resolve(int& w, int& e) { << "' specified for notifier '" << get_display_name() << "' is not defined anywhere!"; SPDLOG_LOGGER_ERROR( - log_v2::config(), + config_logger, "Error: Notification period '{}' specified for notifier '{}' is not " "defined anywhere!", notification_period(), get_display_name()); @@ -1526,7 +1522,7 @@ void notifier::resolve(int& w, int& e) { << "Warning: Notifier '" << get_display_name() << "' has no notification time period defined!"; SPDLOG_LOGGER_WARN( - log_v2::config(), + config_logger, "Warning: Notifier '{}' has no notification time period defined!", get_display_name()); warnings++; @@ -1579,11 +1575,11 @@ time_t notifier::get_next_notification_time(time_t offset) { engine_logger(dbg_functions, basic) << "notifier::get_next_notification_time()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), + SPDLOG_LOGGER_TRACE(functions_logger, "notifier::get_next_notification_time()"); engine_logger(dbg_notifications, most) << "Calculating next valid notification time..."; - SPDLOG_LOGGER_INFO(log_v2::notifications(), + SPDLOG_LOGGER_INFO(notifications_logger, "Calculating next valid notification time..."); /* default notification interval */ @@ -1591,7 +1587,7 @@ time_t notifier::get_next_notification_time(time_t offset) { engine_logger(dbg_notifications, most) << "Default interval: " << interval_to_use; - SPDLOG_LOGGER_INFO(log_v2::notifications(), "Default interval: {}", + SPDLOG_LOGGER_INFO(notifications_logger, "Default interval: {}", interval_to_use); /* @@ -1610,7 +1606,7 @@ time_t notifier::get_next_notification_time(time_t offset) { engine_logger(dbg_notifications, most) << "Found a valid escalation w/ interval of " << e->get_notification_interval(); - SPDLOG_LOGGER_INFO(log_v2::notifications(), + SPDLOG_LOGGER_INFO(notifications_logger, "Found a valid escalation w/ interval of {}", e->get_notification_interval()); @@ -1628,7 +1624,7 @@ time_t notifier::get_next_notification_time(time_t offset) { engine_logger(dbg_notifications, most) << "New interval: " << interval_to_use; - SPDLOG_LOGGER_INFO(log_v2::notifications(), "New interval: {}", + SPDLOG_LOGGER_INFO(notifications_logger, "New interval: {}", interval_to_use); } @@ -1645,7 +1641,7 @@ time_t notifier::get_next_notification_time(time_t offset) { << "Interval used for calculating next valid " "notification time: " << interval_to_use; - SPDLOG_LOGGER_INFO(log_v2::notifications(), + SPDLOG_LOGGER_INFO(notifications_logger, "Interval used for calculating next valid " "notification time: {}", interval_to_use); @@ -1690,7 +1686,7 @@ void notifier::set_notification(int32_t idx, std::string const& value) { << "Error: Bad format in the notification part, the line should start " "with 'type: '"; SPDLOG_LOGGER_ERROR( - log_v2::config(), + config_logger, "Error: Bad format in the notification part, the line should start " "with 'type: '"); return; @@ -1704,7 +1700,7 @@ void notifier::set_notification(int32_t idx, std::string const& value) { << "Error: Bad format in the notification part, the separator between " << "two fields is ', '"; SPDLOG_LOGGER_ERROR( - log_v2::config(), + config_logger, "Error: Bad format in the notification part, the separator between two " "fields is ', '"); return; @@ -1716,7 +1712,7 @@ void notifier::set_notification(int32_t idx, std::string const& value) { << "Error: Bad format in the notification part, the expected field " " after 'type' is 'author'"; SPDLOG_LOGGER_ERROR( - log_v2::config(), + config_logger, "Error: Bad format in the notification part, the expected field after " "'type' is 'author'"); return; @@ -1733,7 +1729,7 @@ void notifier::set_notification(int32_t idx, std::string const& value) { << "Error: Bad format in the notification part, the expected field " " after 'author' is 'options'"; SPDLOG_LOGGER_ERROR( - log_v2::config(), + config_logger, "Error: Bad format in the notification part, the expected field after " "'author' is 'options'"); return; @@ -1746,7 +1742,7 @@ void notifier::set_notification(int32_t idx, std::string const& value) { << "Error: Bad format in the notification part, the separator between " << "two fields is ', '"; SPDLOG_LOGGER_ERROR( - log_v2::config(), + config_logger, "Error: Bad format in the notification part, the separator between two " "fields is ', '"); return; @@ -1758,7 +1754,7 @@ void notifier::set_notification(int32_t idx, std::string const& value) { << "Error: Bad format in the notification part, the expected field " " after 'options' is 'escalated'"; SPDLOG_LOGGER_ERROR( - log_v2::config(), + config_logger, "Error: Bad format in the notification part, the expected field " " after 'options' is 'escalated'"); return; @@ -1771,7 +1767,7 @@ void notifier::set_notification(int32_t idx, std::string const& value) { << "Error: Bad format in the notification part, the separator between " << "two fields is ', '"; SPDLOG_LOGGER_ERROR( - log_v2::config(), + config_logger, "Error: Bad format in the notification part, the separator between two " "fields is ', '"); return; @@ -1783,7 +1779,7 @@ void notifier::set_notification(int32_t idx, std::string const& value) { << "Error: Bad format in the notification part, the expected field " " after 'escalated' is 'id'"; SPDLOG_LOGGER_ERROR( - log_v2::config(), + config_logger, "Error: Bad format in the notification part, the expected field " " after 'escalated' is 'id'"); return; @@ -1796,7 +1792,7 @@ void notifier::set_notification(int32_t idx, std::string const& value) { << "Error: Bad format in the notification part, the separator between " << "two fields is ', '"; SPDLOG_LOGGER_ERROR( - log_v2::config(), + config_logger, "Error: Bad format in the notification part, the separator between two " "fields is ', '"); return; @@ -1808,7 +1804,7 @@ void notifier::set_notification(int32_t idx, std::string const& value) { << "Error: Bad format in the notification part, the expected field " " after 'id' is 'number'"; SPDLOG_LOGGER_ERROR( - log_v2::config(), + config_logger, "Error: Bad format in the notification part, the expected field " " after 'id' is 'number'"); return; @@ -1821,7 +1817,7 @@ void notifier::set_notification(int32_t idx, std::string const& value) { << "Error: Bad format in the notification part, the separator between " << "two fields is ', '"; SPDLOG_LOGGER_ERROR( - log_v2::config(), + config_logger, "Error: Bad format in the notification part, the separator between two " "fields is ', '"); return; @@ -1833,7 +1829,7 @@ void notifier::set_notification(int32_t idx, std::string const& value) { << "Error: Bad format in the notification part, the expected field " " after 'number' is 'interval'"; SPDLOG_LOGGER_ERROR( - log_v2::config(), + config_logger, "Error: Bad format in the notification part, the expected field " " after 'number' is 'interval'"); return; @@ -1846,7 +1842,7 @@ void notifier::set_notification(int32_t idx, std::string const& value) { << "Error: Bad format in the notification part, the 'interval' value " "should be an integer"; SPDLOG_LOGGER_ERROR( - log_v2::config(), + config_logger, "Error: Bad format in the notification part, the 'interval' value " "should be an integer"); return; diff --git a/engine/src/retention/applier/downtime.cc b/engine/src/retention/applier/downtime.cc index 1f3fd2200b1..e14aeeb6350 100644 --- a/engine/src/retention/applier/downtime.cc +++ b/engine/src/retention/applier/downtime.cc @@ -1,26 +1,25 @@ /** -* Copyright 2011-2021 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2021 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/engine/retention/applier/downtime.hh" #include "com/centreon/engine/downtimes/downtime_manager.hh" #include "com/centreon/engine/downtimes/host_downtime.hh" #include "com/centreon/engine/downtimes/service_downtime.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" using namespace com::centreon::engine; using namespace com::centreon::engine::retention; @@ -60,7 +59,7 @@ void applier::downtime::_add_host_downtime( downtimes::downtime_manager::instance().register_downtime( downtimes::downtime::host_downtime, obj.downtime_id()); } else - log_v2::downtimes()->error( + downtimes_logger->error( "Cannot add host downtime on host '{}' because it does not exist", obj.host_name()); } @@ -84,7 +83,7 @@ void applier::downtime::_add_service_downtime( downtimes::downtime_manager::instance().register_downtime( downtimes::downtime::service_downtime, obj.downtime_id()); } else - log_v2::downtimes()->error( + downtimes_logger->error( "Cannot create service downtime on service ('{}', '{}') because it " "does not exist", obj.host_name(), obj.service_description()); diff --git a/engine/src/retention/applier/service.cc b/engine/src/retention/applier/service.cc index c5bf6aac61b..d8e060eec3b 100644 --- a/engine/src/retention/applier/service.cc +++ b/engine/src/retention/applier/service.cc @@ -1,21 +1,21 @@ /** -* Copyright 2011-2013,2015-2016,2022 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2013,2015-2016,2022 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/retention/applier/service.hh" #include "com/centreon/engine/configuration/applier/state.hh" diff --git a/engine/src/retention/dump.cc b/engine/src/retention/dump.cc index 2f7b9e40894..37a345833be 100644 --- a/engine/src/retention/dump.cc +++ b/engine/src/retention/dump.cc @@ -1,21 +1,21 @@ /** -* Copyright 2011-2013,2015-2016 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2013,2015-2016 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/retention/dump.hh" #include @@ -29,7 +29,6 @@ #include "com/centreon/engine/downtimes/service_downtime.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" using namespace com::centreon::engine; using namespace com::centreon::engine::configuration::applier; @@ -48,7 +47,7 @@ using namespace com::centreon::engine::retention; std::ostream& dump::comment(std::ostream& os, com::centreon::engine::comment const& obj) { engine_logger(dbg_functions, basic) << "dump::comment()"; - log_v2::functions()->trace("dump::comment()"); + functions_logger->trace("dump::comment()"); char const* host_name; char const* service_description; if (obj.get_comment_type() == com::centreon::engine::comment::host) { @@ -109,7 +108,7 @@ std::ostream& dump::comment(std::ostream& os, */ std::ostream& dump::comments(std::ostream& os) { engine_logger(dbg_functions, basic) << "dump::comments()"; - log_v2::functions()->trace("dump::comments()"); + functions_logger->trace("dump::comments()"); for (comment_map::iterator it(comment::comments.begin()), end(comment::comments.end()); it != end; ++it) @@ -215,7 +214,7 @@ std::ostream& dump::notifications( */ std::ostream& dump::scheduled_downtime(std::ostream& os, downtime const& obj) { engine_logger(dbg_functions, basic) << "dump::scheduled_downtime()"; - log_v2::functions()->trace("dump::scheduled_downtime()"); + functions_logger->trace("dump::scheduled_downtime()"); obj.retention(os); return os; } @@ -229,7 +228,7 @@ std::ostream& dump::scheduled_downtime(std::ostream& os, downtime const& obj) { */ std::ostream& dump::downtimes(std::ostream& os) { engine_logger(dbg_functions, basic) << "dump::downtimes()"; - log_v2::functions()->trace("dump::downtimes()"); + functions_logger->trace("dump::downtimes()"); for (auto obj = downtimes::downtime_manager::instance() .get_scheduled_downtimes() .begin(); @@ -574,7 +573,7 @@ bool dump::save(std::string const& path) { ret = true; } catch (std::exception const& e) { engine_logger(log_runtime_error, basic) << e.what(); - log_v2::runtime()->error(e.what()); + runtime_logger->error(e.what()); } // send data to event broker. diff --git a/engine/src/retention/host.cc b/engine/src/retention/host.cc index 350aceae0b9..231d69a4d12 100644 --- a/engine/src/retention/host.cc +++ b/engine/src/retention/host.cc @@ -1,26 +1,26 @@ /** -* Copyright 2011-2013,2016 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2013,2016 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/retention/host.hh" #include "com/centreon/engine/common.hh" -#include "com/centreon/engine/log_v2.hh" +#include "com/centreon/engine/globals.hh" #include "com/centreon/engine/logging.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/string.hh" @@ -1102,7 +1102,7 @@ bool host::_set_last_time_down(time_t value) { engine_logger(log_verification_error, basic) << "Warning: Host last time down cannot be in the future (bad value: " << value << ")"; - log_v2::config()->warn( + config_logger->warn( "Warning: Host last time down cannot be in the future (bad value: {})", value); value = now; @@ -1123,7 +1123,7 @@ bool host::_set_last_time_unreachable(time_t value) { << "Warning: Host last time unreachable cannot be in the future (bad " "value: " << value << ")"; - log_v2::config()->warn( + config_logger->warn( "Warning: Host last time unreachable cannot be in the future (bad " "value: {})", value); @@ -1144,7 +1144,7 @@ bool host::_set_last_time_up(time_t value) { engine_logger(log_verification_error, basic) << "Warning: Host last time up cannot be in the future (bad value: " << value << ")"; - log_v2::config()->warn( + config_logger->warn( "Warning: Host last time up cannot be in the future (bad value: {})", value); value = now; diff --git a/engine/src/retention/service.cc b/engine/src/retention/service.cc index 2183da167b3..d8be0959b7c 100644 --- a/engine/src/retention/service.cc +++ b/engine/src/retention/service.cc @@ -1,26 +1,26 @@ /** -* Copyright 2011-2013,2015-2016 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2013,2015-2016 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/retention/service.hh" #include "com/centreon/engine/common.hh" -#include "com/centreon/engine/log_v2.hh" +#include "com/centreon/engine/globals.hh" #include "com/centreon/engine/logging.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/string.hh" @@ -112,8 +112,8 @@ service::service() : service(object::service) {} service::service(type_id object_type) : object(object_type), - _next_setter(_setters), _host_id{0}, + _next_setter(_setters), _service_id{0} {} /** @@ -1183,7 +1183,7 @@ bool service::_set_last_time_critical(time_t value) { "critical cannot be in the future " "(bad value: " << value << ")"; - log_v2::config()->warn( + config_logger->warn( "Warning: Service last time " "critical cannot be in the future " "(bad value: {})", @@ -1205,7 +1205,7 @@ bool service::_set_last_time_ok(time_t value) { engine_logger(log_verification_error, basic) << "Warning: Service last time ok cannot be in the future (bad value: " << value << ")"; - log_v2::config()->warn( + config_logger->warn( "Warning: Service last time ok cannot be in the future (bad value: {})", value); value = now; @@ -1227,7 +1227,7 @@ bool service::_set_last_time_unknown(time_t value) { "unknown cannot be in the future " "(bad value: " << value << ")"; - log_v2::config()->warn( + config_logger->warn( "Warning: Service last time " "unknown cannot be in the future " "(bad value: {})", @@ -1251,7 +1251,7 @@ bool service::_set_last_time_warning(time_t value) { "warning cannot be in the future " "(bad value: " << value << ")"; - log_v2::config()->warn( + config_logger->warn( "Warning: Service last time " "warning cannot be in the future " "(bad value: {})", diff --git a/engine/src/sehandlers.cc b/engine/src/sehandlers.cc index cce3a606ceb..4ae3cb69a10 100644 --- a/engine/src/sehandlers.cc +++ b/engine/src/sehandlers.cc @@ -1,22 +1,23 @@ /** -* Copyright 1999-2010 Ethan Galstad -* Copyright 2011-2013 Merethis -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 1999-2010 Ethan Galstad + * Copyright 2011-2013 Merethis + * Copyright 2014-2024 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/sehandlers.hh" #include "com/centreon/engine/broker.hh" @@ -24,7 +25,6 @@ #include "com/centreon/engine/downtimes/downtime.hh" #include "com/centreon/engine/downtimes/downtime_manager.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/macros.hh" @@ -51,7 +51,7 @@ int obsessive_compulsive_host_check_processor( engine_logger(dbg_functions, basic) << "obsessive_compulsive_host_check_processor()"; - log_v2::functions()->trace("obsessive_compulsive_host_check_processor()"); + functions_logger->trace("obsessive_compulsive_host_check_processor()"); if (hst == nullptr) return ERROR; @@ -80,7 +80,7 @@ int obsessive_compulsive_host_check_processor( engine_logger(dbg_checks, most) << "Raw obsessive compulsive host processor command line: " << raw_command; - log_v2::checks()->debug( + checks_logger->debug( "Raw obsessive compulsive host processor command line: {}", raw_command); /* process any macros in the raw command line */ @@ -94,7 +94,7 @@ int obsessive_compulsive_host_check_processor( << "Processed obsessive compulsive host processor " "command line: " << processed_command; - log_v2::checks()->debug( + checks_logger->debug( "Processed obsessive compulsive host processor " "command line: {}", processed_command); @@ -108,7 +108,7 @@ int obsessive_compulsive_host_check_processor( engine_logger(log_runtime_error, basic) << "Error: can't execute compulsive host processor command line '" << processed_command << "' : " << e.what(); - log_v2::runtime()->error( + runtime_logger->error( "Error: can't execute compulsive host processor command line '{}' : {}", processed_command, e.what()); } @@ -120,7 +120,7 @@ int obsessive_compulsive_host_check_processor( << "Warning: OCHP command '" << processed_command << "' for host '" << hst->name() << "' timed out after " << config->ochp_timeout() << " seconds"; - log_v2::runtime()->warn( + runtime_logger->warn( "Warning: OCHP command '{}' for host '{}' timed out after {} seconds", processed_command, hst->name(), config->ochp_timeout()); @@ -144,7 +144,7 @@ int run_global_service_event_handler(nagios_macros* mac, int macro_options = STRIP_ILLEGAL_MACRO_CHARS | ESCAPE_MACRO_CHARS; engine_logger(dbg_functions, basic) << "run_global_service_event_handler()"; - log_v2::functions()->trace("run_global_service_event_handler()"); + functions_logger->trace("run_global_service_event_handler()"); if (svc == nullptr) return ERROR; @@ -160,7 +160,7 @@ int run_global_service_event_handler(nagios_macros* mac, engine_logger(dbg_eventhandlers, more) << "Running global event handler for service '" << svc->description() << "' on host '" << svc->get_hostname() << "'..."; - log_v2::events()->debug( + events_logger->debug( "Running global event handler for service '{}' on host '{}'...", svc->description(), svc->get_hostname()); @@ -177,8 +177,8 @@ int run_global_service_event_handler(nagios_macros* mac, engine_logger(dbg_eventhandlers, most) << "Raw global service event handler command line: " << raw_command; - log_v2::events()->debug("Raw global service event handler command line: {}", - raw_command); + events_logger->debug("Raw global service event handler command line: {}", + raw_command); /* process any macros in the raw command line */ process_macros_r(mac, raw_command, processed_command, macro_options); @@ -189,7 +189,7 @@ int run_global_service_event_handler(nagios_macros* mac, << "Processed global service event handler " "command line: " << processed_command; - log_v2::events()->debug( + events_logger->debug( "Processed global service event handler command line: {}", processed_command); @@ -201,7 +201,7 @@ int run_global_service_event_handler(nagios_macros* mac, << config->global_service_event_handler(); process_macros_r(mac, oss.str(), processed_logentry, macro_options); engine_logger(log_event_handler, basic) << processed_logentry; - log_v2::events()->debug(processed_logentry); + events_logger->debug(processed_logentry); } /* run the command */ @@ -213,7 +213,7 @@ int run_global_service_event_handler(nagios_macros* mac, << "Error: can't execute global service event handler " "command line '" << processed_command << "' : " << e.what(); - log_v2::runtime()->error( + runtime_logger->error( "Error: can't execute global service event handler " "command line '{}' : {}", processed_command, e.what()); @@ -225,7 +225,7 @@ int run_global_service_event_handler(nagios_macros* mac, << "Warning: Global service event handler command '" << processed_command << "' timed out after " << config->event_handler_timeout() << " seconds"; - log_v2::events()->info( + events_logger->info( "Warning: Global service event handler command '{}' timed out after {} " "seconds", processed_command, config->event_handler_timeout()); @@ -246,7 +246,7 @@ int run_service_event_handler(nagios_macros* mac, int macro_options = STRIP_ILLEGAL_MACRO_CHARS | ESCAPE_MACRO_CHARS; engine_logger(dbg_functions, basic) << "run_service_event_handler()"; - log_v2::functions()->trace("run_service_event_handler()"); + functions_logger->trace("run_service_event_handler()"); if (svc == nullptr) return ERROR; @@ -258,9 +258,8 @@ int run_service_event_handler(nagios_macros* mac, engine_logger(dbg_eventhandlers, more) << "Running event handler for service '" << svc->description() << "' on host '" << svc->get_hostname() << "'..."; - log_v2::events()->debug( - "Running event handler for service '{}' on host '{}'...", - svc->description(), svc->get_hostname()); + events_logger->debug("Running event handler for service '{}' on host '{}'...", + svc->description(), svc->get_hostname()); /* get start time */ gettimeofday(&start_time, nullptr); @@ -274,8 +273,8 @@ int run_service_event_handler(nagios_macros* mac, engine_logger(dbg_eventhandlers, most) << "Raw service event handler command line: " << raw_command; - log_v2::events()->debug("Raw service event handler command line: {}", - raw_command); + events_logger->debug("Raw service event handler command line: {}", + raw_command); /* process any macros in the raw command line */ process_macros_r(mac, raw_command, processed_command, macro_options); @@ -284,8 +283,8 @@ int run_service_event_handler(nagios_macros* mac, engine_logger(dbg_eventhandlers, most) << "Processed service event handler command line: " << processed_command; - log_v2::events()->debug("Processed service event handler command line: {}", - processed_command); + events_logger->debug("Processed service event handler command line: {}", + processed_command); if (config->log_event_handlers() == true) { std::ostringstream oss; @@ -295,7 +294,7 @@ int run_service_event_handler(nagios_macros* mac, << svc->event_handler(); process_macros_r(mac, oss.str(), processed_logentry, macro_options); engine_logger(log_event_handler, basic) << processed_logentry; - log_v2::events()->info(processed_logentry); + events_logger->info(processed_logentry); } /* run the command */ @@ -306,7 +305,7 @@ int run_service_event_handler(nagios_macros* mac, engine_logger(log_runtime_error, basic) << "Error: can't execute service event handler command line '" << processed_command << "' : " << e.what(); - log_v2::runtime()->error( + runtime_logger->error( "Error: can't execute service event handler command line '{}' : {}", processed_command, e.what()); } @@ -317,7 +316,7 @@ int run_service_event_handler(nagios_macros* mac, << "Warning: Service event handler command '" << processed_command << "' timed out after " << config->event_handler_timeout() << " seconds"; - log_v2::events()->info( + events_logger->info( "Warning: Service event handler command '{}' timed out after {} " "seconds", processed_command, config->event_handler_timeout()); @@ -334,7 +333,7 @@ int handle_host_event(com::centreon::engine::host* hst) { nagios_macros* mac(get_global_macros()); engine_logger(dbg_functions, basic) << "handle_host_event()"; - log_v2::functions()->trace("handle_host_event()"); + functions_logger->trace("handle_host_event()"); if (hst == nullptr) return ERROR; @@ -381,7 +380,7 @@ int run_global_host_event_handler(nagios_macros* mac, int macro_options = STRIP_ILLEGAL_MACRO_CHARS | ESCAPE_MACRO_CHARS; engine_logger(dbg_functions, basic) << "run_global_host_event_handler()"; - log_v2::functions()->trace("run_global_host_event_handler()"); + functions_logger->trace("run_global_host_event_handler()"); if (hst == nullptr) return ERROR; @@ -396,8 +395,8 @@ int run_global_host_event_handler(nagios_macros* mac, engine_logger(dbg_eventhandlers, more) << "Running global event handler for host '" << hst->name() << "'..."; - log_v2::events()->debug("Running global event handler for host '{}'...", - hst->name()); + events_logger->debug("Running global event handler for host '{}'...", + hst->name()); /* get start time */ gettimeofday(&start_time, nullptr); @@ -411,8 +410,8 @@ int run_global_host_event_handler(nagios_macros* mac, engine_logger(dbg_eventhandlers, most) << "Raw global host event handler command line: " << raw_command; - log_v2::events()->debug("Raw global host event handler command line: {}", - raw_command); + events_logger->debug("Raw global host event handler command line: {}", + raw_command); /* process any macros in the raw command line */ process_macros_r(mac, raw_command, processed_command, macro_options); @@ -423,9 +422,8 @@ int run_global_host_event_handler(nagios_macros* mac, << "Processed global host event handler " "command line: " << processed_command; - log_v2::events()->debug( - "Processed global host event handler command line: {}", - processed_command); + events_logger->debug("Processed global host event handler command line: {}", + processed_command); if (config->log_event_handlers() == true) { std::ostringstream oss; @@ -434,7 +432,7 @@ int run_global_host_event_handler(nagios_macros* mac, << config->global_host_event_handler(); process_macros_r(mac, oss.str(), processed_logentry, macro_options); engine_logger(log_event_handler, basic) << processed_logentry; - log_v2::events()->info(processed_logentry); + events_logger->info(processed_logentry); } /* run the command */ @@ -445,7 +443,7 @@ int run_global_host_event_handler(nagios_macros* mac, engine_logger(log_runtime_error, basic) << "Error: can't execute global host event handler command line '" << processed_command << "' : " << e.what(); - log_v2::runtime()->error( + runtime_logger->error( "Error: can't execute global host event handler command line '{}' : {}", processed_command, e.what()); } @@ -456,7 +454,7 @@ int run_global_host_event_handler(nagios_macros* mac, << "Warning: Global host event handler command '" << processed_command << "' timed out after " << config->event_handler_timeout() << " seconds"; - log_v2::events()->info( + events_logger->info( "Warning: Global host event handler command '{}' timed out after {} " "seconds", processed_command, config->event_handler_timeout()); @@ -478,7 +476,7 @@ int run_host_event_handler(nagios_macros* mac, int macro_options = STRIP_ILLEGAL_MACRO_CHARS | ESCAPE_MACRO_CHARS; engine_logger(dbg_functions, basic) << "run_host_event_handler()"; - log_v2::functions()->trace("run_host_event_handler()"); + functions_logger->trace("run_host_event_handler()"); if (hst == nullptr) return ERROR; @@ -489,8 +487,7 @@ int run_host_event_handler(nagios_macros* mac, engine_logger(dbg_eventhandlers, more) << "Running event handler for host '" << hst->name() << "'..."; - log_v2::events()->debug("Running event handler for host '{}'...", - hst->name()); + events_logger->debug("Running event handler for host '{}'...", hst->name()); /* get start time */ gettimeofday(&start_time, nullptr); @@ -504,8 +501,7 @@ int run_host_event_handler(nagios_macros* mac, engine_logger(dbg_eventhandlers, most) << "Raw host event handler command line: " << raw_command; - log_v2::events()->debug("Raw host event handler command line: {}", - raw_command); + events_logger->debug("Raw host event handler command line: {}", raw_command); /* process any macros in the raw command line */ process_macros_r(mac, raw_command, processed_command, macro_options); @@ -514,8 +510,8 @@ int run_host_event_handler(nagios_macros* mac, engine_logger(dbg_eventhandlers, most) << "Processed host event handler command line: " << processed_command; - log_v2::events()->debug("Processed host event handler command line: {}", - processed_command); + events_logger->debug("Processed host event handler command line: {}", + processed_command); if (config->log_event_handlers() == true) { std::ostringstream oss; @@ -524,7 +520,7 @@ int run_host_event_handler(nagios_macros* mac, << hst->event_handler(); process_macros_r(mac, oss.str(), processed_logentry, macro_options); engine_logger(log_event_handler, basic) << processed_logentry; - log_v2::events()->info(processed_logentry); + events_logger->info(processed_logentry); } /* run the command */ @@ -535,7 +531,7 @@ int run_host_event_handler(nagios_macros* mac, engine_logger(log_runtime_error, basic) << "Error: can't execute host event handler command line '" << processed_command << "' : " << e.what(); - log_v2::runtime()->error( + runtime_logger->error( "Error: can't execute host event handler command line '{}' : {}", processed_command, e.what()); } @@ -546,7 +542,7 @@ int run_host_event_handler(nagios_macros* mac, << "Warning: Host event handler command '" << processed_command << "' timed out after " << config->event_handler_timeout() << " seconds"; - log_v2::events()->info( + events_logger->info( "Warning: Host event handler command '{}' timed out after {} seconds", processed_command, config->event_handler_timeout()); } diff --git a/engine/src/service.cc b/engine/src/service.cc index ea19b49ccf4..58845c20d65 100644 --- a/engine/src/service.cc +++ b/engine/src/service.cc @@ -1,5 +1,5 @@ /** - * Copyright 2011 - 2022 Centreon (https://www.centreon.com/) + * Copyright 2011 - 2024 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,8 +21,6 @@ #include -#include "com/centreon/engine/log_v2.hh" - #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/checks/checker.hh" #include "com/centreon/engine/configuration/whitelist.hh" @@ -692,26 +690,26 @@ com::centreon::engine::service* add_service( engine_logger(log_config_error, basic) << "Error: Service comes from a database, therefore its service id " << "must not be null"; - log_v2::config()->error( + config_logger->error( "Error: Service comes from a database, therefore its service id must " "not be null"); return nullptr; } else if (description.empty()) { engine_logger(log_config_error, basic) << "Error: Service description is not set"; - log_v2::config()->error("Error: Service description is not set"); + config_logger->error("Error: Service description is not set"); return nullptr; } else if (host_name.empty()) { engine_logger(log_config_error, basic) << "Error: Host name of service '" << description << "' is not set"; - log_v2::config()->error("Error: Host name of service '{}' is not set", - description); + config_logger->error("Error: Host name of service '{}' is not set", + description); return nullptr; } else if (check_command.empty()) { engine_logger(log_config_error, basic) << "Error: Check command of service '" << description << "' on host '" << host_name << "' is not set"; - log_v2::config()->error( + config_logger->error( "Error: Check command of service '{}' on host '{}' is not set", description, host_name); return nullptr; @@ -723,7 +721,7 @@ com::centreon::engine::service* add_service( << "Error: The service '" << description << "' cannot be created because" << " host '" << host_name << "' does not exist (host_id is null)"; - log_v2::config()->error( + config_logger->error( "Error: The service '{}' cannot be created because host '{}' does not " "exist (host_id is null)", description, host_name); @@ -733,7 +731,7 @@ com::centreon::engine::service* add_service( << "Error: The service '" << description << "' cannot be created because the host id corresponding to the host" << " '" << host_name << "' is not the same as the one in configuration"; - log_v2::config()->error( + config_logger->error( "Error: The service '{}' cannot be created because the host id " "corresponding to the host '{}' is not the same as the one in " "configuration", @@ -748,7 +746,7 @@ com::centreon::engine::service* add_service( << "Error: Invalid max_attempts, check_interval, retry_interval" ", or notification_interval value for service '" << description << "' on host '" << host_name << "'"; - log_v2::config()->error( + config_logger->error( "Error: Invalid max_attempts, check_interval, retry_interval" ", or notification_interval value for service '{}' on host '{}'", description, host_name); @@ -760,7 +758,7 @@ com::centreon::engine::service* add_service( engine_logger(log_config_error, basic) << "Error: Service '" << description << "' on host '" << host_name << "' has already been defined"; - log_v2::config()->error( + config_logger->error( "Error: Service '{}' on host '{}' has already been defined", description, host_name); return nullptr; @@ -842,7 +840,7 @@ void service::check_for_expired_acknowledgement() { << "Acknowledgement of service '" << description() << "' on host '" << this->get_host_ptr()->name() << "' just expired"; SPDLOG_LOGGER_INFO( - log_v2::events(), + events_logger, "Acknowledgement of service '{}' on host '{}' just expired", description(), this->get_host_ptr()->name()); set_acknowledgement(AckType::NONE); @@ -1057,8 +1055,7 @@ int service::handle_async_check_result( int flapping_check_done = false; engine_logger(dbg_functions, basic) << "handle_async_service_check_result()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), - "handle_async_service_check_result()"); + SPDLOG_LOGGER_TRACE(functions_logger, "handle_async_service_check_result()"); /* get the current time */ time_t current_time = std::time(nullptr); @@ -1077,7 +1074,7 @@ int service::handle_async_check_result( << "** Handling check result for service '" << name() << "' on host '" << _hostname << "'..."; SPDLOG_LOGGER_TRACE( - log_v2::checks(), + checks_logger, "** Handling check result for service '{}' on host '{}'...", name(), _hostname); engine_logger(dbg_checks, more) @@ -1092,7 +1089,7 @@ int service::handle_async_check_result( << ", return CODE: " << queued_check_result.get_return_code() << ", OUTPUT: " << queued_check_result.get_output(); SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "HOST: {}, SERVICE: {}, CHECK TYPE: {}, OPTIONS: {}, RESCHEDULE: {}, " "EXITED OK: {}, EXEC TIME: {}, return CODE: {}, OUTPUT: {}", _hostname, name(), @@ -1117,7 +1114,7 @@ int service::handle_async_check_result( << "Discarding passive service check result because passive " "service checks are disabled globally."; SPDLOG_LOGGER_TRACE( - log_v2::checks(), + checks_logger, "Discarding passive service check result because passive " "service checks are disabled globally."); return ERROR; @@ -1127,7 +1124,7 @@ int service::handle_async_check_result( << "Discarding passive service check result because passive " "checks are disabled for this service."; SPDLOG_LOGGER_TRACE( - log_v2::checks(), + checks_logger, "Discarding passive service check result because passive " "checks are disabled for this service."); return ERROR; @@ -1161,7 +1158,7 @@ int service::handle_async_check_result( << "Discarding service freshness check result because the service " "is currently fresh (race condition avoided)."; SPDLOG_LOGGER_TRACE( - log_v2::checks(), + checks_logger, "Discarding service freshness check result because the service " "is currently fresh (race condition avoided)."); return OK; @@ -1204,7 +1201,7 @@ int service::handle_async_check_result( << "Warning: Check of service '" << name() << "' on host '" << _hostname << "' did not exit properly!"; SPDLOG_LOGGER_WARN( - log_v2::runtime(), + runtime_logger, "Warning: Check of service '{}' on host '{}' did not exit properly!", name(), _hostname); @@ -1225,7 +1222,7 @@ int service::handle_async_check_result( "exists." : "")); SPDLOG_LOGGER_WARN( - log_v2::runtime(), + runtime_logger, "Warning: return (code of {} for check of service '{}' on host '{}' " "was out of bounds.{}", queued_check_result.get_return_code(), name(), _hostname, @@ -1289,7 +1286,7 @@ int service::handle_async_check_result( << "Perf Data:\n" << (get_perf_data().empty() ? "nullptr" : get_perf_data()); SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "Parsing check output Short Output: {} Long Output: {} Perf Data: {}", get_plugin_output().empty() ? "nullptr" : get_plugin_output(), get_long_plugin_output().empty() ? "nullptr" : get_long_plugin_output(), @@ -1331,7 +1328,7 @@ int service::handle_async_check_result( engine_logger(log_passive_check, basic) << "PASSIVE SERVICE CHECK: " << _hostname << ";" << name() << ";" << _current_state << ";" << get_plugin_output(); - SPDLOG_LOGGER_INFO(log_v2::checks(), "PASSIVE SERVICE CHECK: {};{};{};{}", + SPDLOG_LOGGER_INFO(checks_logger, "PASSIVE SERVICE CHECK: {};{};{};{}", _hostname, name(), static_cast(_current_state), get_plugin_output()); } @@ -1367,7 +1364,7 @@ int service::handle_async_check_result( << " CS: " << _current_state << " LS: " << _last_state << " LHS: " << _last_hard_state; SPDLOG_LOGGER_DEBUG( - log_v2::checks(), "ST: {} CA: {} MA: {} CS: {} LS: {} LHS: {}", + checks_logger, "ST: {} CA: {} MA: {} CS: {} LS: {} LHS: {}", (get_state_type() == soft ? "SOFT" : "HARD"), get_current_attempt(), max_check_attempts(), static_cast(_current_state), static_cast(_last_state), @@ -1377,7 +1374,7 @@ int service::handle_async_check_result( if (_current_state != _last_state) { engine_logger(dbg_checks, most) << "Service has changed state since last check!"; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "Service has changed state since last check!"); state_change = true; } @@ -1390,7 +1387,7 @@ int service::handle_async_check_result( */ if (_host_problem_at_last_check && _current_state == service::state_ok) { engine_logger(dbg_checks, most) << "Service had a HARD STATE CHANGE!!"; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), "Service had a HARD STATE CHANGE!!"); + SPDLOG_LOGGER_DEBUG(checks_logger, "Service had a HARD STATE CHANGE!!"); hard_state_change = true; } @@ -1402,7 +1399,7 @@ int service::handle_async_check_result( (_current_state != _last_hard_state || get_last_state_change() > get_last_hard_state_change())) { engine_logger(dbg_checks, most) << "Service had a HARD STATE CHANGE!!"; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), "Service had a HARD STATE CHANGE!!"); + SPDLOG_LOGGER_DEBUG(checks_logger, "Service had a HARD STATE CHANGE!!"); hard_state_change = true; } @@ -1490,7 +1487,7 @@ int service::handle_async_check_result( /* if the service is up and running OK... */ if (_current_state == service::state_ok) { engine_logger(dbg_checks, more) << "Service is OK."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), "Service is OK."); + SPDLOG_LOGGER_DEBUG(checks_logger, "Service is OK."); /* reset the acknowledgement flag (this should already have been done, but * just in case...) */ @@ -1501,7 +1498,7 @@ int service::handle_async_check_result( engine_logger(dbg_checks, more) << "Host is NOT UP, so we'll check it to see if it recovered..."; SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "Host is NOT UP, so we'll check it to see if it recovered..."); /* 09/23/07 EG don't launch a new host check if we already did so earlier @@ -1511,7 +1508,7 @@ int service::handle_async_check_result( << "First host check was already initiated, so we'll skip a " "new host check."; SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "First host check was already initiated, so we'll skip a " "new host check."); } else { @@ -1524,7 +1521,7 @@ int service::handle_async_check_result( config->cached_host_check_horizon())) { engine_logger(dbg_checks, more) << "* Using cached host state: " << hst->get_current_state(); - SPDLOG_LOGGER_DEBUG(log_v2::checks(), "* Using cached host state: {}", + SPDLOG_LOGGER_DEBUG(checks_logger, "* Using cached host state: {}", static_cast(hst->get_current_state())); update_check_stats(ACTIVE_ONDEMAND_HOST_CHECK_STATS, current_time); update_check_stats(ACTIVE_CACHED_HOST_CHECK_STATS, current_time); @@ -1540,7 +1537,7 @@ int service::handle_async_check_result( /* if a hard service recovery has occurred... */ if (hard_state_change) { engine_logger(dbg_checks, more) << "Service experienced a HARD RECOVERY."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "Service experienced a HARD RECOVERY."); /* set the state type macro */ @@ -1570,7 +1567,7 @@ int service::handle_async_check_result( /* else if a soft service recovery has occurred... */ else if (state_change) { engine_logger(dbg_checks, more) << "Service experienced a SOFT RECOVERY."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "Service experienced a SOFT RECOVERY."); /* this is a soft recovery */ @@ -1589,7 +1586,7 @@ int service::handle_async_check_result( /* else no service state change has occurred... */ else { engine_logger(dbg_checks, more) << "Service did not change state."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), "Service did not change state."); + SPDLOG_LOGGER_DEBUG(checks_logger, "Service did not change state."); } /* Check if we need to send a recovery notification */ notify(reason_recovery, "", "", notification_option_none); @@ -1620,14 +1617,14 @@ int service::handle_async_check_result( /* hey, something's not working quite like it should... */ else { engine_logger(dbg_checks, more) << "Service is in a non-OK state!"; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), "Service is in a non-OK state!"); + SPDLOG_LOGGER_DEBUG(checks_logger, "Service is in a non-OK state!"); /* check the route to the host if its up right now... */ if (hst->get_current_state() == host::state_up) { engine_logger(dbg_checks, more) << "Host is currently UP, so we'll recheck its state to " "make sure..."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "Host is currently UP, so we'll recheck its state to " "make sure..."); @@ -1642,7 +1639,7 @@ int service::handle_async_check_result( route_result = hst->get_current_state(); engine_logger(dbg_checks, more) << "* Using cached host state: " << hst->get_current_state(); - SPDLOG_LOGGER_DEBUG(log_v2::checks(), "* Using cached host state: {}", + SPDLOG_LOGGER_DEBUG(checks_logger, "* Using cached host state: {}", static_cast(hst->get_current_state())); update_check_stats(ACTIVE_ONDEMAND_HOST_CHECK_STATS, current_time); update_check_stats(ACTIVE_CACHED_HOST_CHECK_STATS, current_time); @@ -1664,8 +1661,7 @@ int service::handle_async_check_result( route_result = hst->get_current_state(); engine_logger(dbg_checks, more) << "* Using last known host state: " << hst->get_current_state(); - SPDLOG_LOGGER_DEBUG(log_v2::checks(), - "* Using last known host state: {}", + SPDLOG_LOGGER_DEBUG(checks_logger, "* Using last known host state: {}", static_cast(hst->get_current_state())); update_check_stats(ACTIVE_ONDEMAND_HOST_CHECK_STATS, current_time); update_check_stats(ACTIVE_CACHED_HOST_CHECK_STATS, current_time); @@ -1676,8 +1672,7 @@ int service::handle_async_check_result( */ else { engine_logger(dbg_checks, more) << "Host is currently DOWN/UNREACHABLE."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), - "Host is currently DOWN/UNREACHABLE."); + SPDLOG_LOGGER_DEBUG(checks_logger, "Host is currently DOWN/UNREACHABLE."); /* the service wobbled between non-OK states, so check the host... */ if ((state_change && !state_changes_use_cached_state) && @@ -1686,7 +1681,7 @@ int service::handle_async_check_result( << "Service wobbled between non-OK states, so we'll recheck" " the host state..."; SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "Service wobbled between non-OK states, so we'll recheck" " the host state..."); /* previous logic was to simply run a sync (serial) host check */ @@ -1703,7 +1698,7 @@ int service::handle_async_check_result( else { engine_logger(dbg_checks, more) << "Assuming host is in same state as before..."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "Assuming host is in same state as before..."); /* if the host has never been checked before, set the checked flag and @@ -1731,7 +1726,7 @@ int service::handle_async_check_result( engine_logger(dbg_checks, most) << "Host is not UP, so we mark state changes if appropriate"; SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "Host is not UP, so we mark state changes if appropriate"); /* "fake" a hard state change for the service - well, its not really fake, @@ -1777,7 +1772,7 @@ int service::handle_async_check_result( engine_logger(dbg_checks, more) << "Current/Max Attempt(s): " << get_current_attempt() << '/' << max_check_attempts(); - SPDLOG_LOGGER_DEBUG(log_v2::checks(), "Current/Max Attempt(s): {}/{}", + SPDLOG_LOGGER_DEBUG(checks_logger, "Current/Max Attempt(s): {}/{}", get_current_attempt(), max_check_attempts()); /* if we should retry the service check, do so (except it the host is down @@ -1789,7 +1784,7 @@ int service::handle_async_check_result( engine_logger(dbg_checks, more) << "Host isn't UP, so we won't retry the service check..."; SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "Host isn't UP, so we won't retry the service check..."); /* the host is not up, so reschedule the next service check at regular @@ -1813,7 +1808,7 @@ int service::handle_async_check_result( else { engine_logger(dbg_checks, more) << "Host is UP, so we'll retry the service check..."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "Host is UP, so we'll retry the service check..."); /* this is a soft state */ @@ -1838,7 +1833,7 @@ int service::handle_async_check_result( engine_logger(dbg_checks, more) << "Looking for services to check for predictive " "dependency checks..."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "Looking for services to check for predictive " "dependency checks..."); @@ -1860,7 +1855,7 @@ int service::handle_async_check_result( << master_service->description() << "' on host '" << master_service->get_hostname() << "' queued."; SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "Predictive check of service '{}' on host '{}' queued.", master_service->description(), master_service->get_hostname()); check_servicelist.push_back(master_service); @@ -1876,7 +1871,7 @@ int service::handle_async_check_result( << "Service has reached max number of rechecks, so we'll " "handle the error..."; SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "Service has reached max number of rechecks, so we'll " "handle the error..."); @@ -1943,7 +1938,7 @@ int service::handle_async_check_result( if (reschedule_check) { engine_logger(dbg_checks, more) << "Rescheduling next check of service at " << my_ctime(&next_service_check); - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "Rescheduling next check of service at {}", my_ctime(&next_service_check)); @@ -2075,7 +2070,7 @@ int service::log_event() { << "SERVICE ALERT: " << _hostname << ";" << name() << ";" << state << ";" << state_type << ";" << get_current_attempt() << ";" << get_plugin_output(); - SPDLOG_LOGGER_INFO(log_v2::events(), "SERVICE ALERT: {};{};{};{};{};{}", + SPDLOG_LOGGER_INFO(events_logger, "SERVICE ALERT: {};{};{};{};{};{}", _hostname, name(), state, state_type, get_current_attempt(), get_plugin_output()); return OK; @@ -2101,12 +2096,12 @@ void service::check_for_flapping(bool update, * change calculation */ engine_logger(dbg_functions, basic) << "check_for_flapping()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), "check_for_flapping()"); + SPDLOG_LOGGER_TRACE(functions_logger, "check_for_flapping()"); engine_logger(dbg_flapping, more) << "Checking service '" << name() << "' on host '" << _hostname << "' for flapping..."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "Checking service '{}' on host '{}' for flapping...", name(), _hostname); @@ -2178,7 +2173,7 @@ void service::check_for_flapping(bool update, << com::centreon::logging::setprecision(2) << "LFT=" << low_threshold << ", HFT=" << high_threshold << ", CPC=" << curved_percent_change << ", PSC=" << curved_percent_change << "%"; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "LFT={:.2f}, HFT={:.2f}, CPC={:.2f}, PSC={:.2f}%", low_threshold, high_threshold, curved_percent_change, curved_percent_change); @@ -2212,7 +2207,7 @@ void service::check_for_flapping(bool update, << com::centreon::logging::setprecision(2) << "Service " << (is_flapping ? "is" : "is not") << " flapping (" << curved_percent_change << "% state change)."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "Service {} flapping ({:.2f}% state change).", is_flapping ? "is" : "is not", curved_percent_change); @@ -2231,7 +2226,7 @@ int service::handle_service_event() { nagios_macros* mac(get_global_macros()); engine_logger(dbg_functions, basic) << "handle_service_event()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), "handle_service_event()"); + SPDLOG_LOGGER_TRACE(functions_logger, "handle_service_event()"); /* send event data to broker */ broker_statechange_data(NEBTYPE_STATECHANGE_END, NEBFLAG_NONE, NEBATTR_NONE, @@ -2280,7 +2275,7 @@ int service::obsessive_compulsive_service_check_processor() { engine_logger(dbg_functions, basic) << "obsessive_compulsive_service_check_processor()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), + SPDLOG_LOGGER_TRACE(functions_logger, "obsessive_compulsive_service_check_processor()"); /* bail out if we shouldn't be obsessing */ @@ -2313,7 +2308,7 @@ int service::obsessive_compulsive_service_check_processor() { << "Raw obsessive compulsive service processor " "command line: " << raw_command; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "Raw obsessive compulsive service processor " "command line: {}", raw_command); @@ -2328,7 +2323,7 @@ int service::obsessive_compulsive_service_check_processor() { engine_logger(dbg_checks, most) << "Processed obsessive compulsive service " "processor command line: " << processed_command; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "Processed obsessive compulsive service " "processor command line: {}", processed_command); @@ -2343,7 +2338,7 @@ int service::obsessive_compulsive_service_check_processor() { << "Error: can't execute compulsive service processor command line '" << processed_command << "' : " << e.what(); SPDLOG_LOGGER_ERROR( - log_v2::runtime(), + runtime_logger, "Error: can't execute compulsive service processor command line '{}' : " "{}", processed_command, e.what()); @@ -2358,7 +2353,7 @@ int service::obsessive_compulsive_service_check_processor() { << name() << "' on host '" << _hostname << "' timed out after " << config->ocsp_timeout() << " seconds"; SPDLOG_LOGGER_WARN( - log_v2::runtime(), + runtime_logger, "Warning: OCSP command '{}' for service '{}' on host '{}' timed out " "after {} seconds", processed_command, name(), _hostname, config->ocsp_timeout()); @@ -2390,13 +2385,13 @@ int service::run_scheduled_check(int check_options, double latency) { bool time_is_valid = true; engine_logger(dbg_functions, basic) << "run_scheduled_service_check()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), "run_scheduled_service_check()"); + SPDLOG_LOGGER_TRACE(functions_logger, "run_scheduled_service_check()"); engine_logger(dbg_checks, basic) << "Attempting to run scheduled check of service '" << name() << "' on host '" << _hostname << "': check options=" << check_options << ", latency=" << latency; SPDLOG_LOGGER_TRACE( - log_v2::checks(), + checks_logger, "Attempting to run scheduled check of service '{}' on host '{}': check " "options={}, latency={}", name(), _hostname, check_options, latency); @@ -2409,7 +2404,7 @@ int service::run_scheduled_check(int check_options, double latency) { if (result == ERROR) { engine_logger(dbg_checks, more) << "Unable to run scheduled service check at this time"; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "Unable to run scheduled service check at this time"); /* only attempt to (re)schedule checks that should get checked... */ @@ -2447,7 +2442,7 @@ int service::run_scheduled_check(int check_options, double latency) { << "' could not be " "rescheduled properly. Scheduling check for next week..."; SPDLOG_LOGGER_WARN( - log_v2::runtime(), + runtime_logger, "Warning: Check of service '{}' on host '{}' could not be " "rescheduled properly. Scheduling check for next week...", name(), _hostname); @@ -2455,7 +2450,7 @@ int service::run_scheduled_check(int check_options, double latency) { << "Unable to find any valid times to reschedule the next " "service check!"; SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "Unable to find any valid times to reschedule the next " "service check!"); } @@ -2466,7 +2461,7 @@ int service::run_scheduled_check(int check_options, double latency) { engine_logger(dbg_checks, more) << "Rescheduled next service check for " << my_ctime(&next_valid_time); - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "Rescheduled next service check for {}", my_ctime(&next_valid_time)); } @@ -2533,7 +2528,7 @@ int service::run_async_check_local(int check_options, << "service::run_async_check, check_options=" << check_options << ", latency=" << latency << ", scheduled_check=" << scheduled_check << ", reschedule_check=" << reschedule_check; - SPDLOG_LOGGER_TRACE(log_v2::functions(), + SPDLOG_LOGGER_TRACE(functions_logger, "service::run_async_check, check_options={}, latency={}, " "scheduled_check={}, reschedule_check={}", check_options, latency, scheduled_check, @@ -2545,7 +2540,7 @@ int service::run_async_check_local(int check_options, << "Error: Attempt to run active check on service '" << description() << "' on host '" << get_host_ptr()->name() << "' with no check command"; SPDLOG_LOGGER_ERROR( - log_v2::runtime(), + runtime_logger, "Error: Attempt to run active check on service '{}' on host '{}' with " "no check command", description(), get_host_ptr()->name()); @@ -2555,7 +2550,7 @@ int service::run_async_check_local(int check_options, engine_logger(dbg_checks, basic) << "** Running async check of service '" << description() << "' on host '" << get_hostname() << "'..."; - SPDLOG_LOGGER_TRACE(log_v2::checks(), + SPDLOG_LOGGER_TRACE(checks_logger, "** Running async check of service '{} on host '{}'...", description(), get_hostname()); @@ -2577,7 +2572,7 @@ int service::run_async_check_local(int check_options, << "Error: Some broker module cancelled check of service '" << description() << "' on host '" << get_hostname(); SPDLOG_LOGGER_ERROR( - log_v2::runtime(), + runtime_logger, "Error: Some broker module cancelled check of service '{}' on host " "'{}'", description(), get_hostname()); @@ -2589,7 +2584,7 @@ int service::run_async_check_local(int check_options, << "Some broker module overrode check of service '" << description() << "' on host '" << get_hostname() << "' so we'll bail out"; SPDLOG_LOGGER_TRACE( - log_v2::functions(), + functions_logger, "Some broker module overrode check of service '{}' on host '{}' so " "we'll bail out", description(), get_hostname()); @@ -2599,7 +2594,7 @@ int service::run_async_check_local(int check_options, // Checking starts. engine_logger(dbg_checks, basic) << "Checking service '" << description() << "' on host '" << get_hostname() << "'..."; - SPDLOG_LOGGER_TRACE(log_v2::checks(), "Checking service '{}' on host '{}'...", + SPDLOG_LOGGER_TRACE(checks_logger, "Checking service '{}' on host '{}'...", description(), get_hostname()); // Clear check options. @@ -2625,7 +2620,7 @@ int service::run_async_check_local(int check_options, ++currently_running_service_checks; engine_logger(dbg_checks, basic) << "Current running service checks: " << currently_running_service_checks; - SPDLOG_LOGGER_TRACE(log_v2::checks(), "Current running service checks: {}", + SPDLOG_LOGGER_TRACE(checks_logger, "Current running service checks: {}", currently_running_service_checks); // Set the execution flag. @@ -2676,13 +2671,13 @@ int service::run_async_check_local(int check_options, // allowed by whitelist? if (!is_whitelist_allowed(processed_cmd)) { SPDLOG_LOGGER_ERROR( - log_v2::commands(), + commands_logger, "service {}: this command cannot be executed because of " "security restrictions on the poller. A whitelist has " "been defined, and it does not include this command.", name()); - SPDLOG_LOGGER_DEBUG(log_v2::commands(), + SPDLOG_LOGGER_DEBUG(commands_logger, "service {}: command not allowed by whitelist {}", name(), processed_cmd); run_failure(configuration::command_blacklist_output); @@ -2695,7 +2690,7 @@ int service::run_async_check_local(int check_options, uint64_t id = cmd->run(processed_cmd, *macros, config->service_check_timeout(), check_result_info, this); - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "run id={} {} for service {} host {}", id, processed_cmd, _service_id, _hostname); } catch (com::centreon::exceptions::interruption const& e) { @@ -2705,7 +2700,7 @@ int service::run_async_check_local(int check_options, engine_logger(log_runtime_warning, basic) << "Error: Service check command execution failed: " << e.what(); - SPDLOG_LOGGER_WARN(log_v2::runtime(), + SPDLOG_LOGGER_WARN(runtime_logger, "Error: Service check command execution failed: {}", e.what()); } @@ -2730,7 +2725,7 @@ bool service::schedule_check(time_t check_time, uint32_t options, bool no_update_status_now) { engine_logger(dbg_functions, basic) << "schedule_service_check()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), "schedule_service_check()"); + SPDLOG_LOGGER_TRACE(functions_logger, "schedule_service_check()"); engine_logger(dbg_checks, basic) << "Scheduling a " @@ -2738,7 +2733,7 @@ bool service::schedule_check(time_t check_time, << ", active check of service '" << name() << "' on host '" << _hostname << "' @ " << my_ctime(&check_time); SPDLOG_LOGGER_TRACE( - log_v2::checks(), + checks_logger, "Scheduling a {}, active check of service '{}' on host '{}' @ {}", options & CHECK_OPTION_FORCE_EXECUTION ? "forced" : "non-forced", name(), _hostname, my_ctime(&check_time)); @@ -2748,7 +2743,7 @@ bool service::schedule_check(time_t check_time, if (!active_checks_enabled() && !(options & CHECK_OPTION_FORCE_EXECUTION)) { engine_logger(dbg_checks, basic) << "Active checks of this service are disabled."; - SPDLOG_LOGGER_TRACE(log_v2::checks(), + SPDLOG_LOGGER_TRACE(checks_logger, "Active checks of this service are disabled."); return false; } @@ -2766,7 +2761,7 @@ bool service::schedule_check(time_t check_time, << "Found another service check event for this service @ " << my_ctime(&temp_event->run_time); SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "Found another service check event for this service @ {}", my_ctime(&temp_event->run_time)); @@ -2784,7 +2779,7 @@ bool service::schedule_check(time_t check_time, << "New service check event is forced and occurs before the " "existing event, so the new event will be used instead."; SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "New service check event is forced and occurs before the " "existing event, so the new event will be used instead."); } @@ -2798,7 +2793,7 @@ bool service::schedule_check(time_t check_time, << "New service check event is forced, so it will be used " "instead of the existing event."; SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "New service check event is forced, so it will be used " "instead of the existing event."); } @@ -2810,7 +2805,7 @@ bool service::schedule_check(time_t check_time, << "New service check event occurs before the existing " "(older) event, so it will be used instead."; SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "New service check event occurs before the existing " "(older) event, so it will be used instead."); } @@ -2820,7 +2815,7 @@ bool service::schedule_check(time_t check_time, << "New service check event occurs after the existing event, " "so we'll ignore it."; SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "New service check event occurs after the existing event, " "so we'll ignore it."); } @@ -2837,7 +2832,7 @@ bool service::schedule_check(time_t check_time, engine_logger(dbg_checks, most) << "Keeping original service check event (ignoring the new one)."; SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "Keeping original service check event (ignoring the new one)."); } } @@ -2848,8 +2843,7 @@ bool service::schedule_check(time_t check_time, // Schedule a new event. if (!use_original_event) { engine_logger(dbg_checks, most) << "Scheduling new service check event."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), - "Scheduling new service check event."); + SPDLOG_LOGGER_DEBUG(checks_logger, "Scheduling new service check event."); // Allocate memory for a new event item. try { @@ -2884,11 +2878,11 @@ void service::set_flap(double percent_change, double low_threshold [[maybe_unused]], int allow_flapstart_notification) { engine_logger(dbg_functions, basic) << "set_service_flap()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), "set_service_flap()"); + SPDLOG_LOGGER_TRACE(functions_logger, "set_service_flap()"); engine_logger(dbg_flapping, more) << "Service '" << name() << "' on host '" << _hostname << "' started flapping!"; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "Service '{}' on host '{}' started flapping!", name(), _hostname); @@ -2899,7 +2893,7 @@ void service::set_flap(double percent_change, << ";STARTED; Service appears to have started flapping (" << percent_change << "% change >= " << high_threshold << "% threshold)"; SPDLOG_LOGGER_WARN( - log_v2::runtime(), + runtime_logger, "SERVICE FLAPPING ALERT: {};{};STARTED; Service appears to have started " "flapping ({:.1f}% change >= {:.1f}% threshold)", _hostname, name(), percent_change, high_threshold); @@ -2938,11 +2932,11 @@ void service::clear_flap(double percent_change, double high_threshold [[maybe_unused]], double low_threshold) { engine_logger(dbg_functions, basic) << "clear_service_flap()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), "clear_service_flap()"); + SPDLOG_LOGGER_TRACE(functions_logger, "clear_service_flap()"); engine_logger(dbg_flapping, more) << "Service '" << name() << "' on host '" << _hostname << "' stopped flapping."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "Service '{}' on host '{}' stopped flapping.", name(), _hostname); @@ -2953,7 +2947,7 @@ void service::clear_flap(double percent_change, << ";STOPPED; Service appears to have stopped flapping (" << percent_change << "% change < " << low_threshold << "% threshold)"; SPDLOG_LOGGER_INFO( - log_v2::events(), + events_logger, "SERVICE FLAPPING ALERT: {};{};STOPPED; Service appears to have stopped " "flapping ({:.1f}% change < {:.1f}% threshold)", _hostname, name(), percent_change, low_threshold); @@ -2978,12 +2972,12 @@ void service::enable_flap_detection() { unsigned long attr = MODATTR_FLAP_DETECTION_ENABLED; engine_logger(dbg_functions, basic) << "service::enable_flap_detection()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), "service::enable_flap_detection()"); + SPDLOG_LOGGER_TRACE(functions_logger, "service::enable_flap_detection()"); engine_logger(dbg_flapping, more) << "Enabling flap detection for service '" << name() << "' on host '" << _hostname << "'."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "Enabling flap detection for service '{}' on host '{}'.", name(), _hostname); @@ -3015,12 +3009,12 @@ void service::disable_flap_detection() { unsigned long attr = MODATTR_FLAP_DETECTION_ENABLED; engine_logger(dbg_functions, basic) << "disable_service_flap_detection()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), "disable_service_flap_detection()"); + SPDLOG_LOGGER_TRACE(functions_logger, "disable_service_flap_detection()"); engine_logger(dbg_flapping, more) << "Disabling flap detection for service '" << name() << "' on host '" << _hostname << "'."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "Disabling flap detection for service '{}' on host '{}'.", name(), _hostname); @@ -3073,7 +3067,7 @@ bool service::verify_check_viability(int check_options, int check_interval = 0; engine_logger(dbg_functions, basic) << "check_service_check_viability()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), "check_service_check_viability()"); + SPDLOG_LOGGER_TRACE(functions_logger, "check_service_check_viability()"); /* get the check interval to use if we need to reschedule the check */ if (get_state_type() == soft && _current_state != service::state_ok) @@ -3099,7 +3093,7 @@ bool service::verify_check_viability(int check_options, engine_logger(dbg_checks, most) << "Active checks of the service are currently disabled."; SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "Active checks of the service are currently disabled."); } @@ -3116,7 +3110,7 @@ bool service::verify_check_viability(int check_options, << "This is not a valid time for this service to be actively " "checked."; SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "This is not a valid time for this service to be actively " "checked."); } @@ -3131,7 +3125,7 @@ bool service::verify_check_viability(int check_options, << "Execution dependencies for this service failed, so it will " "not be actively checked."; SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "Execution dependencies for this service failed, so it will " "not be actively checked."); } @@ -3167,11 +3161,10 @@ int service::notify_contact(nagios_macros* mac, int neb_result; engine_logger(dbg_functions, basic) << "notify_contact_of_service()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), "notify_contact_of_service()"); + SPDLOG_LOGGER_TRACE(functions_logger, "notify_contact_of_service()"); engine_logger(dbg_notifications, most) << "** Notifying contact '" << cntct->get_name() << "'"; - log_v2::notifications()->debug("** Notifying contact '{}'", - cntct->get_name()); + notifications_logger->debug("** Notifying contact '{}'", cntct->get_name()); /* get start time */ gettimeofday(&start_time, nullptr); @@ -3215,7 +3208,7 @@ int service::notify_contact(nagios_macros* mac, engine_logger(dbg_notifications, most) << "Raw notification command: " << raw_command; - log_v2::notifications()->debug("Raw notification command: {}", raw_command); + notifications_logger->debug("Raw notification command: {}", raw_command); /* process any macros contained in the argument */ process_macros_r(mac, raw_command, processed_command, macro_options); @@ -3226,8 +3219,8 @@ int service::notify_contact(nagios_macros* mac, engine_logger(dbg_notifications, most) << "Processed notification command: " << processed_command; - log_v2::notifications()->trace("Processed notification command: {}", - processed_command); + notifications_logger->trace("Processed notification command: {}", + processed_command); /* log the notification to program log file */ if (config->log_notifications()) { @@ -3259,10 +3252,10 @@ int service::notify_contact(nagios_macros* mac, << get_hostname() << ';' << description() << ';' << service_notification_state << ";" << cmd->get_name() << ';' << get_plugin_output() << info; - log_v2::notifications()->info( - "SERVICE NOTIFICATION: {};{};{};{};{};{};{}", cntct->get_name(), - get_hostname(), description(), service_notification_state, - cmd->get_name(), get_plugin_output(), info); + notifications_logger->info("SERVICE NOTIFICATION: {};{};{};{};{};{};{}", + cntct->get_name(), get_hostname(), + description(), service_notification_state, + cmd->get_name(), get_plugin_output(), info); } /* run the notification command */ @@ -3274,7 +3267,7 @@ int service::notify_contact(nagios_macros* mac, engine_logger(log_runtime_error, basic) << "Error: can't execute service notification '" << cntct->get_name() << "' : " << e.what(); - SPDLOG_LOGGER_ERROR(log_v2::runtime(), + SPDLOG_LOGGER_ERROR(runtime_logger, "Error: can't execute service notification '{}' : {}", cntct->get_name(), e.what()); } @@ -3286,7 +3279,7 @@ int service::notify_contact(nagios_macros* mac, << "' service notification command '" << processed_command << "' timed out after " << config->notification_timeout() << " seconds"; - log_v2::notifications()->info( + notifications_logger->info( "Warning: Contact '{}' service notification command '{}' timed out " "after {} seconds", cntct->get_name(), processed_command, config->notification_timeout()); @@ -3338,7 +3331,7 @@ bool service::is_valid_escalation_for_notification(escalation const* e, engine_logger(dbg_functions, basic) << "service::is_valid_escalation_for_notification()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), + SPDLOG_LOGGER_TRACE(functions_logger, "service::is_valid_escalation_for_notification()"); /* get the current time */ @@ -3411,7 +3404,7 @@ bool service::is_result_fresh(time_t current_time, int log_this) { engine_logger(dbg_checks, most) << "Checking freshness of service '" << this->description() << "' on host '" << this->get_hostname() << "'..."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "Checking freshness of service '{}' on host '{}'...", this->description(), this->get_hostname()); @@ -3432,8 +3425,7 @@ bool service::is_result_fresh(time_t current_time, int log_this) { engine_logger(dbg_checks, most) << "Freshness thresholds: service=" << this->get_freshness_threshold() << ", use=" << freshness_threshold; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), - "Freshness thresholds: service={}, use={}", + SPDLOG_LOGGER_DEBUG(checks_logger, "Freshness thresholds: service={}, use={}", this->get_freshness_threshold(), freshness_threshold); /* calculate expiration time */ @@ -3464,7 +3456,7 @@ bool service::is_result_fresh(time_t current_time, int log_this) { << "HBC: " << this->has_been_checked() << ", PS: " << program_start << ", ES: " << event_start << ", LC: " << get_last_check() << ", CT: " << current_time << ", ET: " << expiration_time; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "HBC: {}, PS: {}, ES: {}, LC: {}, CT: {}, ET: {}", this->has_been_checked(), program_start, event_start, get_last_check(), current_time, expiration_time); @@ -3487,7 +3479,7 @@ bool service::is_result_fresh(time_t current_time, int log_this) { << "s). I'm forcing an immediate check " "of the service."; SPDLOG_LOGGER_WARN( - log_v2::runtime(), + runtime_logger, "Warning: The results of service '{}' on host '{}' are stale by {}d " "{}h {}m {}s (threshold={}d {}h {}m {}s). I'm forcing an immediate " "check " @@ -3503,7 +3495,7 @@ bool service::is_result_fresh(time_t current_time, int log_this) { << "s). Forcing an immediate check of " "the service..."; SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "Check results for service '{}' on host '{}' are stale by {}d {}h {}m " "{}s (threshold={}d {}h {}m {}s). Forcing an immediate check of the " "service...", @@ -3516,7 +3508,7 @@ bool service::is_result_fresh(time_t current_time, int log_this) { engine_logger(dbg_checks, more) << "Check results for service '" << this->description() << "' on host '" << this->get_hostname() << "' are fresh."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "Check results for service '{}' on host '{}' are fresh.", this->description(), this->get_hostname()); @@ -3530,7 +3522,7 @@ bool service::is_result_fresh(time_t current_time, int log_this) { void service::handle_flap_detection_disabled() { engine_logger(dbg_functions, basic) << "handle_service_flap_detection_disabled()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), + SPDLOG_LOGGER_TRACE(functions_logger, "handle_service_flap_detection_disabled()"); /* if the service was flapping, remove the flapping indicator */ @@ -3546,7 +3538,7 @@ void service::handle_flap_detection_disabled() { engine_logger(log_info_message, basic) << "SERVICE FLAPPING ALERT: " << this->get_hostname() << ";" << this->description() << ";DISABLED; Flap detection has been disabled"; - log_v2::events()->debug( + events_logger->debug( "SERVICE FLAPPING ALERT: {};{};DISABLED; Flap detection has been " "disabled", this->get_hostname(), this->description()); @@ -3589,7 +3581,7 @@ bool service::authorized_by_dependencies( dependency::types dependency_type) const { engine_logger(dbg_functions, basic) << "service::authorized_by_dependencies()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), + SPDLOG_LOGGER_TRACE(functions_logger, "service::authorized_by_dependencies()"); auto p( @@ -3646,7 +3638,7 @@ void service::check_for_orphaned() { time_t expected_time{0L}; engine_logger(dbg_functions, basic) << "check_for_orphaned_services()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), "check_for_orphaned_services()"); + SPDLOG_LOGGER_TRACE(functions_logger, "check_for_orphaned_services()"); /* get the current time */ time(¤t_time); @@ -3677,7 +3669,7 @@ void service::check_for_orphaned() { "(results never came back). I'm scheduling an immediate check " "of the service..."; SPDLOG_LOGGER_WARN( - log_v2::runtime(), + runtime_logger, "Warning: The check of service '{}' on host '{}' looks like it was " "orphaned " "(results never came back). I'm scheduling an immediate check " @@ -3688,7 +3680,7 @@ void service::check_for_orphaned() { << "Service '" << it->first.second << "' on host '" << it->first.first << "' was orphaned, so we're scheduling an immediate check..."; SPDLOG_LOGGER_DEBUG( - log_v2::checks(), + checks_logger, "Service '{}' on host '{}' was orphaned, so we're scheduling an " "immediate check...", it->first.second, it->first.first); @@ -3711,17 +3703,17 @@ void service::check_result_freshness() { time_t current_time{0L}; engine_logger(dbg_functions, basic) << "check_service_result_freshness()"; - SPDLOG_LOGGER_TRACE(log_v2::functions(), "check_service_result_freshness()"); + SPDLOG_LOGGER_TRACE(functions_logger, "check_service_result_freshness()"); engine_logger(dbg_checks, more) << "Checking the freshness of service check results..."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "Checking the freshness of service check results..."); /* bail out if we're not supposed to be checking freshness */ if (!config->check_service_freshness()) { engine_logger(dbg_checks, more) << "Service freshness checking is disabled."; - SPDLOG_LOGGER_DEBUG(log_v2::checks(), + SPDLOG_LOGGER_DEBUG(checks_logger, "Service freshness checking is disabled."); return; } @@ -3816,7 +3808,7 @@ void service::resolve(int& w, int& e) { engine_logger(log_verification_error, basic) << "Error: Service description '" << name() << "' of host '" << _hostname << "' has problem in its notifier part: " << e.what(); - log_v2::config()->error( + config_logger->error( "Error: Service description '{}' of host '{}' has problem in its " "notifier part: {}", name(), _hostname, e.what()); @@ -3834,7 +3826,7 @@ void service::resolve(int& w, int& e) { << "' specified in service " "'" << name() << "' not defined anywhere!"; - log_v2::config()->error( + config_logger->error( "Error: Host '{}' specified in service '{}' not defined anywhere!", _hostname, name()); errors++; @@ -3862,7 +3854,7 @@ void service::resolve(int& w, int& e) { << "' for host '" << _hostname << "' doesn't make any sense - specify warning and /or critical " "options as well"; - log_v2::config()->warn( + config_logger->warn( "Warning: Recovery notification option in service '{}' for host '{}' " "doesn't make any sense - specify warning and /or critical " "options as well", @@ -3879,7 +3871,7 @@ void service::resolve(int& w, int& e) { "its check interval! Notifications are only re-sent after " "checks are made, so the effective notification interval will " "be that of the check interval."; - log_v2::config()->warn( + config_logger->warn( "Warning: Service '{}' on host '{}' has a notification interval less " "than " "its check interval! Notifications are only re-sent after " @@ -3895,7 +3887,7 @@ void service::resolve(int& w, int& e) { << "Error: The description string for service '" << name() << "' on host '" << _hostname << "' contains one or more illegal characters."; - log_v2::config()->error( + config_logger->error( "Error: The description string for service '{}' on host '{}' contains " "one or more illegal characters.", name(), _hostname); diff --git a/engine/src/servicedependency.cc b/engine/src/servicedependency.cc index 257659a64e3..2b6c62cc0d8 100644 --- a/engine/src/servicedependency.cc +++ b/engine/src/servicedependency.cc @@ -1,27 +1,26 @@ /** -* Copyright 2011-2019 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2019 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/servicedependency.hh" #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/shared.hh" #include "com/centreon/engine/string.hh" @@ -299,7 +298,7 @@ void servicedependency::resolve(int& w, int& e) { << "' specified in service dependency for service '" << get_service_description() << "' on host '" << get_hostname() << "' is not defined anywhere!"; - log_v2::config()->error( + config_logger->error( "Error: Dependent service '{}' on host '{}' specified in service " "dependency for service '{}' on host '{}' is not defined anywhere!", get_dependent_service_description(), get_dependent_hostname(), @@ -319,7 +318,7 @@ void servicedependency::resolve(int& w, int& e) { << get_hostname() << "' specified in service dependency for service '" << get_dependent_service_description() << "' on host '" << get_dependent_hostname() << "' is not defined anywhere!"; - log_v2::config()->error( + config_logger->error( "Error: Service '{}' on host '{}' specified in service dependency for " "service '{}' on host '{}' is not defined anywhere!", get_service_description(), get_hostname(), @@ -337,7 +336,7 @@ void servicedependency::resolve(int& w, int& e) { << "Error: Service dependency definition for service '" << get_dependent_service_description() << "' on host '" << get_dependent_hostname() << "' is circular (it depends on itself)!"; - log_v2::config()->error( + config_logger->error( "Error: Service dependency definition for service '{}' on host '{}' is " "circular (it depends on itself)!", get_dependent_service_description(), get_dependent_hostname()); @@ -355,7 +354,7 @@ void servicedependency::resolve(int& w, int& e) { << "' specified in service dependency for service '" << get_dependent_service_description() << "' on host '" << get_dependent_hostname() << "' is not defined anywhere!"; - log_v2::config()->error( + config_logger->error( "Error: Dependency period '{}' specified in service dependency for " "service '{}' on host '{}' is not defined anywhere!", get_dependency_period(), get_dependent_service_description(), diff --git a/engine/src/serviceescalation.cc b/engine/src/serviceescalation.cc index 4c8441891a0..5d98f226890 100644 --- a/engine/src/serviceescalation.cc +++ b/engine/src/serviceescalation.cc @@ -1,28 +1,27 @@ /** -* Copyright 2011-2019 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2024 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/serviceescalation.hh" #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" using namespace com::centreon::engine::configuration::applier; @@ -73,7 +72,7 @@ std::string const& serviceescalation::get_description() const { bool serviceescalation::is_viable(int state, uint32_t notification_number) const { engine_logger(dbg_functions, basic) << "serviceescalation::is_viable()"; - log_v2::functions()->trace("serviceescalation::is_viable()"); + functions_logger->trace("serviceescalation::is_viable()"); bool retval{escalation::is_viable(state, notification_number)}; if (retval) { @@ -103,7 +102,7 @@ void serviceescalation::resolve(int& w, int& e) { << "Error: Service '" << get_description() << "' on host '" << get_hostname() << "' specified in service escalation is not defined anywhere!"; - log_v2::config()->error( + config_logger->error( "Error: Service '{}' on host '{}' specified in service escalation is " "not defined anywhere!", get_description(), get_hostname()); @@ -119,7 +118,7 @@ void serviceescalation::resolve(int& w, int& e) { } catch (std::exception const& ee) { engine_logger(log_verification_error, basic) << "Error: Notifier escalation error: " << ee.what(); - log_v2::config()->error("Error: Notifier escalation error: {}", ee.what()); + config_logger->error("Error: Notifier escalation error: {}", ee.what()); } // Add errors. diff --git a/engine/src/servicegroup.cc b/engine/src/servicegroup.cc index 6f991d31b36..c8b24fcf126 100644 --- a/engine/src/servicegroup.cc +++ b/engine/src/servicegroup.cc @@ -1,28 +1,27 @@ /** -* Copyright 2011-2013 Merethis -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2013 Merethis + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/servicegroup.hh" #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/shared.hh" #include "com/centreon/engine/string.hh" @@ -63,8 +62,8 @@ servicegroup::servicegroup(uint64_t id, engine_logger(log_config_error, basic) << "Error: Servicegroup '" << group_name << "' has already been defined"; - log_v2::config()->error("Error: Servicegroup '{}' has already been defined", - group_name); + config_logger->error("Error: Servicegroup '{}' has already been defined", + group_name); throw engine_error() << "Could not register service group '" << group_name << "'"; } @@ -176,7 +175,7 @@ void servicegroup::resolve(int& w, int& e) { << "Error: Service '" << it->first.second << "' on host '" << it->first.first << "' specified in service group '" << _group_name << "' is not defined anywhere!"; - log_v2::config()->error( + config_logger->error( "Error: Service '{}' on host '{}' specified in service group '{}' is " "not defined anywhere!", it->first.second, it->first.first, _group_name); @@ -202,7 +201,7 @@ void servicegroup::resolve(int& w, int& e) { engine_logger(log_verification_error, basic) << "Error: The name of servicegroup '" << _group_name << "' contains one or more illegal characters."; - log_v2::config()->error( + config_logger->error( "Error: The name of servicegroup '{}' contains one or more illegal " "characters.", _group_name); diff --git a/engine/src/timeperiod.cc b/engine/src/timeperiod.cc index 1baf1a2b33c..e156edd99f2 100644 --- a/engine/src/timeperiod.cc +++ b/engine/src/timeperiod.cc @@ -1,21 +1,22 @@ /** -* Copyright 2011-2013 Merethis -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2013 Merethis + * Copyright 2014-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include "com/centreon/engine/timeperiod.hh" #include "com/centreon/engine/broker.hh" @@ -23,7 +24,6 @@ #include "com/centreon/engine/daterange.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/shared.hh" #include "com/centreon/engine/string.hh" @@ -50,7 +50,7 @@ timeperiod::timeperiod(std::string const& name, std::string const& alias) if (name.empty() || alias.empty()) { engine_logger(log_config_error, basic) << "Error: Name or alias for timeperiod is NULL"; - log_v2::config()->error("Error: Name or alias for timeperiod is NULL"); + config_logger->error("Error: Name or alias for timeperiod is NULL"); throw engine_error() << "Could not register time period '" << name << "'"; } @@ -59,8 +59,8 @@ timeperiod::timeperiod(std::string const& name, std::string const& alias) if (it != timeperiod::timeperiods.end()) { engine_logger(log_config_error, basic) << "Error: Timeperiod '" << name << "' has already been defined"; - log_v2::config()->error("Error: Timeperiod '{}' has already been defined", - name); + config_logger->error("Error: Timeperiod '{}' has already been defined", + name); throw engine_error() << "Could not register time period '" << name << "'"; } } @@ -755,7 +755,7 @@ static bool _timerange_to_time_t(const timerange& trange, */ bool check_time_against_period(time_t test_time, timeperiod* tperiod) { engine_logger(dbg_functions, basic) << "check_time_against_period()"; - log_v2::functions()->trace("check_time_against_period()"); + functions_logger->trace("check_time_against_period()"); // If no period was specified, assume the time is good. if (!tperiod) @@ -765,8 +765,8 @@ bool check_time_against_period(time_t test_time, timeperiod* tperiod) { time_t next_valid_time{(time_t)-1}; tperiod->get_next_valid_time_per_timeperiod(test_time, &next_valid_time, false); - log_v2::functions()->trace("check_time_against_period {} ret={}", - tperiod->get_name(), next_valid_time == test_time); + functions_logger->trace("check_time_against_period {} ret={}", + tperiod->get_name(), next_valid_time == test_time); return next_valid_time == test_time; } @@ -784,7 +784,7 @@ bool check_time_against_period_for_notif(time_t test_time, timeperiod* tperiod) { engine_logger(dbg_functions, basic) << "check_time_against_period_for_notif()"; - log_v2::functions()->trace("check_time_against_period_for_notif()"); + functions_logger->trace("check_time_against_period_for_notif()"); // If no period was specified, assume the time is good. if (!tperiod) @@ -810,7 +810,7 @@ void timeperiod::get_next_invalid_time_per_timeperiod(time_t preferred_time, bool notif_timeperiod) { engine_logger(dbg_functions, basic) << "get_next_invalid_time_per_timeperiod()"; - log_v2::functions()->trace("get_next_invalid_time_per_timeperiod()"); + functions_logger->trace("get_next_invalid_time_per_timeperiod()"); // If no time can be found, the original preferred time will be set // in invalid_time at the end of the loop. @@ -995,7 +995,7 @@ void timeperiod::get_next_valid_time_per_timeperiod(time_t preferred_time, time_t* valid_time, bool notif_timeperiod) { engine_logger(dbg_functions, basic) << "get_next_valid_time_per_timeperiod()"; - log_v2::functions()->trace("get_next_valid_time_per_timeperiod()"); + functions_logger->trace("get_next_valid_time_per_timeperiod()"); // If no time can be found, the original preferred time will be set // in valid_time at the end of the loop. @@ -1106,9 +1106,8 @@ void timeperiod::get_next_valid_time_per_timeperiod(time_t preferred_time, // Else use the calculated time. else *valid_time = earliest_time; - log_v2::functions()->trace( - "get_next_valid_time_per_timeperiod {} valid_time={}", _name, - *valid_time); + functions_logger->trace("get_next_valid_time_per_timeperiod {} valid_time={}", + _name, *valid_time); } /** @@ -1123,7 +1122,7 @@ void get_next_valid_time(time_t pref_time, time_t* valid_time, timeperiod* tperiod) { engine_logger(dbg_functions, basic) << "get_next_valid_time()"; - log_v2::functions()->trace("get_next_valid_time()"); + functions_logger->trace("get_next_valid_time()"); // Preferred time must be now or in the future. time_t preferred_time(std::max(pref_time, time(NULL))); @@ -1158,7 +1157,7 @@ void timeperiod::resolve(int& w __attribute__((unused)), int& e) { engine_logger(log_verification_error, basic) << "Error: The name of time period '" << _name << "' contains one or more illegal characters."; - log_v2::config()->error( + config_logger->error( "Error: The name of time period '{}' contains one or more illegal " "characters.", _name); @@ -1177,7 +1176,7 @@ void timeperiod::resolve(int& w __attribute__((unused)), int& e) { << "Error: Excluded time period '" << it->first << "' specified in timeperiod '" << _name << "' is not defined anywhere!"; - log_v2::config()->error( + config_logger->error( "Error: Excluded time period '{}' specified in timeperiod '{}' is " "not defined anywhere!", it->first, _name); diff --git a/engine/src/timerange.cc b/engine/src/timerange.cc index 4f214c72c9c..a0e069420af 100644 --- a/engine/src/timerange.cc +++ b/engine/src/timerange.cc @@ -1,24 +1,24 @@ /** -* Copyright 2022 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/engine/timerange.hh" #include "com/centreon/engine/exceptions/error.hh" -#include "com/centreon/engine/log_v2.hh" +#include "com/centreon/engine/globals.hh" #include "com/centreon/engine/logging/logger.hh" using namespace com::centreon::engine; @@ -29,16 +29,15 @@ timerange::timerange(uint64_t start, uint64_t end) { if (start > 86400) { engine_logger(log_config_error, basic) << "Error: Start time " << start << " is not valid for timeperiod"; - log_v2::config()->error("Error: Start time {} is not valid for timeperiod", - start); + config_logger->error("Error: Start time {} is not valid for timeperiod", + start); throw engine_error() << "Could not create timerange " << "start'" << start << "' end '" << end << "'"; } if (end > 86400) { engine_logger(log_config_error, basic) << "Error: End time " << end << " is not value for timeperiod"; - log_v2::config()->error("Error: End time {} is not value for timeperiod", - end); + config_logger->error("Error: End time {} is not value for timeperiod", end); throw engine_error() << "Could not create timerange " << "start'" << start << "' end '" << end << "'"; } @@ -84,4 +83,4 @@ std::ostream& operator<<(std::ostream& os, timerange_list const& obj) { return os; } -} +} // namespace com::centreon::engine diff --git a/engine/src/utils.cc b/engine/src/utils.cc index 7350d00719e..888248b91eb 100644 --- a/engine/src/utils.cc +++ b/engine/src/utils.cc @@ -1,23 +1,23 @@ /** -* Copyright 1999-2009 Ethan Galstad -* Copyright 2009-2012 Icinga Development Team (http://www.icinga.org) -* Copyright 2011-2014,2016 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 1999-2009 Ethan Galstad + * Copyright 2009-2012 Icinga Development Team (http://www.icinga.org) + * Copyright 2011-2014,2016 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/utils.hh" @@ -38,7 +38,6 @@ #include "com/centreon/engine/downtimes/downtime_manager.hh" #include "com/centreon/engine/events/loop.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/macros.hh" #include "com/centreon/engine/nebmods.hh" @@ -63,7 +62,7 @@ int my_system_r(nagios_macros* mac, std::string& output, unsigned int max_output_length) { engine_logger(dbg_functions, basic) << "my_system_r()"; - log_v2::functions()->trace("my_system_r()"); + functions_logger->trace("my_system_r()"); // initialize return variables. *early_timeout = false; @@ -75,7 +74,7 @@ int my_system_r(nagios_macros* mac, } engine_logger(dbg_commands, more) << "Running command '" << cmd << "'..."; - SPDLOG_LOGGER_DEBUG(log_v2::commands(), "Running command '{}'...", cmd); + SPDLOG_LOGGER_DEBUG(commands_logger, "Running command '{}'...", cmd); timeval start_time = timeval(); timeval end_time = timeval(); @@ -109,7 +108,7 @@ int my_system_r(nagios_macros* mac, << " sec, early timeout=" << *early_timeout << ", result=" << result << ", output=" << output; SPDLOG_LOGGER_DEBUG( - log_v2::commands(), + commands_logger, "Execution time={:.3f} sec, early timeout={}, result={}, output={}", *exectime, *early_timeout, result, output); @@ -144,7 +143,7 @@ int get_raw_command_line_r(nagios_macros* mac, int escaped = false; engine_logger(dbg_functions, basic) << "get_raw_command_line_r()"; - log_v2::functions()->trace("get_raw_command_line_r()"); + functions_logger->trace("get_raw_command_line_r()"); /* clear the argv macros */ clear_argv_macros_r(mac); @@ -156,7 +155,7 @@ int get_raw_command_line_r(nagios_macros* mac, engine_logger(dbg_commands | dbg_checks | dbg_macros, most) << "Raw Command Input: " << cmd_ptr->get_command_line(); - SPDLOG_LOGGER_DEBUG(log_v2::commands(), "Raw Command Input: {}", + SPDLOG_LOGGER_DEBUG(commands_logger, "Raw Command Input: {}", cmd_ptr->get_command_line()); /* get the full command line */ @@ -209,7 +208,7 @@ int get_raw_command_line_r(nagios_macros* mac, engine_logger(dbg_commands | dbg_checks | dbg_macros, most) << "Expanded Command Output: " << full_command; - SPDLOG_LOGGER_DEBUG(log_v2::commands(), "Expanded Command Output: {}", + SPDLOG_LOGGER_DEBUG(commands_logger, "Expanded Command Output: {}", full_command); return OK; diff --git a/engine/src/xpddefault.cc b/engine/src/xpddefault.cc index f67b8a9d592..00cf6912ac6 100644 --- a/engine/src/xpddefault.cc +++ b/engine/src/xpddefault.cc @@ -1,22 +1,22 @@ /** -* Copyright 2000-2008 Ethan Galstad -* Copyright 2011-2013 Merethis -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2000-2008 Ethan Galstad + * Copyright 2011-2013 Merethis + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/xpddefault.hh" #include @@ -26,7 +26,6 @@ #include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/globals.hh" #include "com/centreon/engine/host.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/macros.hh" #include "com/centreon/engine/service.hh" @@ -99,7 +98,7 @@ int xpddefault_initialize_performance_data() { << "Warning: Host performance command '" << temp_command_name << "' was not found - host performance data will not " "be processed!"; - log_v2::runtime()->warn( + runtime_logger->warn( "Warning: Host performance command '{}' was not found - host " "performance data will not " "be processed!", @@ -125,7 +124,7 @@ int xpddefault_initialize_performance_data() { << "Warning: Service performance command '" << temp_command_name << "' was not found - service performance data will not " "be processed!"; - log_v2::runtime()->warn( + runtime_logger->warn( "Warning: Service performance command '{}' was not found - service " "performance data will not " "be processed!", @@ -152,7 +151,7 @@ int xpddefault_initialize_performance_data() { << temp_command_name << "' was not found - host performance " "data file will not be processed!"; - log_v2::runtime()->warn( + runtime_logger->warn( "Warning: Host performance file processing command '{}' was not " "found - host performance " "data file will not be processed!", @@ -180,7 +179,7 @@ int xpddefault_initialize_performance_data() { << temp_command_name << "' was not found - service performance " "data file will not be processed!"; - log_v2::runtime()->warn( + runtime_logger->warn( "Warning: Service performance file processing command '{}' was not " "found - service performance " "data file will not be processed!", @@ -299,7 +298,7 @@ int xpddefault_run_service_performance_data_command( engine_logger(dbg_functions, basic) << "run_service_performance_data_command()"; - log_v2::functions()->trace("run_service_performance_data_command()"); + functions_logger->trace("run_service_performance_data_command()"); if (svc == nullptr) return ERROR; @@ -317,8 +316,8 @@ int xpddefault_run_service_performance_data_command( engine_logger(dbg_perfdata, most) << "Raw service performance data command line: " << raw_command_line; - log_v2::commands()->debug("Raw service performance data command line: {}", - raw_command_line); + commands_logger->debug("Raw service performance data command line: {}", + raw_command_line); // process any macros in the raw command line. process_macros_r(mac, raw_command_line, processed_command_line, @@ -329,9 +328,8 @@ int xpddefault_run_service_performance_data_command( engine_logger(dbg_perfdata, most) << "Processed service performance data " "command line: " << processed_command_line; - log_v2::commands()->debug( - "Processed service performance data command line: {}", - processed_command_line); + commands_logger->debug("Processed service performance data command line: {}", + processed_command_line); // run the command. try { @@ -342,7 +340,7 @@ int xpddefault_run_service_performance_data_command( engine_logger(log_runtime_error, basic) << "Error: can't execute service performance data command line '" << processed_command_line << "' : " << e.what(); - log_v2::runtime()->error( + runtime_logger->error( "Error: can't execute service performance data command line '{}' : {}", processed_command_line, e.what()); } @@ -354,7 +352,7 @@ int xpddefault_run_service_performance_data_command( << processed_command_line << "' for service '" << svc->description() << "' on host '" << svc->get_hostname() << "' timed out after " << config->perfdata_timeout() << " seconds"; - log_v2::runtime()->warn( + runtime_logger->warn( "Warning: Service performance data command '{}' for service '{}' on host " "'{}' timed out after {} seconds", processed_command_line, svc->description(), svc->get_hostname(), @@ -374,7 +372,7 @@ int xpddefault_run_host_performance_data_command(nagios_macros* mac, int macro_options(STRIP_ILLEGAL_MACRO_CHARS | ESCAPE_MACRO_CHARS); engine_logger(dbg_functions, basic) << "run_host_performance_data_command()"; - log_v2::functions()->trace("run_host_performance_data_command()"); + functions_logger->trace("run_host_performance_data_command()"); if (hst == nullptr) return ERROR; @@ -392,8 +390,8 @@ int xpddefault_run_host_performance_data_command(nagios_macros* mac, engine_logger(dbg_perfdata, most) << "Raw host performance data command line: " << raw_command_line; - log_v2::commands()->info("Raw host performance data command line: {}", - raw_command_line); + commands_logger->info("Raw host performance data command line: {}", + raw_command_line); // process any macros in the raw command line. process_macros_r(mac, raw_command_line, processed_command_line, @@ -402,8 +400,8 @@ int xpddefault_run_host_performance_data_command(nagios_macros* mac, engine_logger(dbg_perfdata, most) << "Processed host performance data command line: " << processed_command_line; - log_v2::commands()->info("Processed host performance data command line: {}", - processed_command_line); + commands_logger->info("Processed host performance data command line: {}", + processed_command_line); // run the command. try { @@ -414,7 +412,7 @@ int xpddefault_run_host_performance_data_command(nagios_macros* mac, engine_logger(log_runtime_error, basic) << "Error: can't execute host performance data command line '" << processed_command_line << "' : " << e.what(); - log_v2::runtime()->error( + runtime_logger->error( "Error: can't execute host performance data command line '{}' : {}", processed_command_line, e.what()); } @@ -428,7 +426,7 @@ int xpddefault_run_host_performance_data_command(nagios_macros* mac, << "Warning: Host performance data command '" << processed_command_line << "' for host '" << hst->name() << "' timed out after " << config->perfdata_timeout() << " seconds"; - log_v2::runtime()->warn( + runtime_logger->warn( "Warning: Host performance data command '{}' for host '{}' timed out " "after {} seconds", processed_command_line, hst->name(), config->perfdata_timeout()); @@ -460,7 +458,7 @@ int xpddefault_open_host_perfdata_file() { << "Warning: File '" << xpddefault_host_perfdata_fp << "' could not be opened - host performance data will not " "be written to file!"; - log_v2::runtime()->warn( + runtime_logger->warn( "Warning: File '{}' could not be opened - host performance data will " "not " "be written to file!", @@ -496,7 +494,7 @@ int xpddefault_open_service_perfdata_file() { << "Warning: File '" << config->service_perfdata_file() << "' could not be opened - service performance data will not " "be written to file!"; - log_v2::runtime()->warn( + runtime_logger->warn( "Warning: File '{}' could not be opened - service performance data " "will not " "be written to file!", @@ -574,7 +572,7 @@ int xpddefault_update_service_performance_data_file( engine_logger(dbg_functions, basic) << "update_service_performance_data_file()"; - log_v2::functions()->trace("update_service_performance_data_file()"); + functions_logger->trace("update_service_performance_data_file()"); if (svc == nullptr) return ERROR; @@ -589,8 +587,8 @@ int xpddefault_update_service_performance_data_file( engine_logger(dbg_perfdata, most) << "Raw service performance data file output: " << raw_output; - log_v2::commands()->info("Raw service performance data file output: {}", - raw_output); + commands_logger->info("Raw service performance data file output: {}", + raw_output); // process any macros in the raw output line. process_macros_r(mac, raw_output, processed_output, 0); @@ -599,8 +597,8 @@ int xpddefault_update_service_performance_data_file( engine_logger(dbg_perfdata, most) << "Processed service performance data file output: " << processed_output; - log_v2::commands()->info("Processed service performance data file output: {}", - processed_output); + commands_logger->info("Processed service performance data file output: {}", + processed_output); // lock, write to and unlock host performance data file. pthread_mutex_lock(&xpddefault_service_perfdata_fp_lock); @@ -620,7 +618,7 @@ int xpddefault_update_host_performance_data_file(nagios_macros* mac, int result(OK); engine_logger(dbg_functions, basic) << "update_host_performance_data_file()"; - log_v2::functions()->trace("update_host_performance_data_file()"); + functions_logger->trace("update_host_performance_data_file()"); if (hst == nullptr) return ERROR; @@ -635,7 +633,7 @@ int xpddefault_update_host_performance_data_file(nagios_macros* mac, engine_logger(dbg_perfdata, most) << "Raw host performance file output: " << raw_output; - log_v2::commands()->info("Raw host performance file output: {}", raw_output); + commands_logger->info("Raw host performance file output: {}", raw_output); // process any macros in the raw output. process_macros_r(mac, raw_output, processed_output, 0); @@ -644,8 +642,8 @@ int xpddefault_update_host_performance_data_file(nagios_macros* mac, engine_logger(dbg_perfdata, most) << "Processed host performance data file output: " << processed_output; - log_v2::commands()->info("Processed host performance data file output: {}", - processed_output); + commands_logger->info("Processed host performance data file output: {}", + processed_output); // lock, write to and unlock host performance data file. pthread_mutex_lock(&xpddefault_host_perfdata_fp_lock); @@ -668,7 +666,7 @@ int xpddefault_process_host_perfdata_file() { nagios_macros* mac(get_global_macros()); engine_logger(dbg_functions, basic) << "process_host_perfdata_file()"; - log_v2::functions()->trace("process_host_perfdata_file()"); + functions_logger->trace("process_host_perfdata_file()"); // we don't have a command. if (config->host_perfdata_file_processing_command().empty()) @@ -687,7 +685,7 @@ int xpddefault_process_host_perfdata_file() { engine_logger(dbg_perfdata, most) << "Raw host performance data file processing command line: " << raw_command_line; - log_v2::commands()->info( + commands_logger->info( "Raw host performance data file processing command line: {}", raw_command_line); @@ -703,7 +701,7 @@ int xpddefault_process_host_perfdata_file() { << "Processed host performance data file processing command " "line: " << processed_command_line; - log_v2::commands()->info( + commands_logger->info( "Processed host performance data file processing command line: {}", processed_command_line); @@ -721,7 +719,7 @@ int xpddefault_process_host_perfdata_file() { << "Error: can't execute host performance data file processing command " "line '" << processed_command_line << "' : " << e.what(); - log_v2::runtime()->error( + runtime_logger->error( "Error: can't execute host performance data file processing command " "line '{}' : {}", processed_command_line, e.what()); @@ -738,7 +736,7 @@ int xpddefault_process_host_perfdata_file() { << "Warning: Host performance data file processing command '" << processed_command_line << "' timed out after " << config->perfdata_timeout() << " seconds"; - log_v2::runtime()->warn( + runtime_logger->warn( "Warning: Host performance data file processing command '{}' timed out " "after {} seconds", processed_command_line, config->perfdata_timeout()); @@ -756,7 +754,7 @@ int xpddefault_process_service_perfdata_file() { nagios_macros* mac(get_global_macros()); engine_logger(dbg_functions, basic) << "process_service_perfdata_file()"; - log_v2::functions()->trace("process_service_perfdata_file()"); + functions_logger->trace("process_service_perfdata_file()"); // we don't have a command. if (config->service_perfdata_file_processing_command().empty()) @@ -776,7 +774,7 @@ int xpddefault_process_service_perfdata_file() { << "Raw service performance data file processing " "command line: " << raw_command_line; - log_v2::commands()->info( + commands_logger->info( "Raw service performance data file processing command line: {}", raw_command_line); @@ -792,7 +790,7 @@ int xpddefault_process_service_perfdata_file() { << "Processed service performance data file processing " "command line: " << processed_command_line; - log_v2::commands()->info( + commands_logger->info( "Processed service performance data file processing command line: {}", processed_command_line); @@ -810,7 +808,7 @@ int xpddefault_process_service_perfdata_file() { << "Error: can't execute service performance data file processing " "command line '" << processed_command_line << "' : " << e.what(); - log_v2::runtime()->error( + runtime_logger->error( "Error: can't execute service performance data file processing " "command line '{}' : {}", processed_command_line, e.what()); @@ -828,7 +826,7 @@ int xpddefault_process_service_perfdata_file() { << "Warning: Service performance data file processing command '" << processed_command_line << "' timed out after " << config->perfdata_timeout() << " seconds"; - log_v2::runtime()->warn( + runtime_logger->warn( "Warning: Service performance data file processing command '{}' timed " "out after {} seconds", processed_command_line, config->perfdata_timeout()); diff --git a/engine/src/xsddefault.cc b/engine/src/xsddefault.cc index 1d92f37c585..9ae791a047d 100644 --- a/engine/src/xsddefault.cc +++ b/engine/src/xsddefault.cc @@ -1,24 +1,24 @@ /** -* Copyright 2000-2009 Ethan Galstad -* Copyright 2009 Nagios Core Development Team and Community -*Contributors -* Copyright 2011-2013,2015 Merethis -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2000-2009 Ethan Galstad + * Copyright 2009 Nagios Core Development Team and Community + *Contributors + * Copyright 2011-2013,2015 Merethis + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/xsddefault.hh" #include @@ -32,7 +32,6 @@ #include "com/centreon/engine/downtimes/downtime.hh" #include "com/centreon/engine/downtimes/downtime_manager.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/macros.hh" #include "com/centreon/engine/statusdata.hh" @@ -63,9 +62,8 @@ int xsddefault_initialize_status_data() { engine_logger(engine::logging::log_runtime_error, engine::logging::basic) << "Error: Unable to open status data file '" << config->status_file() << "': " << strerror(errno); - log_v2::runtime()->error( - "Error: Unable to open status data file '{}': {}", - config->status_file(), strerror(errno)); + runtime_logger->error("Error: Unable to open status data file '{}': {}", + config->status_file(), strerror(errno)); return ERROR; } set_cloexec(xsddefault_status_log_fd); @@ -105,7 +103,7 @@ int xsddefault_save_status_data() { engine_logger(engine::logging::dbg_functions, engine::logging::basic) << "save_status_data()"; - log_v2::functions()->trace("save_status_data()"); + functions_logger->trace("save_status_data()"); // get number of items in the command buffer if (config->check_external_commands()) { @@ -733,9 +731,8 @@ int xsddefault_save_status_data() { engine_logger(engine::logging::log_runtime_error, engine::logging::basic) << "Error: Unable to update status data file '" << config->status_file() << "': " << msg; - log_v2::runtime()->error( - "Error: Unable to update status data file '{}': {}", - config->status_file(), msg); + runtime_logger->error("Error: Unable to update status data file '{}': {}", + config->status_file(), msg); return ERROR; } @@ -750,9 +747,8 @@ int xsddefault_save_status_data() { engine_logger(engine::logging::log_runtime_error, engine::logging::basic) << "Error: Unable to update status data file '" << config->status_file() << "': " << msg; - log_v2::runtime()->error( - "Error: Unable to update status data file '{}': {}", - config->status_file(), msg); + runtime_logger->error("Error: Unable to update status data file '{}': {}", + config->status_file(), msg); return ERROR; } data_ptr += wb; diff --git a/engine/tests/CMakeLists.txt b/engine/tests/CMakeLists.txt index 7d11b056cd8..45fd6113cda 100755 --- a/engine/tests/CMakeLists.txt +++ b/engine/tests/CMakeLists.txt @@ -21,7 +21,8 @@ if(WITH_TESTING) # Tests directory. Add root inclusion direction. set(MODULE_DIR "${PROJECT_SOURCE_DIR}/modules/external_commands") set(INC_DIR "${MODULE_DIR}/inc/com/centreon/engine/modules/external_commands") - include_directories(${PROJECT_SOURCE_DIR} ${MODULE_DIR}/inc) + include_directories(${CMAKE_SOURCE_DIR} ${CMAKE_SOURCE_DIR}/common/inc + ${PROJECT_SOURCE_DIR} ${MODULE_DIR}/inc) # Set directory. set(TESTS_DIR "${PROJECT_SOURCE_DIR}/tests") @@ -36,8 +37,12 @@ if(WITH_TESTING) cerpc centreon_common spdlog::spdlog - gRPC::gpr gRPC::grpc gRPC::grpc++ gRPC::grpc++_alts - crypto ssl + gRPC::gpr + gRPC::grpc + gRPC::grpc++ + gRPC::grpc++_alts + crypto + ssl z dl pthread) @@ -167,20 +172,27 @@ if(WITH_TESTING) endif() target_link_libraries( - ut_engine PRIVATE - -L${PROTOBUF_LIB_DIR} - ${ENGINERPC} - ut_engine_utils - cce_core - enginelog - pthread - ${GCOV} - GTest::gtest GTest::gtest_main GTest::gmock GTest::gmock_main - gRPC::gpr gRPC::grpc gRPC::grpc++ gRPC::grpc++_alts - crypto ssl - z - fmt::fmt - ryml::ryml - stdc++fs - dl) + ut_engine + PRIVATE -L${PROTOBUF_LIB_DIR} + ${ENGINERPC} + ut_engine_utils + cce_core + log_v2 + pthread + ${GCOV} + GTest::gtest + GTest::gtest_main + GTest::gmock + GTest::gmock_main + gRPC::gpr + gRPC::grpc + gRPC::grpc++ + gRPC::grpc++_alts + crypto + ssl + z + fmt::fmt + ryml::ryml + stdc++fs + dl) endif() diff --git a/engine/tests/checks/anomalydetection.cc b/engine/tests/checks/anomalydetection.cc index d26a29349f7..0d55cd2e373 100644 --- a/engine/tests/checks/anomalydetection.cc +++ b/engine/tests/checks/anomalydetection.cc @@ -37,7 +37,7 @@ #include "com/centreon/engine/configuration/host.hh" #include "com/centreon/engine/configuration/service.hh" #include "com/centreon/engine/exceptions/error.hh" -#include "com/centreon/engine/log_v2.hh" +#include "com/centreon/engine/globals.hh" #include "helper.hh" using namespace com::centreon; @@ -50,8 +50,8 @@ class AnomalydetectionCheck : public TestEngine { void SetUp() override { init_config_state(); - log_v2::checks()->set_level(spdlog::level::trace); - log_v2::commands()->set_level(spdlog::level::trace); + checks_logger->set_level(spdlog::level::trace); + commands_logger->set_level(spdlog::level::trace); configuration::applier::contact ct_aply; configuration::contact ctct{new_configuration_contact("admin", true)}; diff --git a/engine/tests/commands/simple-command.cc b/engine/tests/commands/simple-command.cc index ebca43df975..a1bb5aff5e1 100644 --- a/engine/tests/commands/simple-command.cc +++ b/engine/tests/commands/simple-command.cc @@ -18,8 +18,8 @@ */ #include -#include -#include "com/centreon/engine/log_v2.hh" +#include "com/centreon/engine/globals.hh" +#include "com/centreon/engine/macros.hh" #include "../timeperiod/utils.hh" #include "com/centreon/engine/commands/raw.hh" @@ -29,6 +29,8 @@ using namespace com::centreon; using namespace com::centreon::engine; using namespace com::centreon::engine::commands; +using com::centreon::common::log_v2::log_v2; + void CreateFile(std::string const& filename, std::string const& content) { std::ofstream oss(filename); oss << content; @@ -149,7 +151,7 @@ TEST_F(SimpleCommand, LongCommandAsync) { } TEST_F(SimpleCommand, TooRecentDoubleCommand) { - log_v2::commands()->set_level(spdlog::level::trace); + commands_logger->set_level(spdlog::level::trace); CreateFile("/tmp/TooRecentDoubleCommand.sh", "echo -n tutu | tee -a /tmp/TooRecentDoubleCommand;"); @@ -191,7 +193,7 @@ TEST_F(SimpleCommand, TooRecentDoubleCommand) { } TEST_F(SimpleCommand, SufficientOldDoubleCommand) { - log_v2::commands()->set_level(spdlog::level::trace); + commands_logger->set_level(spdlog::level::trace); CreateFile("/tmp/TooRecentDoubleCommand.sh", "echo -n tutu | tee -a /tmp/TooRecentDoubleCommand;"); diff --git a/engine/tests/configuration/whitelist-test.cc b/engine/tests/configuration/whitelist-test.cc index 22d20a46d7b..93dcad4b111 100644 --- a/engine/tests/configuration/whitelist-test.cc +++ b/engine/tests/configuration/whitelist-test.cc @@ -22,7 +22,8 @@ #include -#include "com/centreon/engine/log_v2.hh" +#include "com/centreon/engine/globals.hh" +#include "common/log_v2/config.hh" #include "com/centreon/engine/configuration/whitelist.hh" @@ -41,13 +42,11 @@ class whitelist_test : public ::testing::Test { public: static void SetUpTestSuite() { - _old_log_level = log_v2::config()->level(); - log_v2::config()->set_level(spdlog::level::trace); + _old_log_level = config_logger->level(); + config_logger->set_level(spdlog::level::trace); } - static void TearDownTestSuite() { - log_v2::config()->set_level(_old_log_level); - } + static void TearDownTestSuite() { config_logger->set_level(_old_log_level); } }; spdlog::level::level_enum whitelist_test::_old_log_level; diff --git a/engine/tests/helper.cc b/engine/tests/helper.cc index 87ccbce4d21..6a9782c5bda 100644 --- a/engine/tests/helper.cc +++ b/engine/tests/helper.cc @@ -19,12 +19,17 @@ #include "helper.hh" -#include -#include -#include -#include "com/centreon/engine/log_v2.hh" +#include "com/centreon/engine/checks/checker.hh" +#include "com/centreon/engine/configuration/applier/logging.hh" +#include "com/centreon/engine/configuration/applier/state.hh" +#include "com/centreon/engine/globals.hh" + +#include "common/log_v2/config.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::engine; +using com::centreon::common::log_v2::log_v2; +using log_v2_config = com::centreon::common::log_v2::config; extern configuration::state* config; @@ -35,9 +40,14 @@ void init_config_state(void) { config->log_file_line(true); config->log_file(""); + log_v2_config log_conf( + "engine-tests", log_v2_config::logger_type::LOGGER_STDOUT, + config->log_flush_period(), config->log_pid(), config->log_file_line()); + + log_v2::instance().apply(log_conf); + // Hack to instanciate the logger. configuration::applier::logging::instance().apply(*config); - log_v2::instance()->apply(*config); checks::checker::init(true); } diff --git a/engine/tests/main.cc b/engine/tests/main.cc index b19121fb531..e6eaa0303d1 100644 --- a/engine/tests/main.cc +++ b/engine/tests/main.cc @@ -20,11 +20,13 @@ #include #include "com/centreon/clib.hh" #include "com/centreon/common/pool.hh" -#include "com/centreon/engine/log_v2.hh" +#include "com/centreon/engine/globals.hh" std::shared_ptr g_io_context( std::make_shared()); +using com::centreon::common::log_v2::log_v2; + class CentreonEngineEnvironment : public testing::Environment { public: void SetUp() override { @@ -50,9 +52,9 @@ int main(int argc, char* argv[]) { // Set specific environment. testing::AddGlobalTestEnvironment(new CentreonEngineEnvironment()); - com::centreon::engine::log_v2::load(g_io_context); - com::centreon::common::pool::load(g_io_context, - com::centreon::engine::log_v2::runtime()); + com::centreon::common::log_v2::log_v2::load("engine-tests"); + init_loggers(); + com::centreon::common::pool::load(g_io_context, runtime_logger); com::centreon::common::pool::set_pool_size(0); // Run all tests. int ret = RUN_ALL_TESTS(); diff --git a/engine/tests/notifications/host_normal_notification.cc b/engine/tests/notifications/host_normal_notification.cc index 77403b8f7b2..2d75c1ffbc7 100644 --- a/engine/tests/notifications/host_normal_notification.cc +++ b/engine/tests/notifications/host_normal_notification.cc @@ -38,7 +38,7 @@ #include "com/centreon/engine/configuration/state.hh" #include "com/centreon/engine/downtimes/downtime_manager.hh" #include "com/centreon/engine/exceptions/error.hh" -#include "com/centreon/engine/log_v2.hh" +#include "com/centreon/engine/globals.hh" #include "com/centreon/engine/retention/dump.hh" #include "com/centreon/engine/timezone_manager.hh" @@ -54,7 +54,7 @@ class HostNotification : public TestEngine { void SetUp() override { init_config_state(); - log_v2::events()->set_level(spdlog::level::off); + events_logger->set_level(spdlog::level::off); configuration::applier::contact ct_aply; configuration::contact ctct{new_configuration_contact("admin", true)}; diff --git a/engine/tests/notifications/service_downtime_notification_test.cc b/engine/tests/notifications/service_downtime_notification_test.cc index 44137d526aa..f0bd0266fd4 100644 --- a/engine/tests/notifications/service_downtime_notification_test.cc +++ b/engine/tests/notifications/service_downtime_notification_test.cc @@ -38,7 +38,6 @@ #include "com/centreon/engine/configuration/host.hh" #include "com/centreon/engine/configuration/service.hh" #include "com/centreon/engine/exceptions/error.hh" -#include "com/centreon/engine/log_v2.hh" #include "com/centreon/engine/serviceescalation.hh" #include "helper.hh" diff --git a/init.sh b/init.sh index a9b9897eb17..e78e5d7a17e 100644 --- a/init.sh +++ b/init.sh @@ -8,15 +8,11 @@ if (( sourced == 0 )) ; then echo "Please execute this script with:" echo ". init.sh" - exit 1 -fi - # To be sure the script has not already been launched. -if [[ "$PATH" =~ "vcpkg" ]] ; then +elif [[ "$PATH" =~ "vcpkg" ]] ; then echo "Already initialized" - exit 2 +else + # The main purpose. + export VCPKG_ROOT=$PWD/vcpkg + export PATH=$VCPKG_ROOT:$PATH fi - -# The main purpose. -export VCPKG_ROOT=$PWD/vcpkg -export PATH=$VCPKG_ROOT:$PATH diff --git a/tests/bench.py b/tests/bench.py old mode 100644 new mode 100755 index 7ddf29be922..5bf34931c32 --- a/tests/bench.py +++ b/tests/bench.py @@ -24,6 +24,7 @@ import os import re from unqlite import UnQLite +import sys # With the following line, matplotlib can interact with Tkinter matplotlib.use('TkAgg') @@ -122,8 +123,9 @@ def list_metrics(collection_name: str, origin: str): metrics = [] if len(selected) > 0: metrics = list(selected[0].keys()) - for m in ["cpu", "nb_core", "memory_size", "branch", "origin", "commit", "t", "__id"]: - metrics.remove(m) + for m in ["cpu", "nb_core", "memory_size", "branch", "origin", "commit", "t", "__id", "date_commit"]: + if m in metrics: + metrics.remove(m) return metrics @@ -150,22 +152,24 @@ def __init__(self, tests_tree): for kk in tests: menu_collection.add_radiobutton(label=tests_tree[k][kk], variable=self.collection, value=tests_tree[k][kk], command=self.collection_chosen) menu_tests.add_cascade(label=k, menu=menu_collection) + menu_tests.add_separator() + menu_tests.add_command(label="Quit", command=self.exit) self.config(menu=menu) origins_label = tk.Label(self, text = "Origins") origins_label.grid(column=0, row=0) - self.origins_list = tk.Listbox(self, selectmode="SINGLE") + self.origins_list = tk.Listbox(self, selectmode="SINGLE", exportselection=False) self.origins_list.grid(column=0, row=1, sticky="ns") self.origins_list.bind('<>', self.origins_list_changed) confs_label = tk.Label(self, text = "Configurations") confs_label.grid(column=0, row=2) - self.confs_list = tk.Listbox(self, selectmode="SINGLE") + self.confs_list = tk.Listbox(self, selectmode="SINGLE", exportselection=False) self.confs_list.grid(column=0, row=3, sticky="ns") self.confs_list.bind('<>', self.confs_list_changed) metrics_label = tk.Label(self, text = "Metrics") metrics_label.grid(column=0, row=4) - self.metrics_list = tk.Listbox(self, selectmode="SINGLE") + self.metrics_list = tk.Listbox(self, selectmode="SINGLE", exportselection=False) self.metrics_list.grid(column=0, row=5, sticky="ns") self.metrics_list.bind('<>', self.metrics_list_changed) @@ -188,6 +192,8 @@ def __init__(self, tests_tree): figure_canvas.get_tk_widget().grid(column=1, row=0, rowspan=6, sticky="nesw") + self.protocol('WM_DELETE_WINDOW', self.exit) + def collection_chosen(self): self.origins_list.delete(0, self.origins_list.size()) origins = list(list_origin_branch(self.collection.get())) @@ -214,6 +220,10 @@ def origins_list_changed(self, evt): for i, m in enumerate(metrics): self.metrics_list.insert(i, m) + def exit(self): + plt.close('all') + sys.exit() + def confs_list_changed(self, evt): # Note here that Tkinter passes an event object to onselect() w = evt.widget diff --git a/tests/broker-engine/bench.robot b/tests/broker-engine/bench.robot index e7a9e727773..14d7f53d1b6 100644 --- a/tests/broker-engine/bench.robot +++ b/tests/broker-engine/bench.robot @@ -22,6 +22,7 @@ BENCH_${nb_checks}STATUS Ctn Clear Db logs Ctn Clear Db comments Ctn Clear Db data_bin + Ctn Clear Logs Ctn Config Engine ${1} ${50} ${20} # We want all the services to be passive to avoid parasite checks during our test. Ctn Set Services Passive ${0} service_.* @@ -91,6 +92,7 @@ BENCH_${nb_checks}STATUS_TRACES Ctn Clear Db logs Ctn Clear Db comments Ctn Clear Db data_bin + Ctn Clear Logs Ctn Config Engine ${1} ${50} ${20} # We want all the services to be passive to avoid parasite checks during our test. Ctn Set Services Passive ${0} service_.* @@ -163,6 +165,7 @@ BENCH_1000STATUS_100${suffixe} Ctn Clear Db logs Ctn Clear Db comments Ctn Clear Db data_bin + Ctn Clear Logs Ctn Config Engine ${100} ${100} ${20} Ctn Config Broker module ${100} Ctn Config Broker central @@ -177,7 +180,7 @@ BENCH_1000STATUS_100${suffixe} Ctn Config BBDO3 ${100} Ctn Config Broker Sql Output central unified_sql Ctn Broker Config Output Set central central-broker-unified-sql connections_count ${nb_conn} - ${start} Get Current Date + ${start} Ctn Get Round Current Date Ctn Start Broker Ctn Start engine ${connected} Ctn Wait For Connections 5669 100 @@ -212,7 +215,7 @@ BENCH_1000STATUS_100${suffixe} ${diff_broker} Ctn Diff Process Stat ${broker_stat_after} ${broker_stat_before} ${diff_engine} Ctn Diff Process Stat ${engine_stat_after} ${engine_stat_before} - ${content} Create List pb service (100, 2000) status 1 type 1 check result output: <> + ${content} Create List pb service status of (100, 2000) - state 1 - type 1 check result output: <> ${result} Ctn Find In Log With Timeout With Line ${centralLog} ${start_check} ${content} 240 Should Be True ${result[0]} No check check result received. ${date_last_check_received} Ctn Extract Date From Log ${result[1][0]} @@ -265,6 +268,7 @@ BENCH_${nb_checks}_SERVICE_STATUS_WITHOUT_SQL Ctn Clear Db logs Ctn Clear Db comments Ctn Clear Db data_bin + Ctn Clear Logs Ctn Config Engine ${1} ${50} ${20} # We want all the services to be passive to avoid parasite checks during our test. Ctn Set Services Passive ${0} service_.* @@ -339,6 +343,7 @@ BENCH_${nb_checks}_SERVICE_STATUS_TRACES_WITHOUT_SQL Ctn Clear Db logs Ctn Clear Db comments Ctn Clear Db data_bin + Ctn Clear Logs Ctn Config Engine ${1} ${50} ${20} # We want all the services to be passive to avoid parasite checks during our test. Ctn Set Services Passive ${0} service_.* @@ -407,3 +412,167 @@ BENCH_${nb_checks}_SERVICE_STATUS_TRACES_WITHOUT_SQL ... 100000 ... 300000 +BENCH_${nb_checks}_REVERSE_SERVICE_STATUS_WITHOUT_SQL + [Documentation] Broker is configured without SQL output. The connection between + ... Engine and Broker is reversed. External command CHECK_SERVICE_RESULT is sent + ... ${nb_checks} times. + [Tags] broker engine bench without_sql reverse connection + # We need to clear the retention and to check that the JSON for the bench event is well generated. + Ctn Clear Retention + Ctn Clear Db logs + Ctn Clear Db comments + Ctn Clear Db data_bin + Ctn Clear Logs + Ctn Config Engine ${1} ${50} ${20} + # We want all the services to be passive to avoid parasite checks during our test. + Ctn Set Services Passive ${0} service_.* + Ctn Config Broker central + Ctn Config Broker rrd + Ctn Config Broker module ${1} + Ctn Broker Config Input Set central central-broker-master-input host 127.0.0.1 + Ctn Broker Config Input Set central central-broker-master-input one_peer_retention_mode yes + Ctn Broker Config Output Remove module0 central-module-master-output host + Ctn Broker Config Output Set module0 central-module-master-output one_peer_retention_mode yes + Ctn Broker Config Log central core info + Ctn Broker Config Log central processing error + Ctn Config BBDO3 1 + # No sql output to avoid broker to slow down too much + Ctn Broker Config Remove Output central unified_sql + Ctn Broker Config Remove Output central sql + Ctn Broker Config Remove Output central storage + ${start} Get Current Date + Ctn Start Broker + Ctn Start engine + Ctn Wait For Engine To Be Ready ${start} ${1} + + ${start} Get Current Date + ${broker_stat_before} Ctn Get Broker Process Stat 51001 + ${engine_stat_before} Ctn Get Engine Process Stat 50001 + Log To Console Sending ${nb_checks} Service check results + Ctn Process Service Check Result host_1 service_1 1 warning config0 0 ${nb_checks} + Ctn Send Bench 1 50001 + Log To Console Done + ${bench_data} Ctn Get Last Bench Result With Timeout ${rrdLog} 1 ${start} central-rrd-master-output 300 + Should be True ${bench_data} is not None No bench element received by Broker + ${broker_stat_after} Ctn Get Broker Process Stat 51001 + ${engine_stat_after} Ctn Get Engine Process Stat 50001 + ${diff_broker} Ctn Diff Process Stat ${broker_stat_after} ${broker_stat_before} + ${diff_engine} Ctn Diff Process Stat ${engine_stat_after} ${engine_stat_before} + + Ctn Download Database From S3 bench.unqlite + + ${success} Ctn Store Result In Unqlite + ... bench.unqlite + ... BENCH_${nb_checks}_REVERSE_SERVICE_STATUS_WITHOUT_SQL + ... broker + ... ${diff_broker} + ... ${broker_stat_after} + ... ${bench_data} + ... central-broker-master-input + ... write + ... central-rrd-master-output + ... publish + Should Be True ${success} Failed to save Broker bench to database + + ${success} Ctn Store Result In Unqlite + ... bench.unqlite + ... BENCH_${nb_checks}_REVERSE_SERVICE_STATUS_WITHOUT_SQL + ... engine + ... ${diff_engine} + ... ${engine_stat_after} + ... ${bench_data} + ... client + ... callback_pb_bench + ... central-module-master-output + ... read + Should Be True ${success} Failed to save Engine bench to database + + Ctn Upload Database To S3 bench.unqlite + + Examples: nb_checks -- + ... 100000 + ... 300000 + +BENCH_${nb_checks}_REVERSE_SERVICE_STATUS_TRACES_WITHOUT_SQL + [Documentation] Broker is configured without SQL output. The connection between Engine + ... and Broker is reversed. External command CHECK_SERVICE_RESULT is sent ${nb_checks} + ... times. Logs are in trace level. + [Tags] broker engine bench without_sql + # We need to clear the retention and to check that the JSON for the bench event is well generated. + Ctn Clear Retention + Ctn Clear Db logs + Ctn Clear Db comments + Ctn Clear Db data_bin + Ctn Clear Logs + Ctn Config Engine ${1} ${50} ${20} + # We want all the services to be passive to avoid parasite checks during our test. + Ctn Set Services Passive ${0} service_.* + Ctn Config Broker central + Ctn Config Broker rrd + Ctn Config Broker module ${1} + FOR ${name} IN @{CONFIG_NAME} + Ctn Broker Config Log central ${name} trace + END + Ctn Broker Config Input Set central central-broker-master-input host 127.0.0.1 + Ctn Broker Config Input Set central central-broker-master-input one_peer_retention_mode yes + Ctn Broker Config Output Remove module0 central-module-master-output host + Ctn Broker Config Output Set module0 central-module-master-output one_peer_retention_mode yes + + Ctn Config BBDO3 1 + # No sql output to avoid broker to slow down too much + Ctn Broker Config Remove Output central unified_sql + Ctn Broker Config Remove Output central sql + Ctn Broker Config Remove Output central storage + ${start} Get Current Date + Ctn Start Broker + Ctn Start engine + Ctn Wait For Engine To Be Ready ${start} ${1} + + ${start} Get Current Date + ${broker_stat_before} Ctn Get Broker Process Stat 51001 + ${engine_stat_before} Ctn Get Engine Process Stat 50001 + Log To Console Sending ${nb_checks} Service check results + Ctn Process Service Check Result host_1 service_1 1 warning config0 0 ${nb_checks} + Ctn Send Bench 1 50001 + Log To Console Done + ${bench_data} Ctn Get Last Bench Result With Timeout ${rrdLog} 1 ${start} central-rrd-master-output 300 + Should be True ${bench_data} is not None No bench element received by Broker + ${broker_stat_after} Ctn Get Broker Process Stat 51001 + ${engine_stat_after} Ctn Get Engine Process Stat 50001 + ${diff_broker} Ctn Diff Process Stat ${broker_stat_after} ${broker_stat_before} + ${diff_engine} Ctn Diff Process Stat ${engine_stat_after} ${engine_stat_before} + + Ctn Download Database From S3 bench.unqlite + + ${success} Ctn Store Result In Unqlite + ... bench.unqlite + ... BENCH_${nb_checks}_REVERSE_SERVICE_STATUS_TRACES_WITHOUT_SQL + ... broker + ... ${diff_broker} + ... ${broker_stat_after} + ... ${bench_data} + ... central-broker-master-input + ... write + ... central-rrd-master-output + ... publish + Should Be True ${success} Failed to save Broker bench to database + + ${success} Ctn Store Result In Unqlite + ... bench.unqlite + ... BENCH_${nb_checks}_REVERSE_SERVICE_STATUS_TRACES_WITHOUT_SQL + ... engine + ... ${diff_engine} + ... ${engine_stat_after} + ... ${bench_data} + ... client + ... callback_pb_bench + ... central-module-master-output + ... read + Should Be True ${success} Failed to save Engine bench to database + + Ctn Upload Database To S3 bench.unqlite + + Examples: nb_checks -- + ... 100000 + ... 300000 + diff --git a/tests/broker-engine/delete-poller.robot b/tests/broker-engine/delete-poller.robot index 011d82d496a..ca8436f761d 100644 --- a/tests/broker-engine/delete-poller.robot +++ b/tests/broker-engine/delete-poller.robot @@ -263,7 +263,7 @@ EBDP3 Should Be Equal As Strings ${output} () EBDP4 - [Documentation] Four new pollers are started and then we remove Poller3 with its hosts and services. All service status/host status are then refused by broker. + [Documentation] Four new pollers are started and then we remove Poller3 with its hosts and services. All service status/host status are then refused by Broker. [Tags] broker engine grpc Ctn Config Engine ${4} ${50} ${20} Ctn Config Broker rrd @@ -272,16 +272,15 @@ EBDP4 Ctn Config BBDO3 ${4} Ctn Broker Config Log central core error Ctn Broker Config Log central sql trace + Ctn Broker Config Log module0 neb trace + Ctn Broker Config Log module1 neb trace + Ctn Broker Config Log module2 neb trace Ctn Broker Config Log module3 neb trace Ctn Broker Config Flush Log central 0 ${start} Get Current Date Ctn Start Broker - Ctn Start engine - - # Let's wait until engine listens to external_commands. - ${content} Create List check_for_external_commands() - ${result} Ctn Find In Log With Timeout ${engineLog3} ${start} ${content} 60 - Should Be True ${result} check_for_external_commands is missing. + Ctn Start Engine + Ctn Wait For Engine To Be Ready ${start} ${4} Connect To Database pymysql ${DBName} ${DBUser} ${DBPass} ${DBHost} ${DBPort} FOR ${index} IN RANGE 60 @@ -310,7 +309,7 @@ EBDP4 Should Be True ${result} Service alerts about service 781 and 782 should be raised ${content} Create List callbacks: service (40, 781) has no perfdata service (40, 782) has no perfdata - ${result} Ctn Find In Log With Timeout ${moduleLog3} ${start} ${content} 60 + ${result} Ctn Find In Log With Timeout ${engineLog3} ${start} ${content} 60 Should Be True ${result} pb service status on services (40, 781) and (40, 782) should be generated Ctn Stop engine @@ -583,7 +582,7 @@ EBDP8 Should Be True ${result} Service alerts about service 781 and 782 should be raised ${content} Create List callbacks: service (40, 781) has no perfdata service (40, 782) has no perfdata - ${result} Ctn Find In Log With Timeout ${moduleLog3} ${start} ${content} 60 + ${result} Ctn Find In Log With Timeout ${engineLog3} ${start} ${content} 60 Should Be True ${result} pb service status on services (40, 781) and (40, 782) should be generated Ctn Stop engine diff --git a/tests/broker-engine/external-commands2.robot b/tests/broker-engine/external-commands2.robot index ecb9b08aeb1..a0349827d7b 100644 --- a/tests/broker-engine/external-commands2.robot +++ b/tests/broker-engine/external-commands2.robot @@ -948,20 +948,18 @@ BEEXTCMD_REVERSE_GRPC1 FOR ${use_grpc} IN RANGE 0 2 Log To Console external command CHANGE_NORMAL_SVC_CHECK_INTERVAL on bbdo3.0 use_grpc=${use_grpc} Ctn Clear Retention - ${start} Get Current Date - Sleep 1s + ${start} Ctn Get Round Current Date Ctn Start Broker Ctn Start engine - ${content} Create List INITIAL SERVICE STATE: host_50;service_1000; check_for_external_commands() - ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 60 - Should Be True - ... ${result} - ... An Initial host state on host_1 should be raised before we can start our external commands. + Ctn Wait For Engine To Be Ready ${1} + Ctn Change Normal Svc Check Interval ${use_grpc} host_1 service_1 10 - Connect To Database pymysql ${DBName} ${DBUser} ${DBPass} ${DBHost} ${DBPort} + Connect To Database + ... pymysql + ... ${DBName} ${DBUser} ${DBPass} ${DBHost} ${DBPort} - FOR ${index} IN RANGE 300 + FOR ${index} IN RANGE 60 Log To Console ... SELECT s.check_interval FROM services s LEFT JOIN hosts h ON s.host_id=h.host_id WHERE h.name='host_1' AND s.description='service_1' ${output} Query diff --git a/tests/broker-engine/log-v2_engine.robot b/tests/broker-engine/log-v2_engine.robot index 84a4037b99c..fa27037e7b8 100644 --- a/tests/broker-engine/log-v2_engine.robot +++ b/tests/broker-engine/log-v2_engine.robot @@ -34,7 +34,7 @@ LOGV2EB1 Should Be True ${result} Engine and Broker not connected ${pid} Get Process Id e0 - ${content} Create List [process] [info] [${pid}] Configuration loaded, main loop starting. + ${content} Create List [process] [info] [:] [${pid}] Configuration loaded, main loop starting. ${result1} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 30 Should Be True ${result1} No message telling configuration loaded. @@ -81,7 +81,7 @@ LOGV2EBU1 Should Be True ${result} Engine and Broker not connected ${pid} Get Process Id e0 - ${content} Create List [process] [info] [${pid}] Configuration loaded, main loop starting. + ${content} Create List [process] [info] [:] [${pid}] Configuration loaded, main loop starting. ${result1} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 30 Should Be True ${result1} No message telling configuration loaded. @@ -171,10 +171,10 @@ LOGV2DB2 ${pid} Get Process Id e0 ${content_v2} Create List [process] [info] [${pid}] Configuration loaded, main loop starting. - ${content_hold} Create List [${pid}] Configuration loaded, main loop starting. + ${content_old} Create List [${pid}] Configuration loaded, main loop starting. ${result1} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content_v2} 30 - ${result2} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content_hold} 30 + ${result2} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content_old} 30 Should Not Be True ${result1} Should Not Be True ${result2} @@ -216,11 +216,11 @@ LOGV2EB2 Should Be True ${result} Engine and Broker not connected ${pid} Get Process Id e0 - ${content_v2} Create List [process] [info] [${pid}] Configuration loaded, main loop starting. - ${content_hold} Create List [${pid}] Configuration loaded, main loop starting. + ${content_v2} Create List [process] [info] [:] [${pid}] Configuration loaded, main loop starting. + ${content_old} Create List [${pid}] Configuration loaded, main loop starting. ${result1} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content_v2} 30 - ${result2} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content_hold} 30 + ${result2} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content_old} 30 Should Be True ${result1} Should Be True ${result2} @@ -264,11 +264,11 @@ LOGV2EBU2 Should Be True ${result} Engine and Broker not connected ${pid} Get Process Id e0 - ${content_v2} Create List [process] [info] [${pid}] Configuration loaded, main loop starting. - ${content_hold} Create List [${pid}] Configuration loaded, main loop starting. + ${content_v2} Create List [process] [info] [:] [${pid}] Configuration loaded, main loop starting. + ${content_old} Create List [${pid}] Configuration loaded, main loop starting. ${result1} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content_v2} 30 - ${result2} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content_hold} 30 + ${result2} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content_old} 30 Should Be True ${result1} Should Be True ${result2} @@ -306,7 +306,7 @@ LOGV2EF1 ${result} Ctn Check Connections Should Be True ${result} Engine and Broker not connected ${pid} Get Process Id e0 - ${content_v2} Create List [process] [info] [${pid}] Configuration loaded, main loop starting. + ${content_v2} Create List [process] [info] [:] [${pid}] Configuration loaded, main loop starting. ${result1} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content_v2} 30 Should Be True ${result1} @@ -331,10 +331,10 @@ LOGV2DF1 ${result} Ctn Check Connections Should Be True ${result} Engine and Broker not connected ${pid} Get Process Id e0 - ${content_hold} Create List [${pid}] Configuration loaded, main loop starting. + ${content_old} Create List [${pid}] Configuration loaded, main loop starting. ${content_v2} Create List [process] [info] [${pid}] Configuration loaded, main loop starting. - ${result1} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content_hold} 30 + ${result1} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content_old} 30 ${result2} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content_v2} 30 Should Be True ${result1} Should Not Be True ${result2} @@ -360,10 +360,10 @@ LOGV2DF2 Should Be True ${result} Engine and Broker not connected ${pid} Get Process Id e0 ${content_v2} Create List [process] [info] [${pid}] Configuration loaded, main loop starting. - ${content_hold} Create List [${pid}] Configuration loaded, main loop starting. + ${content_old} Create List [${pid}] Configuration loaded, main loop starting. ${result1} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content_v2} 15 - ${result2} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content_hold} 15 + ${result2} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content_old} 15 Should Not Be True ${result1} Should Not Be True ${result2} Ctn Stop engine @@ -387,11 +387,11 @@ LOGV2EF2 ${result} Ctn Check Connections Should Be True ${result} Engine and Broker not connected ${pid} Get Process Id e0 - ${content_v2} Create List [process] [info] [${pid}] Configuration loaded, main loop starting. - ${content_hold} Create List [${pid}] Configuration loaded, main loop starting. + ${content_v2} Create List [process] [info] [:] [${pid}] Configuration loaded, main loop starting. + ${content_old} Create List [${pid}] Configuration loaded, main loop starting. ${result1} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content_v2} 15 - ${result2} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content_hold} 15 + ${result2} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content_old} 15 Should Be True ${result1} Should Be True ${result2} Ctn Stop engine @@ -418,7 +418,7 @@ LOGV2FE2 Should Be True ${result} Engine and Broker not connected ${pid} Get Process Id e0 ${content_v2} Create List [process] [info] [${pid}] Configuration loaded, main loop starting. - ${content_hold} Create List [${pid}] Configuration loaded, main loop starting. + ${content_old} Create List [${pid}] Configuration loaded, main loop starting. Sleep 2m diff --git a/tests/broker-engine/muxer_filter.robot b/tests/broker-engine/muxer_filter.robot index addd918ab20..cb00f4e333e 100644 --- a/tests/broker-engine/muxer_filter.robot +++ b/tests/broker-engine/muxer_filter.robot @@ -21,17 +21,18 @@ STUPID_FILTER Ctn Config Broker Sql Output central unified_sql Ctn Config BBDO3 1 Ctn Broker Config Output Set Json central central-broker-unified-sql filters {"category": ["bbdo"]} + Ctn Clear Broker Logs ${start} Get Current Date Ctn Start Broker True Ctn Start engine ${content} Create List - ... The configured write filters for the endpoint 'central-broker-unified-sql' are too restrictive and will be ignored. neb,bbdo,extcmd categories are mandatory. + ... The configured write filters for the endpoint 'central-broker-unified-sql' contain forbidden filters. These ones are removed The configured read filters for the endpoint 'central-broker-unified-sql' contain forbidden filters. These ones are removed ${result} Ctn Find In Log With Timeout ${centralLog} ${start} ${content} 60 Should Be True ${result} A message telling bad filter should be available. - Ctn Stop engine + Ctn Stop Engine Ctn Kindly Stop Broker True STORAGE_ON_LUA @@ -61,7 +62,7 @@ STORAGE_ON_LUA ${grep_res} Grep File /tmp/all_lua_event.log "category":[^3] regexp=True Should Be Empty ${grep_res} Events of category different than 'storage' found. - Ctn Stop engine + Ctn Stop Engine Ctn Kindly Stop Broker True FILTER_ON_LUA_EVENT @@ -87,6 +88,7 @@ FILTER_ON_LUA_EVENT ... test-filter ... filters ... {"category": [ "storage:pb_metric_mapping"]} + Ctn Clear Broker Logs Ctn Start Broker True Ctn Start engine @@ -107,11 +109,12 @@ FILTER_ON_LUA_EVENT ... All the lines in all_lua_event.log should contain "_type":196620 END - Ctn Stop engine + Ctn Stop Engine Ctn Kindly Stop Broker True BAM_STREAM_FILTER - [Documentation] With bbdo version 3.0.1, a BA of type 'worst' with one service is configured. The BA is in critical state, because of its service. we watch its events + [Documentation] With bbdo version 3.0.1, a BA of type 'worst' with one service is + ... configured. The BA is in critical state, because of its service. we watch its events [Tags] broker engine bam filter Ctn Clear Commands Status Ctn Config Broker module ${1} @@ -132,13 +135,12 @@ BAM_STREAM_FILTER ${cmd_1} Ctn Get Service Command Id 314 Log To Console service_314 has command id ${cmd_1} Ctn Set Command Status ${cmd_1} 2 + Ctn Clear Broker Logs + Ctn Start Broker True ${start} Get Current Date Ctn Start engine - # Let's wait for the external command check start - ${content} Create List check_for_external_commands() - ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 60 - Should Be True ${result} A message telling check_for_external_commands() should be available. + Ctn Wait For Engine To Be Ready ${1} # KPI set to critical Ctn Process Service Result Hard host_16 service_314 2 output critical for 314 @@ -150,8 +152,8 @@ BAM_STREAM_FILTER ${result} Ctn Check Ba Status With Timeout test 2 60 Should Be True ${result} The BA ba_1 is not CRITICAL as expected - # monitoring - FOR ${cpt} IN RANGE 30 + # Monitoring + FOR ${cpt} IN RANGE 30 # pb_service ${grep_res1} Grep File ${centralLog} centreon-bam-monitoring event of type 1001b written # pb_service_status @@ -161,26 +163,27 @@ BAM_STREAM_FILTER # pb_kpi_status ${grep_res4} Grep File ${centralLog} centreon-bam-monitoring event of type 6001b written - # reject KpiEvent + # Reject KpiEvent ${grep_res5} Grep File ... ${centralLog} - ... muxer centreon-bam-monitoring event of type 60015 rejected by write filter - # reject storage + ... muxer centreon-bam-monitoring event bam:KpiEvent .* rejected by write filter regexp=True + # Reject storage ${grep_res6} Grep File ... ${centralLog} - ... muxer centreon-bam-monitoring event of type 3[0-9a-f]{4} rejected by write filter regexp=True + ... muxer centreon-bam-monitoring event storage:.* rejected by write filter regexp=True IF len("""${grep_res1}""") > 0 and len("""${grep_res2}""") > 0 and len("""${grep_res3}""") > 0 and len("""${grep_res4}""") > 0 and len("""${grep_res5}""") > 0 and len("""${grep_res6}""") > 0 BREAK END + Sleep 1s END - Should Not Be Empty ${grep_res1} no pb_service event - Should Not Be Empty ${grep_res2} no pb_service_status event - Should Not Be Empty ${grep_res3} no pb_ba_status event - Should Not Be Empty ${grep_res4} no pb_kpi_status event - Should Not Be Empty ${grep_res5} no KpiEvent event - Should Not Be Empty ${grep_res6} no storage event rejected + Should Not Be Empty ${grep_res1} We should receive pb_service events. Nothing received. + Should Not Be Empty ${grep_res2} We should receive pb_service_status events. Nothing received. + Should Not Be Empty ${grep_res3} We should receive pb_ba_status events. Nothing received. + Should Not Be Empty ${grep_res4} We should receive pb_kpi_status events. Nothing received. + Should Not Be Empty ${grep_res5} We should reject KpiEvent events. They are not rejected. + Should Not Be Empty ${grep_res6} We should reject events of Storage category. The are not rejected. # reporting # pb_ba_event @@ -192,15 +195,15 @@ BAM_STREAM_FILTER # reject storage ${grep_res} Grep File ... ${centralLog} - ... centreon-bam-reporting event of type 3[0-9a-f]{4} rejected by write filter regexp=True - Should Not Be Empty ${grep_res} no rejected storage event + ... centreon-bam-reporting event storage:.* rejected by write filter regexp=True + Should Not Be Empty ${grep_res} We should reject events of Storage category. They are not rejected. # reject neb ${grep_res} Grep File ... ${centralLog} - ... centreon-bam-reporting event of type 1[0-9a-f]{4} rejected by write filter regexp=True - Should Not Be Empty ${grep_res} no rejected neb event + ... centreon-bam-reporting event neb:.* rejected by write filter regexp=True + Should Not Be Empty ${grep_res} We should reject events of Neb category. They are not rejected. - Ctn Stop engine + Ctn Stop Engine Ctn Kindly Stop Broker True UNIFIED_SQL_FILTER @@ -213,6 +216,7 @@ UNIFIED_SQL_FILTER Ctn Broker Config Log central core trace Ctn Config BBDO3 ${1} Ctn Config Engine ${1} + Ctn Clear Broker Logs ${start} Get Current Date Ctn Start Broker True @@ -236,7 +240,7 @@ UNIFIED_SQL_FILTER Should Not Be Empty ${grep_res} END - Ctn Stop engine + Ctn Stop Engine Ctn Kindly Stop Broker True CBD_RELOAD_AND_FILTERS @@ -257,10 +261,7 @@ CBD_RELOAD_AND_FILTERS Ctn Start Broker Ctn Start engine - # Let's wait for the external command check start - ${content} Create List check_for_external_commands() - ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 60 - Should Be True ${result} A message telling check_for_external_commands() should be available. + Ctn Wait For Engine To Be Ready ${1} # Let's wait for storage data written into rrd files ${content} Create List RRD: new pb status data for index @@ -269,7 +270,7 @@ CBD_RELOAD_AND_FILTERS # We check that output filters to rrd are set to "all" ${content} Create List - ... endpoint applier: filters for endpoint 'centreon-broker-master-rrd' reduced to the needed ones: all + ... endpoint applier: The configured write filters for the endpoint 'centreon-broker-master-rrd' contain forbidden filters. These ones are removed ${result} Ctn Find In Log With Timeout ${centralLog} ${start} ${content} 60 Should Be True ${result} No message about the output filters to rrd broker. @@ -283,7 +284,7 @@ CBD_RELOAD_AND_FILTERS #wait broker reload ${content} Create List creating endpoint centreon-broker-master-rrd ${result} Ctn Find In Log With Timeout ${centralLog} ${start} ${content} 60 - Should Be True ${result} No creating endpoint centreon-broker-master-rrd. + Should Be True ${result} Endpoint 'centreon-broker-master-rrd' not created. ${start2} Get Current Date # We check that output filters to rrd are set to "storage" @@ -300,7 +301,7 @@ CBD_RELOAD_AND_FILTERS Should Be True ${result} No status from central broker for 1mn. # We check that output filters to rrd are set to "storage" - ${content} Create List rrd event of type .* rejected by write filter + ${content} Create List rrd event .* rejected by write filter ${result} Ctn Find Regex In Log With Timeout ${centralLog} ${start2} ${content} 120 Should Be True ${result} No event rejected by the rrd output whereas only storage category is enabled. @@ -318,7 +319,7 @@ CBD_RELOAD_AND_FILTERS # We check that output filters to rrd are set to "all" ${content} Create List - ... endpoint applier: filters for endpoint 'centreon-broker-master-rrd' reduced to the needed ones: all + ... endpoint applier: The configured write filters for the endpoint 'centreon-broker-master-rrd' contain forbidden filters. These ones are removed ${result} Ctn Find In Log With Timeout ${centralLog} ${start} ${content} 60 Should Be True ${result} No message about the output filters to rrd broker. ${start} Get Current Date @@ -329,14 +330,14 @@ CBD_RELOAD_AND_FILTERS Should Be True ${result} No status from central broker for 1mn. # We check that output filters to rrd doesn't filter anything - ${content} Create List rrd event of type .* rejected by write filter + ${content} Create List rrd event .* rejected by write filter ${result} Ctn Find Regex In Log With Timeout ${centralLog} ${start2} ${content} 30 Should Be Equal As Strings ... ${result[0]} ... False ... Some events are rejected by the rrd output whereas all categories are enabled. - Ctn Stop engine + Ctn Stop Engine Ctn Kindly Stop Broker True CBD_RELOAD_AND_FILTERS_WITH_OPR @@ -360,10 +361,7 @@ CBD_RELOAD_AND_FILTERS_WITH_OPR Ctn Start Broker Ctn Start engine - # Let's wait for the external command check start - ${content} Create List check_for_external_commands() - ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 60 - Should Be True ${result} A message telling check_for_external_commands() should be available. + Ctn Wait For Engine To Be Ready ${1} # Let's wait for storage data written into rrd files ${content} Create List RRD: new pb status data for index @@ -372,8 +370,8 @@ CBD_RELOAD_AND_FILTERS_WITH_OPR # We check that output filters to rrd are set to "all" ${content} Create List - ... endpoint applier: filters for endpoint 'centreon-broker-master-rrd' reduced to the needed ones: all - ${result} Ctn Find In Log With Timeout ${centralLog} ${start} ${content} 60 + ... Filters applied on endpoint:all + ${result} Ctn Find In Log With Timeout ${centralLog} ${start} ${content} 30 Should Be True ${result} No message about the output filters to rrd broker. # New configuration @@ -403,7 +401,7 @@ CBD_RELOAD_AND_FILTERS_WITH_OPR Should Be True ${result} No status from central broker for 1mn. # We check that output filters to rrd are set to "storage" - ${content} Create List rrd event of type .* rejected by write filter + ${content} Create List rrd event .* rejected by write filter ${result} Ctn Find Regex In Log With Timeout ${centralLog} ${start2} ${content} 120 Should Be True ${result} No event rejected by the rrd output whereas only storage category is enabled. @@ -420,8 +418,7 @@ CBD_RELOAD_AND_FILTERS_WITH_OPR ${start2} Get Current Date # We check that output filters to rrd are set to "all" - ${content} Create List - ... endpoint applier: filters for endpoint 'centreon-broker-master-rrd' reduced to the needed ones: all + ${content} Create List Filters applied on endpoint:all ${result} Ctn Find In Log With Timeout ${centralLog} ${start} ${content} 60 Should Be True ${result} No message about the output filters to rrd broker. @@ -431,14 +428,14 @@ CBD_RELOAD_AND_FILTERS_WITH_OPR Should Be True ${result} No status from central broker for 1mn. # We check that output filters to rrd doesn't filter anything - ${content} Create List rrd event of type .* rejected by write filter + ${content} Create List rrd event .* rejected by write filter ${result} Ctn Find Regex In Log With Timeout ${centralLog} ${start2} ${content} 30 Should Be Equal As Strings ... ${result[0]} ... False ... Some events are rejected by the rrd output whereas all categories are enabled. - Ctn Stop engine + Ctn Stop Engine Ctn Kindly Stop Broker True SEVERAL_FILTERS_ON_LUA_EVENT @@ -510,5 +507,5 @@ SEVERAL_FILTERS_ON_LUA_EVENT ... "_type":65565 ... All the lines in all_lua_event-bis.log should contain "_type":65565 END - Ctn Stop engine + Ctn Stop Engine Ctn Kindly Stop Broker True diff --git a/tests/broker-engine/retention-duplicates.robot b/tests/broker-engine/retention-duplicates.robot index 456a465053e..b7ef8a66a7c 100644 --- a/tests/broker-engine/retention-duplicates.robot +++ b/tests/broker-engine/retention-duplicates.robot @@ -32,7 +32,7 @@ BERD1 ${content} Create List lua: initializing the Lua virtual machine ${result} Ctn Find In Log With Timeout ${centralLog} ${start} ${content} 30 Should Be True ${result} Lua not started in cbd - ${result} Ctn Find In Log With Timeout ${moduleLog0} ${start} ${content} 30 + ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 30 Should Be True ${result} Lua not started in centengine ${result} Ctn Check Connections Should Be True ${result} Engine and Broker not connected. @@ -65,6 +65,7 @@ BERD2 Ctn Broker Config Add Lua Output module0 test-doubles ${SCRIPTS}test-doubles.lua Ctn Broker Config Log module0 lua debug Ctn Broker Config Log module0 neb debug + Ctn Broker Config Log central bbdo debug Ctn Config Broker rrd Ctn Clear Retention ${start} Get Current Date @@ -73,13 +74,15 @@ BERD2 ${content} Create List lua: initializing the Lua virtual machine ${result} Ctn Find In Log With Timeout ${centralLog} ${start} ${content} 30 Should Be True ${result} Lua not started in cbd - ${result} Ctn Find In Log With Timeout ${moduleLog0} ${start} ${content} 30 + ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 30 Should Be True ${result} Lua not started in centengine ${result} Ctn Check Connections Should Be True ${result} Engine and Broker not connected. + Log To Console Engine and Broker talk during 15s. Sleep 15s Ctn Stop engine Ctn Start engine + Log To Console Engine has been restart and now they talk during 25s. Sleep 25s Ctn Stop engine Ctn Kindly Stop Broker @@ -113,7 +116,7 @@ BERDUC1 ${content} Create List lua: initializing the Lua virtual machine ${result} Ctn Find In Log With Timeout ${centralLog} ${start} ${content} 30 Should Be True ${result} Lua not started in cbd - ${result} Ctn Find In Log With Timeout ${moduleLog0} ${start} ${content} 30 + ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 30 Should Be True ${result} Lua not started in centengine ${result} Ctn Check Connections Should Be True ${result} Engine and Broker not connected. @@ -152,7 +155,7 @@ BERDUCU1 ${content} Create List lua: initializing the Lua virtual machine ${result} Ctn Find In Log With Timeout ${centralLog} ${start} ${content} 30 Should Be True ${result} Lua not started in cbd - ${result} Ctn Find In Log With Timeout ${moduleLog0} ${start} ${content} 30 + ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 30 Should Be True ${result} Lua not started in centengine Sleep 5s Ctn Kindly Stop Broker @@ -187,7 +190,7 @@ BERDUC2 ${content} Create List lua: initializing the Lua virtual machine ${result} Ctn Find In Log With Timeout ${centralLog} ${start} ${content} 30 Should Be True ${result} Lua not started in cbd - ${result} Ctn Find In Log With Timeout ${moduleLog0} ${start} ${content} 30 + ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 30 Should Be True ${result} Lua not started in centengine ${result} Ctn Check Connections Should Be True ${result} Engine and Broker not connected. @@ -226,7 +229,7 @@ BERDUCU2 ${content} Create List lua: initializing the Lua virtual machine ${result} Ctn Find In Log With Timeout ${centralLog} ${start} ${content} 30 Should Be True ${result} Lua not started in cbd - ${result} Ctn Find In Log With Timeout ${moduleLog0} ${start} ${content} 30 + ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 30 Should Be True ${result} Lua not started in centengine ${result} Ctn Check Connections Should Be True ${result} Engine and Broker not connected. @@ -264,7 +267,7 @@ BERDUC3U1 ${content} Create List lua: initializing the Lua virtual machine ${result} Ctn Find In Log With Timeout ${centralLog} ${start} ${content} 30 Should Be True ${result} Lua not started in cbd - ${result} Ctn Find In Log With Timeout ${moduleLog0} ${start} ${content} 30 + ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 30 Should Be True ${result} Lua not started in centengine ${result} Ctn Check Connections Should Be True ${result} Engine and Broker not connected. @@ -306,7 +309,7 @@ BERDUC3U2 ${content} Create List lua: initializing the Lua virtual machine ${result} Ctn Find In Log With Timeout ${centralLog} ${start} ${content} 30 Should Be True ${result} Lua not started in cbd - ${result} Ctn Find In Log With Timeout ${moduleLog0} ${start} ${content} 30 + ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 30 Should Be True ${result} Lua not started in centengine # Let's wait for all the services configuration. @@ -315,7 +318,7 @@ BERDUC3U2 ${start} Ctn Get Round Current Date # Let's wait for a first service status. - ${content} Create List SQL: pb service .* status .* type .* check result output + ${content} Create List unified_sql: processing pb service status ${result} Ctn Find Regex In Log With Timeout ${centralLog} ${start} ${content} 60 Should Be True ${result[0]} We did not get any pb service status for 60s @@ -352,9 +355,9 @@ BERDUCA300 Ctn Broker Config Flush Log central 0 Ctn Broker Config Flush Log module0 0 Ctn Config Broker rrd - Ctn Broker Config Add Item module0 bbdo_version 3.0.0 - Ctn Broker Config Add Item central bbdo_version 3.0.0 - Ctn Broker Config Add Item rrd bbdo_version 3.0.0 + Ctn Broker Config Add Item module0 bbdo_version 3.0.1 + Ctn Broker Config Add Item central bbdo_version 3.0.1 + Ctn Broker Config Add Item rrd bbdo_version 3.0.1 ${start} Get Current Date Ctn Start Broker Ctn Start engine @@ -362,16 +365,14 @@ BERDUCA300 ${result} Ctn Check Connections Should Be True ${result} Engine and Broker not connected. - # Let's wait for all the services configuration. - ${content} Create List INITIAL SERVICE STATE: host_50;service_1000; check_for_external_commands() - ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 60 + Ctn Wait For Engine To Be Ready ${1} Ctn Stop engine - ${content} Create List BBDO: sending pb stop packet to peer - ${result} Ctn Find In Log With Timeout ${moduleLog0} ${start} ${content} 30 + ${content} Create List BBDO: sending stop packet to peer + ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 30 Should Be True ${result} Engine should send a pb stop message to cbd. - ${content} Create List BBDO: received pb stop from peer + ${content} Create List BBDO: received stop from peer ${result} Ctn Find In Log With Timeout ${centralLog} ${start} ${content} 30 Should Be True ${result} Broker should receive a pb stop message from engine. @@ -380,7 +381,7 @@ BERDUCA300 Should Be True ${result[0]} Broker should send an ack for handled events. ${content} Create List BBDO: received acknowledgement for [0-9]+ events before finishing - ${result} Ctn Find Regex In Log With Timeout ${moduleLog0} ${start} ${content} 30 + ${result} Ctn Find Regex In Log With Timeout ${engineLog0} ${start} ${content} 30 Should Be True ${result[0]} Engine should receive an ack for handled events from broker. Ctn Kindly Stop Broker @@ -414,26 +415,23 @@ BERDUCA301 ${result} Ctn Check Connections Should Be True ${result} Engine and Broker not connected. - - # Let's wait for all the services configuration. - ${content} Create List INITIAL SERVICE STATE: host_50;service_1000; check_for_external_commands() - ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 60 + Ctn Wait For Engine To Be Ready ${1} Ctn Stop engine - ${content} Create List BBDO: sending pb stop packet to peer - ${result} Ctn Find In Log With Timeout ${moduleLog0} ${start} ${content} 30 + ${content} Create List BBDO: sending stop packet to peer + ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 30 Should Be True ${result} Engine should send a pb stop message to cbd. - ${content} Create List BBDO: received pb stop from peer + ${content} Create List BBDO: received stop from peer ${result} Ctn Find In Log With Timeout ${centralLog} ${start} ${content} 30 Should Be True ${result} Broker should receive a pb stop message from engine. - ${content} Create List send pb acknowledgement for [0-9]+ events + ${content} Create List send acknowledgement for [0-9]+ events ${result} Ctn Find Regex In Log With Timeout ${centralLog} ${start} ${content} 30 Should Be True ${result[0]} Broker should send an ack for handled events. ${content} Create List BBDO: received acknowledgement for [0-9]+ events before finishing - ${result} Ctn Find Regex In Log With Timeout ${moduleLog0} ${start} ${content} 30 + ${result} Ctn Find Regex In Log With Timeout ${engineLog0} ${start} ${content} 30 Should Be True ${result[0]} Engine should receive an ack for handled events from broker. Ctn Kindly Stop Broker diff --git a/tests/broker-engine/reverse-connection.robot b/tests/broker-engine/reverse-connection.robot index 36013d1773e..03fd0019d72 100644 --- a/tests/broker-engine/reverse-connection.robot +++ b/tests/broker-engine/reverse-connection.robot @@ -128,9 +128,8 @@ BRCTSMN Ctn Start engine # Let's wait for the external command check start - ${content} Create List check_for_external_commands() - ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 60 - Should Be True ${result} A message telling check_for_external_commands() should be available. + Ctn Wait For Engine To Be Ready ${1} + # pb_service pb_host pb_service_status pb_host_status ${expected_events} Create List 65563 65566 65565 65568 ${categories} Create List 1 diff --git a/tests/broker-engine/services.robot b/tests/broker-engine/services.robot index 5de10e96dfe..4f49c8fba3e 100644 --- a/tests/broker-engine/services.robot +++ b/tests/broker-engine/services.robot @@ -11,26 +11,31 @@ Test Teardown Ctn Save Logs If Failed *** Test Cases *** SDER - [Documentation] The check attempts and the max check attempts of (host_1,service_1) are changed to 280 thanks to the retention.dat file. Then engine and broker are started and broker should write these values in the services and resources tables. We only test the services table because we need a resources table that allows bigger numbers for these two attributes. But we see that broker doesn't crash anymore. + [Documentation] The check attempts and the max check attempts of (host_1,service_1) + ... are changed to 280 thanks to the retention.dat file. Then Engine and Broker are started + ... and Broker should write these values in the services and resources tables. + ... We only test the services table because we need a resources table that allows bigger numbers + ... for these two attributes. But we see that Broker doesn't crash anymore. [Tags] broker engine host extcmd Ctn Config Engine ${1} ${1} ${25} Ctn Config Broker rrd Ctn Config Broker central Ctn Config Broker module ${1} Ctn Config BBDO3 1 + Ctn Broker Config Log central core trace + Ctn Broker Config Log central processing trace Ctn Broker Config Log central sql debug + Ctn Broker Config Log module0 core error Ctn Broker Config Log module0 neb trace + Ctn Broker Config Log module0 processing trace Ctn Config Broker Sql Output central unified_sql + Ctn Engine Config Replace Value In Services 0 service_1 max_check_attempts 42 ${start} Get Current Date Ctn Start Broker - Ctn Start engine + Ctn Start Engine + Ctn Wait For Engine To Be Ready ${start} ${1} - # Let's wait for the external command check start - ${content} Create List check_for_external_commands() - ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 60 - Should Be True ${result} A message telling check_for_external_commands() should be available. - - Ctn Stop engine + Ctn Stop Engine Ctn Modify Retention Dat 0 host_1 service_1 current_attempt 280 # modified attributes is a bit field. We must set the bit corresponding to MAX_ATTEMPTS to be allowed to change max_attempts. Otherwise it will be set to 3. @@ -39,11 +44,12 @@ SDER Ctn Modify Retention Dat 0 host_1 service_1 current_state 2 Ctn Modify Retention Dat 0 host_1 service_1 state_type 1 - Ctn Start engine + Ctn Start Engine + Ctn Wait For Engine To Be Ready ${start} ${1} Connect To Database pymysql ${DBName} ${DBUser} ${DBPass} ${DBHost} ${DBPort} - FOR ${index} IN RANGE 30 + FOR ${index} IN RANGE 20 Log To Console SELECT check_attempt from services WHERE description='service_1' ${output} Query SELECT check_attempt from services WHERE description='service_1' Log To Console ${output} @@ -52,5 +58,5 @@ SDER END Should Be Equal As Strings ${output} ((280,),) - Ctn Stop engine + Ctn Stop Engine Ctn Kindly Stop Broker diff --git a/tests/broker-engine/start-stop.robot b/tests/broker-engine/start-stop.robot index 235fc2ffa08..a52a5497882 100644 --- a/tests/broker-engine/start-stop.robot +++ b/tests/broker-engine/start-stop.robot @@ -18,11 +18,11 @@ BESS1 Ctn Config Broker module Ctn Config Broker rrd Ctn Start Broker - Ctn Start engine + Ctn Start Engine ${result} Ctn Check Connections Should Be True ${result} Ctn Kindly Stop Broker - Ctn Stop engine + Ctn Stop Engine BESS2 [Documentation] Start-Stop Broker/Engine - Broker started first - Engine stopped first @@ -31,15 +31,47 @@ BESS2 Ctn Config Broker central Ctn Config Broker module Ctn Config Broker rrd + Ctn Broker Config Log central sql debug + Ctn Broker Config Log central bbdo info + ${start} Get Current Date Ctn Start Broker - Ctn Start engine + Ctn Start Engine ${result} Ctn Check Connections - Should Be True ${result} + Should Be True ${result} Connection between Engine and Broker not established ${result} Ctn Check Poller Enabled In Database 1 10 - Should Be True ${result} - Ctn Stop engine + Should Be True ${result} Poller not visible in database + Ctn Stop Engine + ${content} Create List SQL: Disabling poller + ${result} Ctn Find In Log With Timeout ${centralLog} ${start} ${content} 30 + Should Be True ${result} No stop event processed by central cbd ${result} Ctn Check Poller Disabled In Database 1 10 - Should Be True ${result} + Should Be True ${result} Poller still visible in database + Ctn Kindly Stop Broker + +BESS2U + [Documentation] Start-Stop Broker/Engine - Broker started first - Engine stopped first. + ... Unified_sql is used. + [Tags] broker engine start-stop + Ctn Config Engine ${1} + Ctn Config Broker central + Ctn Config Broker module + Ctn Config Broker rrd + Ctn Config BBDO3 1 + Ctn Broker Config Log central sql info + Ctn Broker Config Log central bbdo info + ${start} Get Current Date + Ctn Start Broker + Ctn Start Engine + ${result} Ctn Check Connections + Should Be True ${result} Connection between Engine and Broker not established + ${result} Ctn Check Poller Enabled In Database 1 10 + Should Be True ${result} Poller not visible in database + Ctn Stop Engine + ${content} Create List unified_sql: Disabling poller + ${result} Ctn Find In Log With Timeout ${centralLog} ${start} ${content} 30 + Should Be True ${result} No stop event processed by central cbd + ${result} Ctn Check Poller Disabled In Database 1 10 + Should Be True ${result} Poller still visible in database Ctn Kindly Stop Broker BESS3 @@ -49,13 +81,13 @@ BESS3 Ctn Config Broker central Ctn Config Broker module Ctn Config Broker rrd - Ctn Start engine + Ctn Start Engine Ctn Start Broker ${result} Ctn Check Connections Should Be True ${result} ${result} Ctn Check Poller Enabled In Database 1 10 Should Be True ${result} - Ctn Stop engine + Ctn Stop Engine ${result} Ctn Check Poller Disabled In Database 1 10 Should Be True ${result} Ctn Kindly Stop Broker @@ -67,14 +99,14 @@ BESS4 Ctn Config Broker central Ctn Config Broker module Ctn Config Broker rrd - Ctn Start engine + Ctn Start Engine Ctn Start Broker ${result} Ctn Check Connections Should Be True ${result} ${result} Ctn Check Poller Enabled In Database 1 10 Should Be True ${result} Ctn Kindly Stop Broker - Ctn Stop engine + Ctn Stop Engine BESS5 [Documentation] Start-Stop Broker/engine - Engine debug level is set to all, it should not hang @@ -85,7 +117,7 @@ BESS5 Ctn Config Broker rrd Ctn Engine Config Set Value ${0} debug_level ${-1} Ctn Start Broker - Ctn Start engine + Ctn Start Engine ${result} Ctn Check Connections Should Be True ${result} Broker and Engine seem not connected [Teardown] Ctn Stop Engine Broker And Save Logs @@ -102,11 +134,11 @@ BESS_GRPC1 Ctn Change Broker Tcp Input To Grpc central Ctn Change Broker Tcp Input To Grpc rrd Ctn Start Broker - Ctn Start engine + Ctn Start Engine ${result} Ctn Check Connections Should Be True ${result} Ctn Kindly Stop Broker - Ctn Stop engine + Ctn Stop Engine BESS_GRPC2 [Documentation] Start-Stop grpc version Broker/Engine - Broker started first - Engine stopped first @@ -120,14 +152,14 @@ BESS_GRPC2 Ctn Change Broker Tcp Input To Grpc central Ctn Change Broker Tcp Input To Grpc rrd Ctn Start Broker - Ctn Start engine + Ctn Start Engine ${result} Ctn Check Connections - Should Be True ${result} + Should Be True ${result} Connections between Engine and Broker not established ${result} Ctn Check Poller Enabled In Database 1 10 - Should Be True ${result} - Ctn Stop engine + Should Be True ${result} Poller not visible in database + Ctn Stop Engine ${result} Ctn Check Poller Disabled In Database 1 10 - Should Be True ${result} + Should Be True ${result} Poller still visible in database Ctn Kindly Stop Broker BESS_GRPC3 @@ -141,15 +173,15 @@ BESS_GRPC3 Ctn Change Broker Tcp Output To Grpc module0 Ctn Change Broker Tcp Input To Grpc central Ctn Change Broker Tcp Input To Grpc rrd - Ctn Start engine + Ctn Start Engine Ctn Start Broker ${result} Ctn Check Connections - Should Be True ${result} + Should Be True ${result} Connections between Engine and Broker not established ${result} Ctn Check Poller Enabled In Database 1 10 - Should Be True ${result} - Ctn Stop engine + Should Be True ${result} Poller not visible in database + Ctn Stop Engine ${result} Ctn Check Poller Disabled In Database 1 10 - Should Be True ${result} + Should Be True ${result} Poller still visible in database Ctn Kindly Stop Broker BESS_GRPC4 @@ -163,12 +195,12 @@ BESS_GRPC4 Ctn Change Broker Tcp Output To Grpc module0 Ctn Change Broker Tcp Input To Grpc central Ctn Change Broker Tcp Input To Grpc rrd - Ctn Start engine + Ctn Start Engine Ctn Start Broker ${result} Ctn Check Connections Should Be True ${result} Ctn Kindly Stop Broker - Ctn Stop engine + Ctn Stop Engine BESS_GRPC5 [Documentation] Start-Stop grpc version Broker/engine - Engine debug level is set to all, it should not hang @@ -183,14 +215,14 @@ BESS_GRPC5 Ctn Change Broker Tcp Input To Grpc central Ctn Change Broker Tcp Input To Grpc rrd Ctn Start Broker - Ctn Start engine + Ctn Start Engine ${result} Ctn Check Connections - Should Be True ${result} + Should Be True ${result} Connections between Engine and Broker not established ${result} Ctn Check Poller Enabled In Database 1 10 - Should Be True ${result} - Ctn Stop engine + Should Be True ${result} Poller not visible in database + Ctn Stop Engine ${result} Ctn Check Poller Disabled In Database 1 10 - Should Be True ${result} + Should Be True ${result} Poller still visible in database Ctn Kindly Stop Broker BESS_GRPC_COMPRESS1 @@ -207,14 +239,14 @@ BESS_GRPC_COMPRESS1 Ctn Change Broker Compression Output module0 central-module-master-output yes Ctn Change Broker Compression Input central centreon-broker-master-input yes Ctn Start Broker - Ctn Start engine + Ctn Start Engine ${result} Ctn Check Connections - Should Be True ${result} + Should Be True ${result} Connection not established between Engine and Broker ${result} Ctn Check Poller Enabled In Database 1 10 - Should Be True ${result} - Ctn Stop engine + Should Be True ${result} Poller not visible in database + Ctn Stop Engine ${result} Ctn Check Poller Disabled In Database 1 10 - Should Be True ${result} + Should Be True ${result} Poller still visible in database Ctn Kindly Stop Broker BESS_CRYPTED_GRPC1 @@ -237,12 +269,12 @@ BESS_CRYPTED_GRPC1 Ctn Add Host To Broker Output module0 central-module-master-output localhost FOR ${i} IN RANGE 0 5 Ctn Start Broker - Ctn Start engine + Ctn Start Engine ${result} Ctn Check Connections Should Be True ${result} ${result} Ctn Check Poller Enabled In Database 1 10 Should Be True ${result} - Ctn Stop engine + Ctn Stop Engine ${result} Ctn Check Poller Disabled In Database 1 10 Should Be True ${result} Ctn Kindly Stop Broker @@ -265,10 +297,10 @@ BESS_CRYPTED_GRPC2 Ctn Add Broker Tcp Input Grpc Crypto central True False FOR ${i} IN RANGE 0 5 Ctn Start Broker - Ctn Start engine + Ctn Start Engine Sleep 2s Ctn Kindly Stop Broker - Ctn Stop engine + Ctn Stop Engine END BESS_CRYPTED_GRPC3 @@ -288,10 +320,10 @@ BESS_CRYPTED_GRPC3 Ctn Add Broker Tcp Output Grpc Crypto module0 True False FOR ${i} IN RANGE 0 5 Ctn Start Broker - Ctn Start engine + Ctn Start Engine Sleep 2s Ctn Kindly Stop Broker - Ctn Stop engine + Ctn Stop Engine END BESS_CRYPTED_REVERSED_GRPC1 @@ -314,12 +346,12 @@ BESS_CRYPTED_REVERSED_GRPC1 Ctn Remove Host From Broker Output module0 central-module-master-output FOR ${i} IN RANGE 0 5 Ctn Start Broker - Ctn Start engine + Ctn Start Engine ${result} Ctn Check Connections Should Be True ${result} Sleep 2s Ctn Kindly Stop Broker - Ctn Stop engine + Ctn Stop Engine END BESS_CRYPTED_REVERSED_GRPC2 @@ -341,10 +373,10 @@ BESS_CRYPTED_REVERSED_GRPC2 Ctn Remove Host From Broker Output module0 central-module-master-output FOR ${i} IN RANGE 0 5 Ctn Start Broker - Ctn Start engine + Ctn Start Engine Sleep 5s Ctn Kindly Stop Broker - Ctn Stop engine + Ctn Stop Engine END BESS_CRYPTED_REVERSED_GRPC3 @@ -364,10 +396,10 @@ BESS_CRYPTED_REVERSED_GRPC3 Ctn Remove Host From Broker Output module0 central-module-master-output FOR ${i} IN RANGE 0 5 Ctn Start Broker - Ctn Start engine + Ctn Start Engine Sleep 5s Ctn Kindly Stop Broker - Ctn Stop engine + Ctn Stop Engine END BESS_ENGINE_DELETE_HOST @@ -379,7 +411,7 @@ BESS_ENGINE_DELETE_HOST Ctn Clear Retention ${start} Get Current Date Ctn Start Broker True - Ctn Start engine + Ctn Start Engine ${content} Create List check_for_external_commands ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 60 Should Be True @@ -392,7 +424,7 @@ BESS_ENGINE_DELETE_HOST Ctn Reload Engine Sleep 2s Ctn Kindly Stop Broker True - Ctn Stop engine + Ctn Stop Engine BESSBQ1 [Documentation] A very bad queue file is written for broker. Broker and Engine are then started, Broker must read the file raising an error because of that file and then get data sent by Engine. @@ -411,12 +443,12 @@ BESSBQ1 Ctn Create Bad Queue central-broker-master.queue.central-broker-master-sql ${start} Get Current Date Ctn Start Broker - Ctn Start engine - ${content} Create List execute statement 306524174 + Ctn Start Engine + ${content} Create List execute statement 1245300e ${result} Ctn Find In Log With Timeout ${centralLog} ${start} ${content} 120 Should Be True ${result} Services should be updated after the ingestion of the queue file - Ctn Stop engine + Ctn Stop Engine Ctn Kindly Stop Broker Start_Stop_Engine_Broker_${id} @@ -428,7 +460,7 @@ Start_Stop_Engine_Broker_${id} Ctn Config Broker rrd Ctn Broker Config Flush Log central 0 Ctn Broker Config Log central core debug - Ctn Broker Config Log central processing info + Ctn Broker Config Log central processing debug Ctn Config Broker Sql Output central unified_sql IF ${grpc} Ctn Change Broker Tcp Output To Grpc central @@ -438,7 +470,7 @@ Start_Stop_Engine_Broker_${id} END ${start} Get Current Date Ctn Start Broker - Ctn Start engine + Ctn Start Engine ${content} Create List create feeder central-broker-master-input ${result} Ctn Find In Log With Timeout ${centralLog} ${start} ${content} 60 Should Be True ${result} create feeder not found @@ -446,7 +478,7 @@ Start_Stop_Engine_Broker_${id} Should Be True ${result} no connection between engine and cbd Sleep 5s ${start_stop} Get Current Date - Ctn Stop engine + Ctn Stop Engine ${content} Create List feeder 'central-broker-master-input-1', connection closed ${result} Ctn Find In Log With Timeout ${centralLog} ${start_stop} ${content} 60 Should Be True ${result} connection closed not found @@ -465,17 +497,17 @@ Start_Stop_Broker_Engine_${id} Ctn Config Broker rrd Ctn Broker Config Flush Log central 0 Ctn Broker Config Log central core debug + Ctn Broker Config Log central processing debug IF ${grpc} Ctn Change Broker Tcp Output To Grpc central Ctn Change Broker Tcp Output To Grpc module0 Ctn Change Broker Tcp Input To Grpc central Ctn Change Broker Tcp Input To Grpc rrd END - ${start} Get Current Date - + ${start} Ctn Get Round Current Date Ctn Start Broker - Ctn Start engine + Ctn Start Engine ${content} Create List create feeder central-broker-master-input ${result} Ctn Find In Log With Timeout ${centralLog} ${start} ${content} 60 Should Be True ${result} create feeder not found @@ -485,9 +517,9 @@ Start_Stop_Broker_Engine_${id} ${stop_broker} Get Current Date Ctn Kindly Stop Broker ${content} Create List failover central-module-master-output: connection closed - ${result} Ctn Find In Log With Timeout ${moduleLog0} ${stop_broker} ${content} 60 + ${result} Ctn Find In Log With Timeout ${engineLog0} ${stop_broker} ${content} 60 Should Be True ${result} connection closed not found Examples: id grpc -- ... 1 False ... 2 True - Ctn Stop engine + Ctn Stop Engine diff --git a/tests/broker/bbdo-server-client-reversed.robot b/tests/broker/bbdo-server-client-reversed.robot index 365bceed270..9522259e096 100644 --- a/tests/broker/bbdo-server-client-reversed.robot +++ b/tests/broker/bbdo-server-client-reversed.robot @@ -31,6 +31,7 @@ BSCSSRR1 Ctn Broker Config Output Set central centreon-broker-master-rrd retention yes Ctn Config Broker Bbdo Input rrd bbdo_client 5670 tcp localhost Ctn Broker Config Log central config debug + Ctn Broker Config Log central processing trace ${start} Ctn Get Round Current Date Repeat Keyword 5 times Ctn Start Stop Service 0 ${content} Create List failover 'centreon-broker-master-rrd' construction. @@ -68,6 +69,7 @@ BSCSSGRR1 Ctn Broker Config Output Set central centreon-broker-master-rrd retention yes Ctn Config Broker Bbdo Input rrd bbdo_client 5670 grpc localhost Ctn Broker Config Log central config info + Ctn Broker Config Log central processing trace ${start} Ctn Get Round Current Date Repeat Keyword 5 times Ctn Start Stop Service 0 ${content} Create List diff --git a/tests/broker/command-line.robot b/tests/broker/command-line.robot index 4f3d2d9b2e4..fd5202f76a4 100644 --- a/tests/broker/command-line.robot +++ b/tests/broker/command-line.robot @@ -26,7 +26,7 @@ BCL2 Sleep 1s Ctn Start Broker With Args -s5 ${EtcRoot}/centreon-broker/central-broker.json ${table} Create List Starting the TCP thread pool of 5 threads - ${logger_res} Ctn Find In Log With Timeout /tmp/output.txt ${start} ${table} 30 + ${logger_res} Ctn Find In Log With Timeout ${centralLog} ${start} ${table} 30 Should Be True ... ${logger_res} ... Didn't found 5 threads in ${VarRoot}/log/centreon-broker/central-broker-master.log diff --git a/tests/engine/extended_conf.robot b/tests/engine/extended_conf.robot index 89c5e9e1692..847b69c6d9d 100644 --- a/tests/engine/extended_conf.robot +++ b/tests/engine/extended_conf.robot @@ -20,9 +20,9 @@ EXT_CONF1 Ctn Start Engine With Extend Conf Ctn Wait For Engine To Be Ready ${start} ${1} ${level} Ctn Get Engine Log Level 50001 checks - Should Be Equal ${level} trace log_level_checks must be the extended conf value + Should Be Equal ${level} trace log_level_checks must come from the extended conf, trace ${level} Ctn Get Engine Log Level 50001 comments - Should Be Equal ${level} debug log_level_comments must be the extended conf value + Should Be Equal ${level} debug log_level_comments must come from the extended conf, debug EXT_CONF2 [Documentation] Engine configuration is overided by json conf after reload diff --git a/tests/migration/migration.robot b/tests/migration/migration.robot index b2b39f2fd3f..121171608c3 100644 --- a/tests/migration/migration.robot +++ b/tests/migration/migration.robot @@ -43,7 +43,7 @@ MIGRATION Ctn Start engine Sleep 2s - ${contentCentral} Create List SQL: processing service status event + ${contentCentral} Create List unified_sql: processing service status event ${result} Ctn Find In Log With Timeout ${centralLog} ${start} ${contentCentral} 60 Should Be True ${result} No service status processed by the unified_sql output for 60s ${contentRRD} Create List RRD: output::write @@ -81,7 +81,7 @@ MIGRATION Ctn Start engine Sleep 2s - ${contentCentral} Create List SQL: processing service status event + ${contentCentral} Create List unified_sql: processing service status event ${result} Ctn Find In Log With Timeout ${centralLog} ${start} ${contentCentral} 60 Should Be True ${result} No service status processed by the unified_sql output for 60s ${contentRRD} Create List RRD: output::write diff --git a/tests/resources/Broker.py b/tests/resources/Broker.py index c84d10de90f..71c439f1d2d 100755 --- a/tests/resources/Broker.py +++ b/tests/resources/Broker.py @@ -2516,7 +2516,7 @@ def ctn_check_poller_disabled_in_database(poller_id: int, timeout: int): result = cursor.fetchall() if len(result) == 0: return True - time.sleep(5) + time.sleep(2) return False diff --git a/tests/resources/Common.py b/tests/resources/Common.py index 2e82f3a6d2f..8f8699bbca2 100644 --- a/tests/resources/Common.py +++ b/tests/resources/Common.py @@ -13,7 +13,6 @@ from concurrent import futures import grpc import grpc_stream_pb2_grpc -import grpc_stream_pb2 TIMEOUT = 30 @@ -178,7 +177,7 @@ def ctn_find_regex_in_log_with_timeout(log: str, date, content, timeout: int): limit = time.time() + timeout c = "" while time.time() < limit: - ok, c = ctn_find_in_log(log, date, content, True) + ok, c = ctn_find_in_log(log, date, content, regex=True) if ok: return True, c time.sleep(5) @@ -186,12 +185,13 @@ def ctn_find_regex_in_log_with_timeout(log: str, date, content, timeout: int): return False, c -def ctn_find_in_log_with_timeout(log: str, date, content, timeout: int): - +def ctn_find_in_log_with_timeout(log: str, date, content, timeout: int, **kwargs): limit = time.time() + timeout c = "" + kwargs['regex'] = False + while time.time() < limit: - ok, c = ctn_find_in_log(log, date, content, False) + ok, c = ctn_find_in_log(log, date, content, **kwargs) if ok: return True time.sleep(5) @@ -210,7 +210,7 @@ def ctn_find_in_log_with_timeout_with_line(log: str, date, content, timeout: int limit = time.time() + timeout c = "" while time.time() < limit: - ok, c = ctn_find_in_log(log, date, content, False) + ok, c = ctn_find_in_log(log, date, content, regex=False) if ok: return ok, c time.sleep(5) @@ -218,7 +218,7 @@ def ctn_find_in_log_with_timeout_with_line(log: str, date, content, timeout: int return False, None -def ctn_find_in_log(log: str, date, content, regex=False): +def ctn_find_in_log(log: str, date, content, **kwargs): """Find content in log file from the given date Args: @@ -229,13 +229,18 @@ def ctn_find_in_log(log: str, date, content, regex=False): Returns: boolean,str: The boolean is True on success, and the string contains the first string not found in logs otherwise. """ - logger.info(f"regex={regex}") + verbose = True + regex = False + if 'verbose' in kwargs: + verbose = 'verbose' == 'True' + if 'regex' in kwargs: + regex = bool(kwargs['regex']) + res = [] try: - with open(log, "r", encoding="latin1") as f: + with open(log, "r") as f: lines = f.readlines() - idx = ctn_find_line_from(lines, date) for c in content: @@ -247,7 +252,8 @@ def ctn_find_in_log(log: str, date, content, regex=False): else: match = c in line if match: - logger.console(f"\"{c}\" found at line {i} from {idx}") + if verbose: + logger.console(f"\"{c}\" found at line {i} from {idx}") found = True res.append(line) break @@ -394,6 +400,10 @@ def ctn_clear_retention(): def ctn_clear_cache(): getoutput(f"find {VAR_ROOT} -name '*.cache.*' -delete") +def ctn_clear_logs(): + getoutput(f"rm -rf {VAR_ROOT}/log/centreon-engine/config*") + getoutput(f"rm -rf {VAR_ROOT}/log/centreon-broker") + def ctn_engine_log_table_duplicate(result: list): dup = True diff --git a/tests/resources/Engine.py b/tests/resources/Engine.py index cd45400e11c..f43cf9c0f44 100755 --- a/tests/resources/Engine.py +++ b/tests/resources/Engine.py @@ -3314,7 +3314,7 @@ def ctn_get_engine_log_level(port, log, timeout=TIMEOUT): stub = engine_pb2_grpc.EngineStub(channel) try: logs = stub.GetLogInfo(empty_pb2.Empty()) - return logs.loggers[0].level[log] + return logs.level[log] except: logger.console("gRPC server not ready") diff --git a/tests/resources/resources.resource b/tests/resources/resources.resource index 9b7368b20c9..23a25dd7eb1 100644 --- a/tests/resources/resources.resource +++ b/tests/resources/resources.resource @@ -297,7 +297,7 @@ Ctn Dump Process ${output} Catenate SEPARATOR= /tmp/core- ${name} ${gdb_output} Catenate SEPARATOR= ${failDir} /core- ${name} .txt # Log To Console Creation of core ${output}.${pid} to debug - # Run Process gcore -o ${output} ${pid} + Run Process gcore -o ${output} ${pid} Run Process ... gdb ... -batch @@ -379,6 +379,7 @@ Ctn Wait For Engine To Be Ready ${result} Ctn Find In Log With Timeout ... ${ENGINE_LOG}/config${i}/centengine.log ... ${start} ${content} 60 + ... verbose=False Should Be True ... ${result} ... A message telling check_for_external_commands() should be available in config${i}/centengine.log. diff --git a/tests/resources/specific-duplication.py b/tests/resources/specific-duplication.py index ae05af6ae0c..ade6f3656f6 100644 --- a/tests/resources/specific-duplication.py +++ b/tests/resources/specific-duplication.py @@ -1,23 +1,27 @@ -from robot.api import logger -from subprocess import getoutput -import re import json -import time -from dateutil import parser -from datetime import datetime +import re +from subprocess import getoutput + +from robot.api import logger -## -# @brief Given two files with md5 as rows, this function checks the first list -# contains the same md5 as the second list. There are exceptions in these files -# that's why we need a function to make this test. -# -# @param str The first file name -# @param str The second file name -# -# @return A boolean True on success def ctn_files_contain_same_json(file_e: str, file_b: str): - new_inst = '{"_type": 4294901762, "category": 65535, "element": 2, "broker_id": 1, "broker_name": "", "enabled": True, "poller_id": 1, "poller_name": "Central"}'.upper() + """ + ctn_files_contain_same_json + + Given two files with md5 as rows, this function checks the first list + contains the same md5 as the second list. There are exceptions in these files + that's why we need a function to make this test. + + Args: + file_e (str): The log file produced by Engine + file_b (str): The log file produced by Broker + + Returns: + A boolean that is True on success, False otherwise. + """ + new_inst = '{"_type": 4294901762, "category": 65535, "element": 2, "broker_id": 1, "broker_name": "",' \ + '"enabled": True, "poller_id": 1, "poller_name": "Central"}'.upper() f1 = open(file_e) content1 = f1.readlines() @@ -57,28 +61,32 @@ def ctn_files_contain_same_json(file_e: str, file_b: str): else: js1 = json.loads(c1) js2 = json.loads(c2) - if js2['_type'] == 4294901762: + if js2['_type'] in [4294901762, 131081]: idx2 += 1 continue - if js1['_type'] == 4294901762: + if js1['_type'] in [4294901762, 131081]: idx1 += 1 continue if len(js1) != len(js2): + logger.console(f"Line {idx1} in '{file_e}' and line {idx2} in '{file_b}' do not match, json contents are respectively\n{js1}\n{js2}") return False for k in js1: if isinstance(js1[k], float): if abs(js1[k] - js2[k]) > 0.1: + logger.console( + f"Line {idx1} in '{file_e}' and line {idx2} in '{file_b}' do not match, json contents are respectively\n{js1}\n{js2}") return False else: if js1[k] != js2[k]: + logger.console( + f"Line {idx1} in '{file_e}' and line {idx2} in '{file_b}' do not match, json contents are respectively\n{js1}\n{js2}") return False idx1 += 1 idx2 += 1 retval = idx1 == len(content1) or idx2 == len(content2) if not retval: - logger.console("not at the end of files idx1 = {}/{} or idx2 = {}/{}".format( - idx1, len(content1), idx2, len(content2))) + logger.console(f"not at the end of files idx1 = {idx1}/{len(content1)} or idx2 = {idx2}/{len(content2)}") return False return True @@ -175,17 +183,21 @@ def create_md5_list(content): "In lst2: Bad {} {} with type {:x}".format(k, lst2[k], typ2[k])) return len(res1) == 1 and len(res2) == 1 -## -# @brief Given two files generated by a stream connector, this function checks -# that no events except special ones are sent / replayed twice. -# -# @param str The first file name -# @param str The second file name -# -# @return A boolean True on success +def ctn_check_multiplicity_when_engine_restarted(file1: str, file2: str): + """ + ctn_check_multiplicity_when_engine_restarted + Given two files generated by a stream connector, this function checks + that no events except special ones are sent / replayed twice. + + Args: + str The first file name + str The second file name + + Returns: + A boolean True on success + """ -def ctn_check_multiplicity_when_engine_restarted(file1: str, file2: str): f1 = open(file1) content1 = f1.readlines() f2 = open(file2) @@ -206,6 +218,8 @@ def create_md5_list(content): * modules * host checks (they can be done several times * host and service events are also configuration events, so sent each time engine is restarted. + * local::pb_stop (this one is special and cannot pass through + a network). """ if type not in [65544, # host check 4294901762, # bbdo category @@ -220,7 +234,8 @@ def create_md5_list(content): 0x10025, # pb_custom_variable 0x10027, # pb_host_check 0x10028, # pb_service_check - 0x10036 # pb_instance_configuration + 0x10036, # pb_instance_configuration + 0x90001, # local::pb_stop ]: if md5 in lst: lst[md5] += 1 @@ -244,3 +259,4 @@ def create_md5_list(content): logger.console( "In lst2: Bad {} {} with type {:x}".format(k, lst2[k], typ2[k])) return len(res1) == 1 and len(res2) == 1 + From 85e3674bbc1af85bd7928ec19dbb4e26158f9371 Mon Sep 17 00:00:00 2001 From: jean-christophe81 <98889244+jean-christophe81@users.noreply.github.com> Date: Tue, 28 May 2024 16:46:58 +0200 Subject: [PATCH 15/60] enh(common): grpc server/client moved to common and new otlp message for bbdo. REFS: MON-34002 --- .github/scripts/collect-test-robot.sh | 3 + CMakeLists.txt | 18 +++ bbdo/CMakeLists.txt | 32 ++++++ bbdo/events.hh | 3 + broker/bam/test/monitoring_stream.cc | 18 +-- broker/core/test/mysql/mysql.cc | 29 +++-- broker/grpc/CMakeLists.txt | 10 +- broker/grpc/generate_proto.py | 29 +++++ .../inc/com/centreon/broker/grpc/acceptor.hh | 5 +- .../inc/com/centreon/broker/grpc/connector.hh | 6 +- .../com/centreon/broker/grpc/grpc_config.hh | 58 +++------- broker/grpc/src/acceptor.cc | 68 ++---------- broker/grpc/src/connector.cc | 64 ++--------- broker/grpc/src/factory.cc | 16 +-- broker/grpc/test/acceptor.cc | 8 +- broker/grpc/test/stream_test.cc | 27 +++-- broker/lua/src/broker_utils.cc | 20 ++++ broker/neb/CMakeLists.txt | 12 +- .../inc/com/centreon/broker/neb/callbacks.hh | 2 + .../inc/com/centreon/broker/neb/internal.hh | 5 + broker/neb/src/broker.cc | 4 +- broker/neb/src/callbacks.cc | 58 +++++++++- broker/test/CMakeLists.txt | 2 + broker/victoria_metrics/src/factory.cc | 2 +- common/CMakeLists.txt | 1 + common/doc/common-doc.md | 42 +++++++ common/grpc/CMakeLists.txt | 37 +++++++ .../com/centreon/common/grpc/grpc_client.hh | 48 ++++++++ .../com/centreon/common/grpc/grpc_config.hh | 94 ++++++++++++++++ .../com/centreon/common/grpc/grpc_server.hh | 58 ++++++++++ common/grpc/src/grpc_client.cc | 83 ++++++++++++++ common/grpc/src/grpc_server.cc | 103 ++++++++++++++++++ common/src/hex_dump.cc | 33 +++--- engine/CMakeLists.txt | 1 + .../inc/com/centreon/engine/nebcallbacks.hh | 3 +- .../modules/external_commands/CMakeLists.txt | 2 +- tests/README.md | 11 ++ tests/init-proto.sh | 9 +- tests/update-doc.py | 11 ++ 39 files changed, 796 insertions(+), 239 deletions(-) create mode 100644 common/grpc/CMakeLists.txt create mode 100644 common/grpc/inc/com/centreon/common/grpc/grpc_client.hh create mode 100644 common/grpc/inc/com/centreon/common/grpc/grpc_config.hh create mode 100644 common/grpc/inc/com/centreon/common/grpc/grpc_server.hh create mode 100644 common/grpc/src/grpc_client.cc create mode 100644 common/grpc/src/grpc_server.cc diff --git a/.github/scripts/collect-test-robot.sh b/.github/scripts/collect-test-robot.sh index fae6945272a..5f78ed1a907 100755 --- a/.github/scripts/collect-test-robot.sh +++ b/.github/scripts/collect-test-robot.sh @@ -62,6 +62,9 @@ echo '/tmp/core.%p' > /proc/sys/kernel/core_pattern #remove git dubious ownership /usr/bin/git config --global --add safe.directory $PWD +echo "###### git clone opentelemetry-proto #######" +git clone --depth=1 --single-branch https://github.com/open-telemetry/opentelemetry-proto.git opentelemetry-proto + echo "##### Starting tests #####" cd tests ./init-proto.sh diff --git a/CMakeLists.txt b/CMakeLists.txt index 29a44ba4e79..22f208b6765 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -178,6 +178,24 @@ set(OTLP_LIB_DIR ${opentelemetry-cpp_DIR}/../../lib) set(VCPKG_INCLUDE_DIR ${Protobuf_INCLUDE_DIR}) include(GNUInstallDirs) +#import opentelemetry-proto +add_custom_command( + OUTPUT ${CMAKE_SOURCE_DIR}/opentelemetry-proto/opentelemetry/proto/collector/metrics/v1/metrics_service.proto + ${CMAKE_SOURCE_DIR}/opentelemetry-proto/opentelemetry/proto/metrics/v1/metrics.proto + ${CMAKE_SOURCE_DIR}/opentelemetry-proto/opentelemetry/proto/common/v1/common.proto + ${CMAKE_SOURCE_DIR}/opentelemetry-proto/opentelemetry/proto/resource/v1/resource.proto + COMMENT "get opentelemetry proto files from git repository" + COMMAND /bin/rm -rf ${CMAKE_SOURCE_DIR}/opentelemetry-proto + COMMAND git ARGS clone --depth=1 --single-branch https://github.com/open-telemetry/opentelemetry-proto.git ${CMAKE_SOURCE_DIR}/opentelemetry-proto + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} +) + +add_custom_target(opentelemetry-proto-files DEPENDS ${CMAKE_SOURCE_DIR}/opentelemetry-proto/opentelemetry/proto/collector/metrics/v1/metrics_service.proto + ${CMAKE_SOURCE_DIR}/opentelemetry-proto/opentelemetry/proto/metrics/v1/metrics.proto + ${CMAKE_SOURCE_DIR}/opentelemetry-proto/opentelemetry/proto/common/v1/common.proto + ${CMAKE_SOURCE_DIR}/opentelemetry-proto/opentelemetry/proto/resource/v1/resource.proto +) + # var directories. set(BROKER_VAR_LOG_DIR "${CMAKE_INSTALL_FULL_LOCALSTATEDIR}/log/centreon-broker") diff --git a/bbdo/CMakeLists.txt b/bbdo/CMakeLists.txt index 17eded04020..0bab457aa4e 100644 --- a/bbdo/CMakeLists.txt +++ b/bbdo/CMakeLists.txt @@ -92,6 +92,38 @@ add_dependencies(pb_remove_graph_message_lib target_remove_graph_message set_target_properties(pb_remove_graph_message_lib PROPERTIES POSITION_INDEPENDENT_CODE ON) +set(otl_protobuf_files + opentelemetry/proto/collector/metrics/v1/metrics_service + opentelemetry/proto/metrics/v1/metrics + opentelemetry/proto/common/v1/common + opentelemetry/proto/resource/v1/resource +) +foreach(name IN LISTS otl_protobuf_files) + set(proto_file "${name}.proto") + add_custom_command( + OUTPUT "${CMAKE_SOURCE_DIR}/bbdo/${name}.pb.cc" + COMMENT "Generating interface files of the otl file ${proto_file}" + #DEPENDS ${CMAKE_BINARY_DIR}/opentelemetry-proto/${proto_file} + DEPENDS opentelemetry-proto-files + COMMAND + ${Protobuf_PROTOC_EXECUTABLE} ARGS --cpp_out=${CMAKE_SOURCE_DIR}/bbdo + --proto_path=${CMAKE_SOURCE_DIR}/opentelemetry-proto ${proto_file} + VERBATIM) +endforeach() + +add_library(pb_open_telemetry_lib STATIC +${CMAKE_SOURCE_DIR}/bbdo/opentelemetry/proto/collector/metrics/v1/metrics_service.pb.cc +${CMAKE_SOURCE_DIR}/bbdo/opentelemetry/proto/metrics/v1/metrics.pb.cc +${CMAKE_SOURCE_DIR}/bbdo/opentelemetry/proto/common/v1/common.pb.cc +${CMAKE_SOURCE_DIR}/bbdo/opentelemetry/proto/resource/v1/resource.pb.cc +) + +target_include_directories(pb_open_telemetry_lib BEFORE PRIVATE ${CMAKE_SOURCE_DIR}/bbdo) + + +set_target_properties(pb_open_telemetry_lib + PROPERTIES POSITION_INDEPENDENT_CODE ON) + macro(get_protobuf_files name) set_source_files_properties("${CMAKE_SOURCE_DIR}/bbdo/${name}.pb.cc" PROPERTIES GENERATED TRUE) diff --git a/bbdo/events.hh b/bbdo/events.hh index f9431348003..5e392018328 100644 --- a/bbdo/events.hh +++ b/bbdo/events.hh @@ -169,6 +169,9 @@ enum data_element { de_pb_status = 10, de_pb_index_mapping = 11, de_pb_metric_mapping = 12, + de_pb_otl_metrics = + 13 // contain an + // ::opentelemetry::proto::collector::metrics::v1::ExportMetricsServiceRequest }; } namespace bam { diff --git a/broker/bam/test/monitoring_stream.cc b/broker/bam/test/monitoring_stream.cc index 1c9b0e64d04..51fadfc5e95 100644 --- a/broker/bam/test/monitoring_stream.cc +++ b/broker/bam/test/monitoring_stream.cc @@ -24,14 +24,14 @@ #include "com/centreon/broker/config/applier/init.hh" #include "com/centreon/broker/multiplexing/engine.hh" #include "com/centreon/broker/neb/acknowledgement.hh" +#include "common/log_v2/log_v2.hh" +using log_v2 = com::centreon::common::log_v2::log_v2; using namespace com::centreon::broker; using namespace com::centreon::broker::bam; class BamMonitoringStream : public testing::Test { - void SetUp() override { - config::applier::init(0, "test_broker", 0); - } + void SetUp() override { config::applier::init(0, "test_broker", 0); } void TearDown() override { config::applier::deinit(); } }; @@ -44,7 +44,8 @@ TEST_F(BamMonitoringStream, WriteKpi) { std::shared_ptr cache; std::unique_ptr ms; - ASSERT_NO_THROW(ms.reset(new monitoring_stream("", cfg, storage, cache))); + ASSERT_NO_THROW(ms.reset(new monitoring_stream( + "", cfg, storage, cache, log_v2::instance().get(log_v2::BAM)))); std::shared_ptr st{std::make_shared()}; st->mut_obj().set_kpi_id(1); @@ -61,7 +62,8 @@ TEST_F(BamMonitoringStream, WriteBA) { std::shared_ptr cache; std::unique_ptr ms; - ASSERT_NO_THROW(ms.reset(new monitoring_stream("", cfg, storage, cache))); + ASSERT_NO_THROW(ms.reset(new monitoring_stream( + "", cfg, storage, cache, log_v2::instance().get(log_v2::BAM)))); std::shared_ptr st{std::make_shared(ba_status())}; @@ -77,7 +79,8 @@ TEST_F(BamMonitoringStream, WorkWithNoPendigMysqlRequest) { std::shared_ptr cache; std::unique_ptr ms; - ASSERT_NO_THROW(ms.reset(new monitoring_stream("", cfg, storage, cache))); + ASSERT_NO_THROW(ms.reset(new monitoring_stream( + "", cfg, storage, cache, log_v2::instance().get(log_v2::BAM)))); std::shared_ptr st{std::make_shared(ba_status())}; @@ -98,7 +101,8 @@ TEST_F(BamMonitoringStream, WorkWithPendigMysqlRequest) { std::shared_ptr cache; std::unique_ptr ms; - ASSERT_NO_THROW(ms.reset(new monitoring_stream("", cfg, storage, cache))); + ASSERT_NO_THROW(ms.reset(new monitoring_stream( + "", cfg, storage, cache, log_v2::instance().get(log_v2::BAM)))); std::shared_ptr st{std::make_shared(ba_status())}; diff --git a/broker/core/test/mysql/mysql.cc b/broker/core/test/mysql/mysql.cc index 879d06f71ed..bfba10674d2 100644 --- a/broker/core/test/mysql/mysql.cc +++ b/broker/core/test/mysql/mysql.cc @@ -25,7 +25,6 @@ #include "com/centreon/broker/config/applier/init.hh" #include "com/centreon/broker/config/applier/modules.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/neb/custom_variable.hh" #include "com/centreon/broker/neb/downtime.hh" #include "com/centreon/broker/neb/host.hh" @@ -44,10 +43,12 @@ #include "com/centreon/broker/sql/mysql_multi_insert.hh" #include "com/centreon/broker/sql/query_preparator.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using msg_fmt = com::centreon::exceptions::msg_fmt; using namespace com::centreon::broker; using namespace com::centreon::broker::database; +using log_v2 = com::centreon::common::log_v2::log_v2; class DatabaseStorageTest : public ::testing::Test { public: @@ -503,7 +504,7 @@ TEST_F(DatabaseStorageTest, ConnectionOk) { // } // TEST_F(DatabaseStorageTest, CustomVarStatement) { - config::applier::modules modules; + config::applier::modules modules(log_v2::instance().get(log_v2::SQL)); modules.load_file("./broker/neb/10-neb.so"); database_config db_cfg("MySQL", "127.0.0.1", MYSQL_SOCKET, 3306, "root", "centreon", "centreon_storage", 5, true, 5); @@ -2078,7 +2079,7 @@ TEST_F(DatabaseStorageTest, MySqlMultiInsert) { ms->commit(); std::chrono::system_clock::time_point end_insert = std::chrono::system_clock::now(); - SPDLOG_LOGGER_INFO(log_v2::sql(), + SPDLOG_LOGGER_INFO(log_v2::instance().get(log_v2::SQL), " insert {} rows in {} requests duration: {} seconds", data_index, nb_request, std::chrono::duration_cast( @@ -2128,7 +2129,7 @@ TEST_F(DatabaseStorageTest, MySqlMultiInsert) { nb_request = inserter2.execute_queries(*ms); ms->commit(); end_insert = std::chrono::system_clock::now(); - SPDLOG_LOGGER_INFO(log_v2::sql(), + SPDLOG_LOGGER_INFO(log_v2::instance().get(log_v2::SQL), " insert {} rows in {} requests duration: {} seconds", data_index, nb_request, std::chrono::duration_cast( @@ -2218,10 +2219,12 @@ TEST_F(DatabaseStorageTest, bulk_or_multi_bbdo_event_bulk) { inserter->execute(*ms); ms->commit(); - log_v2::sql()->info("100000 rows inserted in {} ms", - std::chrono::duration_cast( - std::chrono::system_clock::now() - begin) - .count()); + log_v2::instance() + .get(log_v2::SQL) + ->info("100000 rows inserted in {} ms", + std::chrono::duration_cast( + std::chrono::system_clock::now() - begin) + .count()); std::promise select_prom; std::future select_fut = select_prom.get_future(); @@ -2269,10 +2272,12 @@ TEST_F(DatabaseStorageTest, bulk_or_multi_bbdo_event_multi) { inserter->execute(*ms); ms->commit(); - log_v2::sql()->info("100000 rows inserted in {} ms", - std::chrono::duration_cast( - std::chrono::system_clock::now() - begin) - .count()); + log_v2::instance() + .get(log_v2::SQL) + ->info("100000 rows inserted in {} ms", + std::chrono::duration_cast( + std::chrono::system_clock::now() - begin) + .count()); std::promise select_prom; std::future select_fut = select_prom.get_future(); diff --git a/broker/grpc/CMakeLists.txt b/broker/grpc/CMakeLists.txt index 4e8a7fd65dd..2dd00ce8935 100644 --- a/broker/grpc/CMakeLists.txt +++ b/broker/grpc/CMakeLists.txt @@ -21,7 +21,11 @@ set(MODULE_DIR "${PROJECT_SOURCE_DIR}/grpc") set(INC_DIR "${MODULE_DIR}/inc/com/centreon/broker/grpc") set(SRC_DIR "${MODULE_DIR}/src") set(TEST_DIR "${MODULE_DIR}/test") -include_directories(${MODULE_DIR}/inc ${SRC_DIR} ${CMAKE_SOURCE_DIR}/bbdo ${CMAKE_SOURCE_DIR}/common) +include_directories(${MODULE_DIR}/inc + ${SRC_DIR} + ${CMAKE_SOURCE_DIR}/bbdo + ${CMAKE_SOURCE_DIR}/common + ${CMAKE_SOURCE_DIR}/common/grpc/inc) # Sources. set(SOURCES @@ -43,6 +47,7 @@ add_library(${GRPC} SHARED ${SOURCES} ) set_target_properties(${GRPC} PROPERTIES PREFIX "") target_link_libraries( ${GRPC} + centreon_grpc "-Wl,--whole-archive" pb_neb_lib pb_storage_lib @@ -51,6 +56,7 @@ target_link_libraries( pb_tag_lib pb_bam_lib pb_extcmd_lib + pb_open_telemetry_lib pb_rebuild_message_lib pb_remove_graph_message_lib pb_header_lib @@ -81,6 +87,7 @@ add_custom_command( COMMAND ${Protobuf_PROTOC_EXECUTABLE} ARGS --cpp_out=${SRC_DIR} --proto_path=${MODULE_DIR} --proto_path=${CMAKE_SOURCE_DIR}/bbdo + --proto_path=${CMAKE_SOURCE_DIR}/opentelemetry-proto grpc_stream.proto VERBATIM) @@ -92,6 +99,7 @@ add_custom_command( ${Protobuf_PROTOC_EXECUTABLE} ARGS --grpc_out=${SRC_DIR} --plugin=protoc-gen-grpc=${GRPC_CPP_PLUGIN} --proto_path=${MODULE_DIR} --proto_path=${CMAKE_SOURCE_DIR}/bbdo + --proto_path=${CMAKE_SOURCE_DIR}/opentelemetry-proto grpc_stream.proto VERBATIM WORKING_DIRECTORY ${CMAKE_BINARY_DIR}) diff --git a/broker/grpc/generate_proto.py b/broker/grpc/generate_proto.py index 8bd044ddb9e..d681e223b9a 100755 --- a/broker/grpc/generate_proto.py +++ b/broker/grpc/generate_proto.py @@ -25,6 +25,7 @@ file_begin_content = """syntax = "proto3"; +import "opentelemetry/proto/collector/metrics/v1/metrics_service.proto"; """ file_message_centreon_event = """ @@ -218,6 +219,34 @@ class received_protobuf : public io::protobuf { """ +#The following message is not in bbdo protobuff files so we need to add manually. + +file_message_centreon_event += f" opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest ExportMetricsServiceRequest_ = {one_of_index};\n" + +cc_file_protobuf_to_event_function += """ + case ::stream::CentreonEvent::kExportMetricsServiceRequest: + return std::make_shared>( + stream_content, &grpc_event_type::exportmetricsservicerequest_, + &grpc_event_type::mutable_exportmetricsservicerequest_); +""" + +cc_file_create_event_with_data_function += """ + case make_type(io::storage, storage::de_pb_otl_metrics): + ret = std::make_shared( + event, reinterpret_cast( + &grpc_event_type::release_exportmetricsservicerequest_)); + ret->grpc_event.set_allocated_exportmetricsservicerequest_( + &std::static_pointer_cast>(event) + ->mut_obj()); + break; +""" + with open(args.proto_file, 'w', encoding="utf-8") as fp: fp.write(file_begin_content) fp.write(""" diff --git a/broker/grpc/inc/com/centreon/broker/grpc/acceptor.hh b/broker/grpc/inc/com/centreon/broker/grpc/acceptor.hh index f130c25766c..b9382370025 100644 --- a/broker/grpc/inc/com/centreon/broker/grpc/acceptor.hh +++ b/broker/grpc/inc/com/centreon/broker/grpc/acceptor.hh @@ -20,6 +20,7 @@ #define CCB_GRPC_ACCEPTOR_HH #include "com/centreon/broker/io/endpoint.hh" +#include "com/centreon/common/grpc/grpc_server.hh" #include "grpc_config.hh" namespace com::centreon::broker::grpc { @@ -60,9 +61,9 @@ class service_impl void unregister(const std::shared_ptr& to_unregister); }; -class acceptor : public io::endpoint { +class acceptor : public io::endpoint, + public com::centreon::common::grpc::grpc_server_base { std::shared_ptr _service; - std::unique_ptr<::grpc::Server> _server; public: acceptor(const grpc_config::pointer& conf); diff --git a/broker/grpc/inc/com/centreon/broker/grpc/connector.hh b/broker/grpc/inc/com/centreon/broker/grpc/connector.hh index 3ce464ae6b8..bcdeb4ec663 100644 --- a/broker/grpc/inc/com/centreon/broker/grpc/connector.hh +++ b/broker/grpc/inc/com/centreon/broker/grpc/connector.hh @@ -20,14 +20,14 @@ #define CCB_GRPC_CONNECTOR_HH #include "com/centreon/broker/io/limit_endpoint.hh" +#include "com/centreon/common/grpc/grpc_client.hh" #include "grpc_config.hh" namespace com::centreon::broker { namespace grpc { -class connector : public io::limit_endpoint { - grpc_config::pointer _conf; - std::shared_ptr<::grpc::Channel> _channel; +class connector : public io::limit_endpoint, + public com::centreon::common::grpc::grpc_client_base { std::unique_ptr _stub; public: diff --git a/broker/grpc/inc/com/centreon/broker/grpc/grpc_config.hh b/broker/grpc/inc/com/centreon/broker/grpc/grpc_config.hh index bbdebd8a45b..d773c1ea823 100644 --- a/broker/grpc/inc/com/centreon/broker/grpc/grpc_config.hh +++ b/broker/grpc/inc/com/centreon/broker/grpc/grpc_config.hh @@ -19,20 +19,12 @@ #ifndef CCB_GRPC_CONFIG_HH #define CCB_GRPC_CONFIG_HH -namespace com::centreon::broker { +#include "com/centreon/common/grpc/grpc_config.hh" -namespace grpc { -class grpc_config { - public: - enum compression_active { NO = 0, AUTO = 1, YES = 2 }; +namespace com::centreon::broker::grpc { - private: - const std::string _hostport; - const bool _crypted = false; - const std::string _certificate, _cert_key, _ca_cert, _authorization; - const std::string _ca_name; - const compression_active _compress; - const int _second_keepalive_interval; +class grpc_config : public com::centreon::common::grpc::grpc_config { + const std::string _authorization; /** * @brief when _grpc_serialized is set, bbdo events are sent on the wire * without bbdo stream serialization @@ -43,14 +35,9 @@ class grpc_config { public: using pointer = std::shared_ptr; - grpc_config() - : _compress(NO), - _second_keepalive_interval(30), - _grpc_serialized(false) {} + grpc_config() : _grpc_serialized(false) {} grpc_config(const std::string& hostp) - : _hostport(hostp), - _compress(NO), - _second_keepalive_interval(30), + : com::centreon::common::grpc::grpc_config(hostp), _grpc_serialized(false) {} grpc_config(const std::string& hostp, bool crypted, @@ -59,37 +46,26 @@ class grpc_config { const std::string& ca_cert, const std::string& authorization, const std::string& ca_name, - compression_active compression, + bool compression, int second_keepalive_interval, bool grpc_serialized) - : _hostport(hostp), - _crypted(crypted), - _certificate(certificate), - _cert_key(cert_key), - _ca_cert(ca_cert), + : com::centreon::common::grpc::grpc_config(hostp, + crypted, + certificate, + cert_key, + ca_cert, + ca_name, + compression, + second_keepalive_interval), _authorization(authorization), - _ca_name(ca_name), - _compress(compression), - _second_keepalive_interval(second_keepalive_interval), _grpc_serialized(grpc_serialized) {} - constexpr const std::string& get_hostport() const { return _hostport; } - constexpr bool is_crypted() const { return _crypted; } - constexpr const std::string& get_cert() const { return _certificate; } - constexpr const std::string& get_key() const { return _cert_key; } - constexpr const std::string& get_ca() const { return _ca_cert; } constexpr const std::string& get_authorization() const { return _authorization; } - const std::string& get_ca_name() const { return _ca_name; } - constexpr compression_active get_compression() const { return _compress; } constexpr bool get_grpc_serialized() const { return _grpc_serialized; } - - int get_second_keepalive_interval() const { - return _second_keepalive_interval; - } }; -}; // namespace grpc -} // namespace com::centreon::broker + +} // namespace com::centreon::broker::grpc #endif // !CCB_GRPC_CONFIG_HH diff --git a/broker/grpc/src/acceptor.cc b/broker/grpc/src/acceptor.cc index a7bf6239bfe..be32e89be90 100644 --- a/broker/grpc/src/acceptor.cc +++ b/broker/grpc/src/acceptor.cc @@ -243,57 +243,14 @@ void service_impl::unregister( */ acceptor::acceptor(const grpc_config::pointer& conf) : io::endpoint(true, _grpc_stream_filter, _grpc_forbidden_filter), - _service(std::make_shared(conf)) { - ::grpc::ServerBuilder builder; - - auto logger = log_v2::instance().get(log_v2::GRPC); - std::shared_ptr<::grpc::ServerCredentials> server_creds; - if (conf->is_crypted() && !conf->get_cert().empty() && - !conf->get_key().empty()) { - ::grpc::SslServerCredentialsOptions::PemKeyCertPair pkcp = { - conf->get_key(), conf->get_cert()}; - - SPDLOG_LOGGER_INFO( - logger, - "encrypted server listening on {} cert: {}..., key: {}..., ca: {}....", - conf->get_hostport(), conf->get_cert().substr(0, 10), - conf->get_key().substr(0, 10), conf->get_ca().substr(0, 10)); - - ::grpc::SslServerCredentialsOptions ssl_opts; - ssl_opts.pem_root_certs = conf->get_ca(); - ssl_opts.pem_key_cert_pairs.push_back(pkcp); - - server_creds = ::grpc::SslServerCredentials(ssl_opts); - } else { - SPDLOG_LOGGER_INFO(logger, "unencrypted server listening on {}", - conf->get_hostport()); - server_creds = ::grpc::InsecureServerCredentials(); - } - builder.AddListeningPort(conf->get_hostport(), server_creds); - builder.RegisterService(_service.get()); - builder.AddChannelArgument(GRPC_ARG_KEEPALIVE_PERMIT_WITHOUT_CALLS, 1); - builder.AddChannelArgument(GRPC_ARG_KEEPALIVE_TIME_MS, - conf->get_second_keepalive_interval() * 1000); - builder.AddChannelArgument(GRPC_ARG_KEEPALIVE_TIMEOUT_MS, - conf->get_second_keepalive_interval() * 300); - builder.AddChannelArgument(GRPC_ARG_HTTP2_MAX_PING_STRIKES, 0); - builder.AddChannelArgument(GRPC_ARG_HTTP2_MAX_PINGS_WITHOUT_DATA, 0); - builder.AddChannelArgument( - GRPC_ARG_HTTP2_MIN_RECV_PING_INTERVAL_WITHOUT_DATA_MS, 60000); - - if (conf->get_compression() == grpc_config::YES) { - grpc_compression_algorithm algo = grpc_compression_algorithm_for_level( - GRPC_COMPRESS_LEVEL_HIGH, calc_accept_all_compression_mask()); - const char* algo_name; - if (grpc_compression_algorithm_name(algo, &algo_name)) - SPDLOG_LOGGER_DEBUG(logger, "server default compression {}", algo_name); - else - SPDLOG_LOGGER_DEBUG(logger, "server default compression unknown"); - - builder.SetDefaultCompressionAlgorithm(algo); - builder.SetDefaultCompressionLevel(GRPC_COMPRESS_LEVEL_HIGH); - } - _server = std::move(builder.BuildAndStart()); + com::centreon::common::grpc::grpc_server_base( + conf, + log_v2::instance().get(log_v2::GRPC)) { + _init([this](::grpc::ServerBuilder& builder) { + _service = std::make_shared( + std::static_pointer_cast(get_conf())); + builder.RegisterService(_service.get()); + }); } /** @@ -301,15 +258,12 @@ acceptor::acceptor(const grpc_config::pointer& conf) * */ acceptor::~acceptor() { - auto logger = log_v2::instance().get(log_v2::GRPC); - if (_server) { - SPDLOG_LOGGER_DEBUG(logger, "begin shutdown of acceptor {} ", + if (initialized()) { + SPDLOG_LOGGER_DEBUG(get_logger(), "begin shutdown of acceptor {} ", _service->get_conf()->get_hostport()); _service->shutdown_all_wait(); _service->shutdown_all_accepted(); - _server->Shutdown(std::chrono::system_clock::now() + - std::chrono::seconds(15)); - SPDLOG_LOGGER_DEBUG(logger, "end shutdown of acceptor {} ", + SPDLOG_LOGGER_DEBUG(get_logger(), "end shutdown of acceptor {} ", _service->get_conf()->get_hostport()); } } diff --git a/broker/grpc/src/connector.cc b/broker/grpc/src/connector.cc index 4a2d835873d..bf484f468eb 100644 --- a/broker/grpc/src/connector.cc +++ b/broker/grpc/src/connector.cc @@ -44,54 +44,9 @@ static constexpr multiplexing::muxer_filter _grpc_forbidden_filter = */ connector::connector(const grpc_config::pointer& conf) : io::limit_endpoint(false, _grpc_stream_filter, _grpc_forbidden_filter), - _conf(conf) { - auto logger = log_v2::instance().get(log_v2::GRPC); - ::grpc::ChannelArguments args; - args.SetInt(GRPC_ARG_KEEPALIVE_PERMIT_WITHOUT_CALLS, 1); - args.SetInt(GRPC_ARG_KEEPALIVE_TIME_MS, - conf->get_second_keepalive_interval() * 1000); - args.SetInt(GRPC_ARG_KEEPALIVE_TIMEOUT_MS, - conf->get_second_keepalive_interval() * 300); - args.SetInt(GRPC_ARG_HTTP2_MAX_PINGS_WITHOUT_DATA, 0); - if (!conf->get_ca_name().empty()) - args.SetString(GRPC_SSL_TARGET_NAME_OVERRIDE_ARG, conf->get_ca_name()); - if (conf->get_compression() == grpc_config::YES) { - grpc_compression_algorithm algo = grpc_compression_algorithm_for_level( - GRPC_COMPRESS_LEVEL_HIGH, calc_accept_all_compression_mask()); - - const char* algo_name; - if (grpc_compression_algorithm_name(algo, &algo_name)) { - logger->debug("client this={:p} activate compression {}", - static_cast(this), algo_name); - } else { - logger->debug("client this={:p} activate compression unknown", - static_cast(this)); - } - args.SetCompressionAlgorithm(algo); - } - std::shared_ptr<::grpc::ChannelCredentials> creds; - if (conf->is_crypted()) { - ::grpc::SslCredentialsOptions ssl_opts = {conf->get_ca(), conf->get_key(), - conf->get_cert()}; - SPDLOG_LOGGER_INFO( - logger, "encrypted connection to {} cert: {}..., key: {}..., ca: {}...", - conf->get_hostport(), conf->get_cert().substr(0, 10), - conf->get_key().substr(0, 10), conf->get_ca().substr(0, 10)); - creds = ::grpc::SslCredentials(ssl_opts); -#ifdef CAN_USE_JWT - if (!_conf->get_jwt().empty()) { - std::shared_ptr<::grpc::CallCredentials> jwt = - ::grpc::ServiceAccountJWTAccessCredentials(_conf->get_jwt(), 86400); - creds = ::grpc::CompositeChannelCredentials(creds, jwt); - } -#endif - } else { - SPDLOG_LOGGER_INFO(logger, "unencrypted connection to {}", - conf->get_hostport()); - creds = ::grpc::InsecureChannelCredentials(); - } - - _channel = ::grpc::CreateCustomChannel(conf->get_hostport(), creds, args); + com::centreon::common::grpc::grpc_client_base( + conf, + log_v2::instance().get(log_v2::GRPC)) { _stub = std::move( com::centreon::broker::stream::centreon_bbdo::NewStub(_channel)); } @@ -102,14 +57,15 @@ connector::connector(const grpc_config::pointer& conf) * @return std::unique_ptr */ std::shared_ptr connector::open() { - auto logger = log_v2::instance().get(log_v2::GRPC); - SPDLOG_LOGGER_INFO(logger, "Connecting to {}", _conf->get_hostport()); + SPDLOG_LOGGER_INFO(get_logger(), "Connecting to {}", + get_conf()->get_hostport()); try { return limit_endpoint::open(); } catch (const std::exception& e) { SPDLOG_LOGGER_DEBUG( - logger, "Unable to establish the connection to {} (attempt {}): {}", - _conf->get_hostport(), _is_ready_count, e.what()); + get_logger(), + "Unable to establish the connection to {} (attempt {}): {}", + get_conf()->get_hostport(), _is_ready_count, e.what()); return nullptr; } } @@ -166,8 +122,8 @@ void client_stream::shutdown() { * @return std::unique_ptr */ std::shared_ptr connector::create_stream() { - std::shared_ptr new_stream = - std::make_shared(_conf); + std::shared_ptr new_stream = std::make_shared( + std::static_pointer_cast(get_conf())); client_stream::register_stream(new_stream); _stub->async()->exchange(&new_stream->get_context(), new_stream.get()); new_stream->start_read(); diff --git a/broker/grpc/src/factory.cc b/broker/grpc/src/factory.cc index 7631f2b339f..edb576739fe 100644 --- a/broker/grpc/src/factory.cc +++ b/broker/grpc/src/factory.cc @@ -209,12 +209,6 @@ io::endpoint* factory::new_endpoint( if (it != cfg.params.end() && !strcasecmp(it->second.c_str(), "yes")) compression = true; - grpc_config::compression_active enable_compression; - if (cfg.get_io_type() == config::endpoint::output) - enable_compression = compression ? grpc_config::YES : grpc_config::NO; - else - enable_compression = grpc_config::AUTO; - // keepalive conf int keepalive_interval = 30; it = cfg.params.find("keepalive_interval"); @@ -243,7 +237,7 @@ io::endpoint* factory::new_endpoint( grpc_config::pointer conf(std::make_shared( hostport, encrypted, certificate, certificate_key, certificate_authority, - authorization, ca_name, enable_compression, keepalive_interval, + authorization, ca_name, compression, keepalive_interval, direct_grpc_serialized(cfg))); std::unique_ptr endp; @@ -439,12 +433,6 @@ io::endpoint* factory::_new_endpoint_bbdo_cs( it->second); } - grpc_config::compression_active enable_compression; - if (cfg.get_io_type() == config::endpoint::output) - enable_compression = compression ? grpc_config::YES : grpc_config::NO; - else - enable_compression = grpc_config::AUTO; - bool enable_retention = false; it = cfg.params.find("retention"); if (it != cfg.params.end()) { @@ -481,7 +469,7 @@ io::endpoint* factory::_new_endpoint_bbdo_cs( grpc_config::pointer conf(std::make_shared( hostport, encryption, certificate, private_key, ca_certificate, - authorization, ca_name, enable_compression, keepalive_interval, + authorization, ca_name, compression, keepalive_interval, direct_grpc_serialized(cfg))); // Acceptor. diff --git a/broker/grpc/test/acceptor.cc b/broker/grpc/test/acceptor.cc index 5737d9cae2e..52d1faf06db 100644 --- a/broker/grpc/test/acceptor.cc +++ b/broker/grpc/test/acceptor.cc @@ -74,7 +74,7 @@ TEST_F(GrpcTlsTest, TlsStream) { auto conf{std::make_shared( "0.0.0.0:4141", true, read_file("/tmp/server.crt"), read_file("/tmp/server.key"), read_file("/tmp/client.crt"), "", - "centreon", grpc_config::NO, 30, false)}; + "centreon", false, 30, false)}; auto a{std::make_unique(conf)}; /* Nominal case, cbd is acceptor and read on the socket */ @@ -106,7 +106,7 @@ TEST_F(GrpcTlsTest, TlsStream) { auto conf{std::make_shared( fmt::format("{}:4141", hostname), true, read_file("/tmp/client.crt"), read_file("/tmp/client.key"), read_file("/tmp/server.crt"), "", "", - grpc_config::NO, 30, false)}; + false, 30, false)}; auto c{std::make_unique(conf)}; /* Nominal case, centengine is connector and write on the socket */ @@ -158,7 +158,7 @@ TEST_F(GrpcTlsTest, TlsStreamBadCaHostname) { auto conf{std::make_shared( "0.0.0.0:4141", true, read_file("/tmp/server.crt"), read_file("/tmp/server.key"), read_file("/tmp/client.crt"), "", - "centreon", grpc_config::NO, 30, false)}; + "centreon", false, 30, false)}; auto a{std::make_unique(conf)}; /* Nominal case, cbd is acceptor and read on the socket */ @@ -173,7 +173,7 @@ TEST_F(GrpcTlsTest, TlsStreamBadCaHostname) { auto conf{std::make_shared( "localhost:4141", true, read_file("/tmp/client.crt"), read_file("/tmp/client.key"), read_file("/tmp/server.crt"), "", - "bad_name", grpc_config::NO, 30, false)}; + "bad_name", false, 30, false)}; auto c{std::make_unique(conf)}; /* Nominal case, centengine is connector and write on the socket */ diff --git a/broker/grpc/test/stream_test.cc b/broker/grpc/test/stream_test.cc index 400a9b9cea6..abd7c061b54 100644 --- a/broker/grpc/test/stream_test.cc +++ b/broker/grpc/test/stream_test.cc @@ -30,17 +30,16 @@ using namespace com::centreon::exceptions; using com::centreon::common::log_v2::log_v2; com::centreon::broker::grpc::grpc_config::pointer conf( - std::make_shared( - "127.0.0.1:4444", - false, - "", - "", - "", - "my_aut", - "", - com::centreon::broker::grpc::grpc_config::NO, - 30, - false)); + std::make_shared("127.0.0.1:4444", + false, + "", + "", + "", + "my_aut", + "", + false, + 30, + false)); static constexpr unsigned relay_listen_port = 5123u; static constexpr unsigned server_listen_port = 5124u; @@ -375,7 +374,7 @@ com::centreon::broker::grpc::grpc_config::pointer conf_crypted_server1234( read_file("tests/grpc_test_keys/ca_1234.crt"), "my_auth", "", - com::centreon::broker::grpc::grpc_config::NO, + false, 30, false)); @@ -388,7 +387,7 @@ com::centreon::broker::grpc::grpc_config::pointer conf_crypted_client1234( read_file("tests/grpc_test_keys/ca_1234.crt"), "my_auth", "", - com::centreon::broker::grpc::grpc_config::NO, + false, 30, false)); @@ -457,7 +456,7 @@ com::centreon::broker::grpc::grpc_config::pointer read_file("tests/grpc_test_keys/ca_1234.crt"), "my_auth_pasbon", "", - com::centreon::broker::grpc::grpc_config::NO, + false, 30, false)); diff --git a/broker/lua/src/broker_utils.cc b/broker/lua/src/broker_utils.cc index 3cb18b162dc..53b751fd691 100644 --- a/broker/lua/src/broker_utils.cc +++ b/broker/lua/src/broker_utils.cc @@ -36,6 +36,7 @@ #include "com/centreon/broker/io/protobuf.hh" #include "com/centreon/broker/mapping/entry.hh" #include "com/centreon/broker/misc/misc.hh" +#include "com/centreon/common/hex_dump.hh" #include "com/centreon/exceptions/msg_fmt.hh" #include "common/log_v2/log_v2.hh" @@ -190,6 +191,7 @@ static void _message_to_json(std::ostringstream& oss, } oss << ']'; break; + case google::protobuf::FieldDescriptor::TYPE_SFIXED64: case google::protobuf::FieldDescriptor::TYPE_INT64: oss << fmt::format("\"{}\":[", entry_name); for (size_t j = 0; j < s; j++) { @@ -199,6 +201,7 @@ static void _message_to_json(std::ostringstream& oss, } oss << ']'; break; + case google::protobuf::FieldDescriptor::TYPE_FIXED64: case google::protobuf::FieldDescriptor::TYPE_UINT64: oss << fmt::format("\"{}\":[", entry_name); for (size_t j = 0; j < s; j++) { @@ -238,6 +241,16 @@ static void _message_to_json(std::ostringstream& oss, } oss << ']'; break; + case google::protobuf::FieldDescriptor::TYPE_BYTES: + oss << fmt::format("\"{}\":[", entry_name); + for (size_t j = 0; j < s; j++) { + if (j > 0) + oss << ','; + tmpl = refl->GetRepeatedStringReference(*p, f, j, &tmpl); + oss << '"' << com::centreon::common::hex_dump(tmpl, 0) << '"'; + } + oss << ']'; + break; default: // Error, a type not handled throw msg_fmt( "protobuf {} type ID is not handled in the broker json converter", @@ -259,9 +272,11 @@ static void _message_to_json(std::ostringstream& oss, case google::protobuf::FieldDescriptor::TYPE_UINT32: oss << fmt::format("\"{}\":{}", entry_name, refl->GetUInt32(*p, f)); break; + case google::protobuf::FieldDescriptor::TYPE_SFIXED64: case google::protobuf::FieldDescriptor::TYPE_INT64: oss << fmt::format("\"{}\":{}", entry_name, refl->GetInt64(*p, f)); break; + case google::protobuf::FieldDescriptor::TYPE_FIXED64: case google::protobuf::FieldDescriptor::TYPE_UINT64: oss << fmt::format("\"{}\":{}", entry_name, refl->GetUInt64(*p, f)); break; @@ -278,6 +293,11 @@ static void _message_to_json(std::ostringstream& oss, _message_to_json(oss, &refl->GetMessage(*p, f)); oss << '}'; break; + case google::protobuf::FieldDescriptor::TYPE_BYTES: + tmpl = refl->GetStringReference(*p, f, &tmpl); + oss << fmt::format(R"("{}":"{}")", entry_name, + com::centreon::common::hex_dump(tmpl, 0)); + break; default: // Error, a type not handled throw msg_fmt( "protobuf {} type ID is not handled in the broker json converter", diff --git a/broker/neb/CMakeLists.txt b/broker/neb/CMakeLists.txt index a2f1a10017a..f18a83c97b0 100644 --- a/broker/neb/CMakeLists.txt +++ b/broker/neb/CMakeLists.txt @@ -100,14 +100,14 @@ add_dependencies( pb_neb_lib pb_header_lib) -target_link_libraries( - nebbase +target_link_libraries(nebbase -L${PROTOBUF_LIB_DIR} - pb_severity_lib + protobuf + pb_severity_lib pb_tag_lib - protobuf - pb_neb_lib - pb_header_lib) + pb_neb_lib + pb_header_lib + pb_open_telemetry_lib) set(NEBBASE_CXXFLAGS "${NEBBASE_CXXFLAGS} -fPIC") set_property(TARGET nebbase PROPERTY COMPILE_FLAGS ${NEBBASE_CXXFLAGS}) diff --git a/broker/neb/inc/com/centreon/broker/neb/callbacks.hh b/broker/neb/inc/com/centreon/broker/neb/callbacks.hh index 0e24b1d3d10..4b226171c5b 100644 --- a/broker/neb/inc/com/centreon/broker/neb/callbacks.hh +++ b/broker/neb/inc/com/centreon/broker/neb/callbacks.hh @@ -70,6 +70,8 @@ int callback_tag(int callback_type, void* data) noexcept; int callback_pb_bench(int callback_type, void* data); +int callback_otl_metrics(int callback_type, void* data); + void unregister_callbacks(); } // namespace neb diff --git a/broker/neb/inc/com/centreon/broker/neb/internal.hh b/broker/neb/inc/com/centreon/broker/neb/internal.hh index 6bc17e4b31d..083f48ccf13 100644 --- a/broker/neb/inc/com/centreon/broker/neb/internal.hh +++ b/broker/neb/inc/com/centreon/broker/neb/internal.hh @@ -27,6 +27,7 @@ #include "com/centreon/broker/io/protobuf.hh" #include "com/centreon/broker/multiplexing/publisher.hh" #include "com/centreon/broker/neb/callback.hh" +#include "opentelemetry/proto/collector/metrics/v1/metrics_service.pb.h" namespace com::centreon::broker { @@ -127,6 +128,10 @@ using pb_instance_configuration = io::protobuf; +using pb_otl_metrics = io::protobuf< + opentelemetry::proto::collector::metrics::v1::ExportMetricsServiceRequest, + make_type(io::storage, storage::de_pb_otl_metrics)>; + } // namespace neb } // namespace com::centreon::broker diff --git a/broker/neb/src/broker.cc b/broker/neb/src/broker.cc index 0196a5e3cd0..d8645e48670 100644 --- a/broker/neb/src/broker.cc +++ b/broker/neb/src/broker.cc @@ -228,13 +228,13 @@ void broker_module_init(void const* arg) { e.register_event( neb::pb_service_group_member::static_type(), "ServiceGroupMember", &neb::pb_service_group_member::operations, "services_servicegroups"); - e.register_event(neb::pb_host_parent::static_type(), "HostParent", &neb::pb_host_parent::operations, "hosts_hosts_parents"); - e.register_event(neb::pb_instance_configuration::static_type(), "InstanceConfiguration", &neb::pb_instance_configuration::operations, "no_table"); + e.register_event(neb::pb_otl_metrics::static_type(), "OTLMetrics", + &neb::pb_otl_metrics::operations, "otl_metrics"); } } } diff --git a/broker/neb/src/callbacks.cc b/broker/neb/src/callbacks.cc index ec4405be004..cf3c7ffdaea 100644 --- a/broker/neb/src/callbacks.cc +++ b/broker/neb/src/callbacks.cc @@ -22,6 +22,8 @@ #include #include "bbdo/neb.pb.h" +#include "opentelemetry/proto/collector/metrics/v1/metrics_service.pb.h" + #include "com/centreon/broker/bbdo/internal.hh" #include "com/centreon/broker/config/applier/state.hh" #include "com/centreon/broker/config/parser.hh" @@ -110,7 +112,8 @@ static struct { {NEBCALLBACK_SERVICE_CHECK_DATA, &neb::callback_pb_service_check}, {NEBCALLBACK_SERVICE_STATUS_DATA, &neb::callback_pb_service_status}, {NEBCALLBACK_ADAPTIVE_SEVERITY_DATA, &neb::callback_severity}, - {NEBCALLBACK_ADAPTIVE_TAG_DATA, &neb::callback_tag}}; + {NEBCALLBACK_ADAPTIVE_TAG_DATA, &neb::callback_tag}, + {NEBCALLBACK_OTL_METRICS, &neb::callback_otl_metrics}}; // List of Engine-specific callbacks. static struct { @@ -4038,6 +4041,59 @@ int neb::callback_pb_bench(int, void* data) { return 0; } +namespace com::centreon::broker::neb::otl_detail { +/** + * @brief the goal of this little class is to avoid copy of an + * ExportMetricsServiceRequest as callback_otl_metrics receives a + * shared_ptr + * + */ +class otl_protobuf + : public io::protobuf { + std::shared_ptr< + opentelemetry::proto::collector::metrics::v1::ExportMetricsServiceRequest> + _obj; + + public: + otl_protobuf(void* pointer_to_shared_ptr) + : _obj(*static_cast< + std::shared_ptr*>( + pointer_to_shared_ptr)) {} + + const opentelemetry::proto::collector::metrics::v1:: + ExportMetricsServiceRequest& + obj() const override { + return *_obj; + } + + opentelemetry::proto::collector::metrics::v1::ExportMetricsServiceRequest& + mut_obj() override { + return *_obj; + } + + void set_obj(opentelemetry::proto::collector::metrics::v1:: + ExportMetricsServiceRequest&& obj) override { + throw com::centreon::exceptions::msg_fmt("unauthorized usage {}", + typeid(*this).name()); + } +}; + +} // namespace com::centreon::broker::neb::otl_detail + +/** + * @brief send an ExportMetricsServiceRequest to broker + * + * @param data pointer to a shared_ptr + * @return int 0 + */ +int neb::callback_otl_metrics(int, void* data) { + gl_publisher.write(std::make_shared(data)); + return 0; +} + /** * Unregister callbacks. */ diff --git a/broker/test/CMakeLists.txt b/broker/test/CMakeLists.txt index 00a11a96c49..064b57fd6d3 100644 --- a/broker/test/CMakeLists.txt +++ b/broker/test/CMakeLists.txt @@ -42,6 +42,8 @@ include_directories(${PROJECT_SOURCE_DIR}/tls2/inc) include_directories(${PROJECT_SOURCE_DIR}/grpc/inc) include_directories(${PROJECT_SOURCE_DIR}/grpc/src) include_directories(${CMAKE_SOURCE_DIR}/common/http/inc) +include_directories(${CMAKE_SOURCE_DIR}/common/grpc/inc) +include_directories(${CMAKE_SOURCE_DIR}/common/log_v2/inc) include_directories(${PROJECT_SOURCE_DIR}/http_tsdb/inc) include_directories(${PROJECT_SOURCE_DIR}/victoria_metrics/inc) include_directories(${PROJECT_SOURCE_DIR}/test/test_util/inc) diff --git a/broker/victoria_metrics/src/factory.cc b/broker/victoria_metrics/src/factory.cc index 42484381aab..321e088a168 100644 --- a/broker/victoria_metrics/src/factory.cc +++ b/broker/victoria_metrics/src/factory.cc @@ -56,7 +56,7 @@ factory::factory() io::endpoint* factory::new_endpoint( config::endpoint& cfg, bool& is_acceptor, - std::shared_ptr cache) const { + std::shared_ptr ) const { is_acceptor = false; std::shared_ptr conf( diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt index 23ba03d80b4..fd8633b6256 100644 --- a/common/CMakeLists.txt +++ b/common/CMakeLists.txt @@ -66,6 +66,7 @@ set_property(TARGET centreon_common PROPERTY POSITION_INDEPENDENT_CODE ON) target_precompile_headers(centreon_common PRIVATE precomp_inc/precomp.hh) add_subdirectory(http) +add_subdirectory(grpc) if(WITH_TESTING) add_subdirectory(tests) diff --git a/common/doc/common-doc.md b/common/doc/common-doc.md index aa2c67ff42a..f0614cf68e7 100644 --- a/common/doc/common-doc.md +++ b/common/doc/common-doc.md @@ -3,8 +3,50 @@ ## Table of content * [Pool](#Pool) +* [Grpc](#Grpc) ## Pool After a fork, only caller thread is activated in child process, so we mustn't join others. That's why thread container is dynamically allocated and not freed in case of fork. + + +## Grpc +The goal of the two classes provided, grpc_server_base and grpc_client_base is to create server or channel in order to use it with grpc generated services such as exchange in broker grpc module. +* `grpc_server_base` creates a ::grpc::server object. You can register service with third constructor parameter builder_option. +* `grpc_client_base` creates a ::grpc::channel that can be used to create a stub. + +In order to use it you have to override and use protected methods and attributes: + * server: +```c++ +class my_grpc_server: public public com::centreon::common::grpc::grpc_server_base { + std::shared_ptr _service; +public: + my_grpc_server(const grpc_config::pointer& conf); +}; + +my_grpc_server::my_grpc_server(const grpc_config::pointer& conf) + : com::centreon::common::grpc::grpc_server_base(conf, log_v2::grpc()) { + _init([this](::grpc::ServerBuilder& builder) { + _service = std::make_shared( + std::static_pointer_cast(get_conf())); + builder.RegisterService(_service.get()); + }); +} +``` + * client: +```c++ +class my_grpc_client : public com::centreon::common::grpc::grpc_client_base { + std::unique_ptr _stub; + + public: + my_grpc_client(const grpc_config::pointer& conf); +}; + +my_grpc_client::my_grpc_client(const grpc_config::pointer& conf) + : com::centreon::common::grpc::grpc_client_base(conf, log_v2::grpc()) { + _stub = std::move(com::centreon::my_service::NewStub(_channel)); +} + + +``` diff --git a/common/grpc/CMakeLists.txt b/common/grpc/CMakeLists.txt new file mode 100644 index 00000000000..ac154d422f4 --- /dev/null +++ b/common/grpc/CMakeLists.txt @@ -0,0 +1,37 @@ +# +# Copyright 2024 Centreon +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may not +# use this file except in compliance with the License. You may obtain a copy of +# the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations under +# the License. +# +# For more information : contact@centreon.com +# + +# Global options. + +set(INC_DIR "${PROJECT_SOURCE_DIR}/grpc/inc") +set(SRC_DIR "src") + +# Sources. +set(SOURCES + ${SRC_DIR}/grpc_client.cc + ${SRC_DIR}/grpc_server.cc +) + + +add_library(centreon_grpc STATIC ${SOURCES} ) +target_include_directories(centreon_grpc PRIVATE ${INC_DIR}) + +target_precompile_headers(centreon_grpc REUSE_FROM centreon_common) + +set_target_properties(centreon_grpc PROPERTIES COMPILE_FLAGS "-fPIC") + diff --git a/common/grpc/inc/com/centreon/common/grpc/grpc_client.hh b/common/grpc/inc/com/centreon/common/grpc/grpc_client.hh new file mode 100644 index 00000000000..6329ca758e4 --- /dev/null +++ b/common/grpc/inc/com/centreon/common/grpc/grpc_client.hh @@ -0,0 +1,48 @@ +/* + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ +#ifndef COMMON_GRPC_CLIENT_HH +#define COMMON_GRPC_CLIENT_HH + +#include +#include "com/centreon/common/grpc/grpc_config.hh" + +namespace com::centreon::common::grpc { + +/** + * @brief base class to create a grpc client + * It only creates grpc channel not stub + * + */ +class grpc_client_base { + grpc_config::pointer _conf; + std::shared_ptr _logger; + + protected: + std::shared_ptr<::grpc::Channel> _channel; + + public: + grpc_client_base(const grpc_config::pointer& conf, + const std::shared_ptr& logger); + + const grpc_config::pointer& get_conf() const { return _conf; } + const std::shared_ptr& get_logger() const { return _logger; } +}; + +} // namespace com::centreon::common::grpc + +#endif diff --git a/common/grpc/inc/com/centreon/common/grpc/grpc_config.hh b/common/grpc/inc/com/centreon/common/grpc/grpc_config.hh new file mode 100644 index 00000000000..a469ad5129f --- /dev/null +++ b/common/grpc/inc/com/centreon/common/grpc/grpc_config.hh @@ -0,0 +1,94 @@ +/* +** Copyright 2024 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef COMMON_GRPC_CONFIG_HH +#define COMMON_GRPC_CONFIG_HH + +#include + +namespace com::centreon::common::grpc { + +/** + * @brief calculate grpc compression mask (used both by client and server) + * + * @return constexpr uint32_t + */ +constexpr uint32_t calc_accept_all_compression_mask() { + uint32_t ret = 0; + for (size_t algo_ind = 0; algo_ind < GRPC_COMPRESS_ALGORITHMS_COUNT; + algo_ind++) { + ret += (1u << algo_ind); + } + return ret; +} + +/** + * @brief configuration bean used by client and server + * + * + */ +class grpc_config { + /** + * @brief client case: where to connect + * server case: address/port to listen + * + */ + const std::string _hostport; + const bool _crypted = false; + const std::string _certificate, _cert_key, _ca_cert; + const std::string _ca_name; + const bool _compress; + const int _second_keepalive_interval; + + public: + using pointer = std::shared_ptr; + + grpc_config() : _compress(false), _second_keepalive_interval(30) {} + grpc_config(const std::string& hostp) + : _hostport(hostp), _compress(false), _second_keepalive_interval(30) {} + grpc_config(const std::string& hostp, + bool crypted, + const std::string& certificate, + const std::string& cert_key, + const std::string& ca_cert, + const std::string& ca_name, + bool compression, + int second_keepalive_interval) + : _hostport(hostp), + _crypted(crypted), + _certificate(certificate), + _cert_key(cert_key), + _ca_cert(ca_cert), + _ca_name(ca_name), + _compress(compression), + _second_keepalive_interval(second_keepalive_interval) {} + + constexpr const std::string& get_hostport() const { return _hostport; } + constexpr bool is_crypted() const { return _crypted; } + constexpr const std::string& get_cert() const { return _certificate; } + constexpr const std::string& get_key() const { return _cert_key; } + constexpr const std::string& get_ca() const { return _ca_cert; } + const std::string& get_ca_name() const { return _ca_name; } + constexpr bool is_compressed() const { return _compress; } + int get_second_keepalive_interval() const { + return _second_keepalive_interval; + } +}; +} // namespace com::centreon::common::grpc + +#endif diff --git a/common/grpc/inc/com/centreon/common/grpc/grpc_server.hh b/common/grpc/inc/com/centreon/common/grpc/grpc_server.hh new file mode 100644 index 00000000000..c908c0916d8 --- /dev/null +++ b/common/grpc/inc/com/centreon/common/grpc/grpc_server.hh @@ -0,0 +1,58 @@ +/* + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ +#ifndef COMMON_GRPC_SERVER_HH +#define COMMON_GRPC_SERVER_HH + +#include +#include + +#include "com/centreon/common/grpc/grpc_config.hh" + +namespace com::centreon::common::grpc { + +/** + * @brief base class to create a grpc server + * + */ +class grpc_server_base { + grpc_config::pointer _conf; + std::shared_ptr _logger; + std::unique_ptr<::grpc::Server> _server; + + protected: + using builder_option = std::function; + void _init(const builder_option& options); + + public: + grpc_server_base(const grpc_config::pointer& conf, + const std::shared_ptr& logger); + + virtual ~grpc_server_base(); + + grpc_server_base(const grpc_server_base&) = delete; + grpc_server_base& operator=(const grpc_server_base&) = delete; + + const grpc_config::pointer& get_conf() const { return _conf; } + const std::shared_ptr& get_logger() const { return _logger; } + + bool initialized() const { return _server.get(); } +}; + +} // namespace com::centreon::common::grpc + +#endif diff --git a/common/grpc/src/grpc_client.cc b/common/grpc/src/grpc_client.cc new file mode 100644 index 00000000000..e62396901f7 --- /dev/null +++ b/common/grpc/src/grpc_client.cc @@ -0,0 +1,83 @@ +/* +** Copyright 2024 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#include + +#include "com/centreon/common/grpc/grpc_client.hh" + +using namespace com::centreon::common::grpc; + +/** + * @brief Construct a new grpc client base::grpc client base object + * + * @param conf + * @param logger + */ +grpc_client_base::grpc_client_base( + const grpc_config::pointer& conf, + const std::shared_ptr& logger) + : _conf(conf), _logger(logger) { + ::grpc::ChannelArguments args; + args.SetInt(GRPC_ARG_KEEPALIVE_PERMIT_WITHOUT_CALLS, 1); + args.SetInt(GRPC_ARG_KEEPALIVE_TIME_MS, + conf->get_second_keepalive_interval() * 1000); + args.SetInt(GRPC_ARG_KEEPALIVE_TIMEOUT_MS, + conf->get_second_keepalive_interval() * 300); + args.SetInt(GRPC_ARG_HTTP2_MAX_PINGS_WITHOUT_DATA, 0); + if (!conf->get_ca_name().empty()) + args.SetString(GRPC_SSL_TARGET_NAME_OVERRIDE_ARG, conf->get_ca_name()); + if (conf->is_compressed()) { + grpc_compression_algorithm algo = grpc_compression_algorithm_for_level( + GRPC_COMPRESS_LEVEL_HIGH, calc_accept_all_compression_mask()); + + const char* algo_name; + if (grpc_compression_algorithm_name(algo, &algo_name)) { + SPDLOG_LOGGER_DEBUG(_logger, "client this={:p} activate compression {}", + static_cast(this), algo_name); + } else { + SPDLOG_LOGGER_DEBUG(_logger, + "client this={:p} activate compression unknown", + static_cast(this)); + } + args.SetCompressionAlgorithm(algo); + } + std::shared_ptr<::grpc::ChannelCredentials> creds; + if (conf->is_crypted()) { + ::grpc::SslCredentialsOptions ssl_opts = {conf->get_ca(), conf->get_key(), + conf->get_cert()}; + SPDLOG_LOGGER_INFO( + _logger, + "encrypted connection to {} cert: {}..., key: {}..., ca: {}...", + conf->get_hostport(), conf->get_cert().substr(0, 10), + conf->get_key().substr(0, 10), conf->get_ca().substr(0, 10)); + creds = ::grpc::SslCredentials(ssl_opts); +#ifdef CAN_USE_JWT + if (!_conf->get_jwt().empty()) { + std::shared_ptr<::grpc::CallCredentials> jwt = + ::grpc::ServiceAccountJWTAccessCredentials(_conf->get_jwt(), 86400); + creds = ::grpc::CompositeChannelCredentials(creds, jwt); + } +#endif + } else { + SPDLOG_LOGGER_INFO(_logger, "unencrypted connection to {}", + conf->get_hostport()); + creds = ::grpc::InsecureChannelCredentials(); + } + + _channel = ::grpc::CreateCustomChannel(conf->get_hostport(), creds, args); +} diff --git a/common/grpc/src/grpc_server.cc b/common/grpc/src/grpc_server.cc new file mode 100644 index 00000000000..1fb0b657598 --- /dev/null +++ b/common/grpc/src/grpc_server.cc @@ -0,0 +1,103 @@ +/** + * Copyright 2024 Centreon (https://www.centreon.com/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ + +#include "com/centreon/common/grpc/grpc_server.hh" + +using namespace com::centreon::common::grpc; + +/** + * @brief Construct a new grpc server base::grpc server base object + * it creates and starts a grpc server + * + * @param conf + * @param logger + * @param options this lambda has access to ServerBuilder and can register + * grpc service(s) generated by protoc like service Export of opentelemetry + */ +grpc_server_base::grpc_server_base( + const grpc_config::pointer& conf, + const std::shared_ptr& logger) + : _conf(conf), _logger(logger) {} + +void grpc_server_base::_init(const builder_option& options) { + ::grpc::ServerBuilder builder; + + std::shared_ptr<::grpc::ServerCredentials> server_creds; + if (_conf->is_crypted() && !_conf->get_cert().empty() && + !_conf->get_key().empty()) { + ::grpc::SslServerCredentialsOptions::PemKeyCertPair pkcp = { + _conf->get_key(), _conf->get_cert()}; + + SPDLOG_LOGGER_INFO( + _logger, + "encrypted server listening on {} cert: {}..., key: {}..., ca: {}....", + _conf->get_hostport(), _conf->get_cert().substr(0, 10), + _conf->get_key().substr(0, 10), _conf->get_ca().substr(0, 10)); + + ::grpc::SslServerCredentialsOptions ssl_opts; + ssl_opts.pem_root_certs = _conf->get_ca(); + ssl_opts.pem_key_cert_pairs.push_back(pkcp); + + server_creds = ::grpc::SslServerCredentials(ssl_opts); + } else { + SPDLOG_LOGGER_INFO(_logger, "unencrypted server listening on {}", + _conf->get_hostport()); + server_creds = ::grpc::InsecureServerCredentials(); + } + builder.AddListeningPort(_conf->get_hostport(), server_creds); + options(builder); + builder.AddChannelArgument(GRPC_ARG_KEEPALIVE_PERMIT_WITHOUT_CALLS, 1); + builder.AddChannelArgument(GRPC_ARG_KEEPALIVE_TIME_MS, + _conf->get_second_keepalive_interval() * 1000); + builder.AddChannelArgument(GRPC_ARG_KEEPALIVE_TIMEOUT_MS, + _conf->get_second_keepalive_interval() * 300); + builder.AddChannelArgument(GRPC_ARG_HTTP2_MAX_PING_STRIKES, 0); + builder.AddChannelArgument(GRPC_ARG_HTTP2_MAX_PINGS_WITHOUT_DATA, 0); + builder.AddChannelArgument( + GRPC_ARG_HTTP2_MIN_RECV_PING_INTERVAL_WITHOUT_DATA_MS, 60000); + + if (_conf->is_compressed()) { + grpc_compression_algorithm algo = grpc_compression_algorithm_for_level( + GRPC_COMPRESS_LEVEL_HIGH, calc_accept_all_compression_mask()); + const char* algo_name; + if (grpc_compression_algorithm_name(algo, &algo_name)) + SPDLOG_LOGGER_DEBUG(_logger, "server default compression {}", algo_name); + else + SPDLOG_LOGGER_DEBUG(_logger, "server default compression unknown"); + + builder.SetDefaultCompressionAlgorithm(algo); + builder.SetDefaultCompressionLevel(GRPC_COMPRESS_LEVEL_HIGH); + } + _server = std::move(builder.BuildAndStart()); +} + +/** + * @brief Destroy the grpc_server::grpc_server object + * + */ +grpc_server_base::~grpc_server_base() { + if (_server) { + SPDLOG_LOGGER_DEBUG(_logger, "begin shutdown of grpc server {} ", + _conf->get_hostport()); + _server->Shutdown(std::chrono::system_clock::now() + + std::chrono::seconds(15)); + SPDLOG_LOGGER_DEBUG(_logger, "end shutdown of grpc server {} ", + _conf->get_hostport()); + } +} diff --git a/common/src/hex_dump.cc b/common/src/hex_dump.cc index 9a2c34caf51..a49cf21091b 100644 --- a/common/src/hex_dump.cc +++ b/common/src/hex_dump.cc @@ -1,21 +1,20 @@ /** -* Copyright 2023 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ - + * Copyright 2023-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "hex_dump.hh" diff --git a/engine/CMakeLists.txt b/engine/CMakeLists.txt index 5203a17f4c4..cabec0afbfb 100644 --- a/engine/CMakeLists.txt +++ b/engine/CMakeLists.txt @@ -498,6 +498,7 @@ include_directories(enginerpc add_library(cce_core ${LIBRARY_TYPE} ${FILES}) add_dependencies(cce_core engine_rpc) add_dependencies(cce_core centreon_clib) +add_dependencies(cce_core pb_neb_lib) target_precompile_headers(cce_core PRIVATE ${PRECOMP_HEADER}) diff --git a/engine/inc/com/centreon/engine/nebcallbacks.hh b/engine/inc/com/centreon/engine/nebcallbacks.hh index 299beab0620..d382b6950f7 100644 --- a/engine/inc/com/centreon/engine/nebcallbacks.hh +++ b/engine/inc/com/centreon/engine/nebcallbacks.hh @@ -74,7 +74,8 @@ #define NEBCALLBACK_ADAPTIVE_TAG_DATA 44 #define NEBCALLBACK_BENCH_DATA 45 -#define NEBCALLBACK_NUMITEMS 46 /* Total number of callback types we have. */ +#define NEBCALLBACK_OTL_METRICS 46 +#define NEBCALLBACK_NUMITEMS 47 /* Total number of callback types we have. */ #ifdef __cplusplus extern "C" { diff --git a/engine/modules/external_commands/CMakeLists.txt b/engine/modules/external_commands/CMakeLists.txt index 8bc6d44d338..2887e9fd75c 100644 --- a/engine/modules/external_commands/CMakeLists.txt +++ b/engine/modules/external_commands/CMakeLists.txt @@ -43,7 +43,7 @@ set_property(TARGET "externalcmd" PROPERTY PREFIX "") target_precompile_headers("externalcmd" PRIVATE precomp_inc/precomp.hh) set(EXTERNALCMD_MODULE "${EXTERNALCMD_MODULE}" PARENT_SCOPE) -add_dependencies(externalcmd centreon_clib) +add_dependencies(externalcmd centreon_clib pb_neb_lib) target_link_libraries(externalcmd centreon_clib spdlog::spdlog) # Install rule. diff --git a/tests/README.md b/tests/README.md index a916da59042..148fe569fcc 100644 --- a/tests/README.md +++ b/tests/README.md @@ -22,6 +22,17 @@ yum install "Development Tools" python3-devel -y pip3 install grpcio==1.33.2 grpcio_tools==1.33.2 +#you need also to provide opentelemetry proto files at the project root with this command +git clone https://github.com/open-telemetry/opentelemetry-proto.git opentelemetry-proto + +#Then you must have something like that: +#root directory/bbdo +# /broker +# /engine +# /opentelemetry-proto +# /tests + + ./init-proto.sh ./init-sql.sh ``` diff --git a/tests/init-proto.sh b/tests/init-proto.sh index b4999b72646..33be9f6daa7 100755 --- a/tests/init-proto.sh +++ b/tests/init-proto.sh @@ -1,5 +1,7 @@ #!/bin/bash +set -e + cd resources python3 -m grpc_tools.protoc -I../../engine/enginerpc -I../../common/src --python_out=. --grpc_python_out=. engine.proto python3 -m grpc_tools.protoc -I../../broker/core/src -I../../common/src --python_out=. --grpc_python_out=. broker.proto @@ -9,5 +11,10 @@ do python3 -m grpc_tools.protoc -I../../bbdo --python_out=. --grpc_python_out=. `basename $file` done python3 ../../broker/grpc/generate_proto.py -f grpc_stream.proto -c /tmp/not_used.cc -d ../../bbdo -python3 -m grpc_tools.protoc -I. -I../../bbdo --python_out=. --grpc_python_out=. grpc_stream.proto +python3 -m grpc_tools.protoc -I. -I../../bbdo -I../../opentelemetry-proto --python_out=. --grpc_python_out=. grpc_stream.proto + +python3 -m grpc_tools.protoc -I../../opentelemetry-proto --python_out=. --grpc_python_out=. opentelemetry/proto/collector/metrics/v1/metrics_service.proto +python3 -m grpc_tools.protoc -I../../opentelemetry-proto --python_out=. --grpc_python_out=. opentelemetry/proto/metrics/v1/metrics.proto +python3 -m grpc_tools.protoc -I../../opentelemetry-proto --python_out=. --grpc_python_out=. opentelemetry/proto/common/v1/common.proto +python3 -m grpc_tools.protoc -I../../opentelemetry-proto --python_out=. --grpc_python_out=. opentelemetry/proto/resource/v1/resource.proto cd .. diff --git a/tests/update-doc.py b/tests/update-doc.py index 906afaa9e88..1335840e447 100755 --- a/tests/update-doc.py +++ b/tests/update-doc.py @@ -68,6 +68,17 @@ def parse_dir(d): pip3 install grpcio==1.33.2 grpcio_tools==1.33.2 +#you need also to provide opentelemetry proto files at the project root with this command +git clone https://github.com/open-telemetry/opentelemetry-proto.git opentelemetry-proto + +#Then you must have something like that: +#root directory/bbdo +# /broker +# /engine +# /opentelemetry-proto +# /tests + + ./init-proto.sh ./init-sql.sh ``` From 54634ba1eafe7a6d815648881ce77d9dcc16b927 Mon Sep 17 00:00:00 2001 From: May <110405507+mushroomempires@users.noreply.github.com> Date: Thu, 30 May 2024 14:10:51 +0200 Subject: [PATCH 16/60] fix(ci): force ubuntu 22.04 usage in all (mostly veracode) pipelines (#1383) --- .github/workflows/veracode-analysis.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/veracode-analysis.yml b/.github/workflows/veracode-analysis.yml index d13bede06ac..db17f1ed72a 100644 --- a/.github/workflows/veracode-analysis.yml +++ b/.github/workflows/veracode-analysis.yml @@ -29,7 +29,7 @@ on: jobs: routing: name: Check before analysis - runs-on: ubuntu-latest + runs-on: ubuntu-22.04 outputs: development_stage: ${{ steps.routing-mode.outputs.development_stage }} @@ -142,7 +142,7 @@ jobs: name: Sandbox scan needs: [routing, build] if: needs.routing.outputs.development_stage != 'Development' - runs-on: ubuntu-latest + runs-on: ubuntu-22.04 steps: - name: Promote latest scan From 97a132a93e92a5ddad8021f96349afe0b0b19628 Mon Sep 17 00:00:00 2001 From: jean-christophe81 <98889244+jean-christophe81@users.noreply.github.com> Date: Fri, 31 May 2024 16:18:55 +0200 Subject: [PATCH 17/60] enh(engine/otlp): new otlp gRPC server * gRPC fix. REFS: MON-34074 --- CMakeLists.txt | 3 +- broker/CMakeLists.txt | 11 +- broker/bam/CMakeLists.txt | 1 + .../inc/com/centreon/broker/grpc/acceptor.hh | 17 +- .../inc/com/centreon/broker/grpc/stream.hh | 8 - broker/grpc/src/acceptor.cc | 18 +- broker/lua/CMakeLists.txt | 3 +- broker/neb/CMakeLists.txt | 2 + broker/simu/CMakeLists.txt | 3 +- broker/sql/CMakeLists.txt | 1 + broker/storage/CMakeLists.txt | 1 + broker/unified_sql/CMakeLists.txt | 4 +- .../com/centreon/common/grpc/grpc_config.hh | 37 +- .../com/centreon/common/grpc/grpc_server.hh | 2 + common/grpc/src/grpc_server.cc | 27 +- .../com/centreon/common/http/http_config.hh | 13 +- common/log_v2/log_v2.cc | 16 +- common/log_v2/log_v2.hh | 3 +- engine/CMakeLists.txt | 3 +- engine/doc/engine-doc.md | 147 ++++++++ engine/enginerpc/precomp_inc/precomp.hh | 1 + .../com/centreon/engine/anomalydetection.hh | 10 +- engine/inc/com/centreon/engine/checkable.hh | 3 +- .../engine/commands/otel_interface.hh | 121 +++++++ engine/modules/CMakeLists.txt | 42 ++- engine/modules/opentelemetry/CMakeLists.txt | 83 +++++ .../modules/opentelemetry/grpc_config.hh | 48 +++ .../modules/opentelemetry/open_telemetry.hh | 90 +++++ .../modules/opentelemetry/otl_config.hh | 57 +++ .../modules/opentelemetry/otl_data_point.hh | 211 ++++++++++++ .../engine/modules/opentelemetry/otl_fmt.hh | 68 ++++ .../modules/opentelemetry/otl_server.hh | 66 ++++ .../opentelemetry/precomp_inc/precomp.hh | 62 ++++ .../modules/opentelemetry/src/grpc_config.cc | 164 +++++++++ engine/modules/opentelemetry/src/main.cc | 121 +++++++ .../opentelemetry/src/open_telemetry.cc | 279 +++++++++++++++ .../modules/opentelemetry/src/otl_config.cc | 109 ++++++ .../opentelemetry/src/otl_data_point.cc | 91 +++++ .../modules/opentelemetry/src/otl_server.cc | 324 ++++++++++++++++++ engine/precomp_inc/precomp.hh | 1 + engine/src/anomalydetection.cc | 164 +++------ engine/src/commands/CMakeLists.txt | 1 + engine/src/commands/otel_interface.cc | 58 ++++ engine/tests/CMakeLists.txt | 19 +- engine/tests/checks/anomalydetection.cc | 1 + .../tests/opentelemetry/grpc_config_test.cc | 110 ++++++ engine/tests/opentelemetry/otl_server_test.cc | 116 +++++++ ...treon-broker-stats-exporter-debuginfo.yaml | 41 --- packaging/centreon-broker-stats-exporter.yaml | 36 -- tests/broker-engine/external-commands2.robot | 4 +- vcpkg.json | 10 +- 51 files changed, 2559 insertions(+), 272 deletions(-) create mode 100644 engine/inc/com/centreon/engine/commands/otel_interface.hh create mode 100644 engine/modules/opentelemetry/CMakeLists.txt create mode 100644 engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/grpc_config.hh create mode 100644 engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/open_telemetry.hh create mode 100644 engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_config.hh create mode 100644 engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_data_point.hh create mode 100644 engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_fmt.hh create mode 100644 engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_server.hh create mode 100644 engine/modules/opentelemetry/precomp_inc/precomp.hh create mode 100644 engine/modules/opentelemetry/src/grpc_config.cc create mode 100644 engine/modules/opentelemetry/src/main.cc create mode 100644 engine/modules/opentelemetry/src/open_telemetry.cc create mode 100644 engine/modules/opentelemetry/src/otl_config.cc create mode 100644 engine/modules/opentelemetry/src/otl_data_point.cc create mode 100644 engine/modules/opentelemetry/src/otl_server.cc create mode 100644 engine/src/commands/otel_interface.cc create mode 100644 engine/tests/opentelemetry/grpc_config_test.cc create mode 100644 engine/tests/opentelemetry/otl_server_test.cc delete mode 100644 packaging/centreon-broker-stats-exporter-debuginfo.yaml delete mode 100644 packaging/centreon-broker-stats-exporter.yaml diff --git a/CMakeLists.txt b/CMakeLists.txt index 22f208b6765..27dc8e2264f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -152,10 +152,9 @@ find_package(spdlog CONFIG REQUIRED) find_package(gRPC CONFIG REQUIRED) find_package(Protobuf REQUIRED) find_package(nlohmann_json CONFIG REQUIRED) -find_package(opentelemetry-cpp REQUIRED) find_package(GTest CONFIG REQUIRED) find_package(CURL REQUIRED) -find_package(Boost REQUIRED) +find_package(Boost REQUIRED COMPONENTS url) find_package(ryml CONFIG REQUIRED) add_definitions("-DSPDLOG_FMT_EXTERNAL") diff --git a/broker/CMakeLists.txt b/broker/CMakeLists.txt index 3464996b05e..aa6ab735390 100644 --- a/broker/CMakeLists.txt +++ b/broker/CMakeLists.txt @@ -110,7 +110,8 @@ add_custom_target("target_broker_message" DEPENDS "${SRC_DIR}/broker.pb.cc" "${SRC_DIR}/broker.pb.h") include_directories(${SRC_DIR} ${CMAKE_SOURCE_DIR}/common/src - ${CMAKE_SOURCE_DIR}/common/inc) + ${CMAKE_SOURCE_DIR}/common/inc + ${CMAKE_SOURCE_DIR}/bbdo) add_library(berpc STATIC ${SRC_DIR}/broker.grpc.pb.cc ${SRC_DIR}/broker.pb.cc ${SRC_DIR}/broker.grpc.pb.h ${SRC_DIR}/broker.pb.h) @@ -446,6 +447,7 @@ target_link_libraries( bbdo_bbdo pb_bbdo_lib pb_extcmd_lib + pb_open_telemetry_lib berpc z spdlog::spdlog @@ -460,10 +462,6 @@ target_link_libraries( rokerbase crypto ssl - gRPC::gpr - gRPC::grpc - gRPC::grpc++ - gRPC::grpc++_alts pthread dl) @@ -494,7 +492,6 @@ target_link_libraries( # spdlog::spdlog gRPC::gpr gRPC::grpc - gRPC::grpc++ gRPC::grpc++_alts) # Centreon Broker Watchdog @@ -513,7 +510,7 @@ add_subdirectory(core/sql) # Generator module. add_broker_module(GENERATOR OFF) add_broker_module(STATS ON) -add_broker_module(STATS_EXPORTER ON) +#add_broker_module(STATS_EXPORTER OFF) add_broker_module(NEB ON) add_broker_module(RRD ON) add_broker_module(UNIFIED_SQL ON) diff --git a/broker/bam/CMakeLists.txt b/broker/bam/CMakeLists.txt index de11cc98c02..5f2f4c57bfb 100644 --- a/broker/bam/CMakeLists.txt +++ b/broker/bam/CMakeLists.txt @@ -146,6 +146,7 @@ target_link_libraries("${BAM}" bbdo_storage bbdo_bam pb_bam_lib spdlog::spdlog) target_precompile_headers(${BAM} PRIVATE precomp_inc/precomp.hpp) set_target_properties("${BAM}" PROPERTIES PREFIX "") +add_dependencies("${BAM}" pb_open_telemetry_lib) # Testing. if(WITH_TESTING) diff --git a/broker/grpc/inc/com/centreon/broker/grpc/acceptor.hh b/broker/grpc/inc/com/centreon/broker/grpc/acceptor.hh index b9382370025..53700596cfc 100644 --- a/broker/grpc/inc/com/centreon/broker/grpc/acceptor.hh +++ b/broker/grpc/inc/com/centreon/broker/grpc/acceptor.hh @@ -33,7 +33,7 @@ namespace com::centreon::broker::grpc { * */ class service_impl - : public com::centreon::broker::stream::centreon_bbdo::CallbackService, + : public com::centreon::broker::stream::centreon_bbdo::Service, public std::enable_shared_from_this { grpc_config::pointer _conf; @@ -46,9 +46,22 @@ class service_impl public: service_impl(const grpc_config::pointer& conf); + void init(); + + // disable synchronous version of this method + ::grpc::Status exchange( + ::grpc::ServerContext* /*context*/, + ::grpc::ServerReaderWriter< + ::com::centreon::broker::stream::CentreonEvent, + ::com::centreon::broker::stream::CentreonEvent>* /*stream*/) + override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + ::grpc::ServerBidiReactor<::com::centreon::broker::stream::CentreonEvent, ::com::centreon::broker::stream::CentreonEvent>* - exchange(::grpc::CallbackServerContext* context) override; + exchange(::grpc::CallbackServerContext* context); const grpc_config::pointer& get_conf() const { return _conf; } diff --git a/broker/grpc/inc/com/centreon/broker/grpc/stream.hh b/broker/grpc/inc/com/centreon/broker/grpc/stream.hh index 358b5a5d6e8..d6fa2b17e97 100644 --- a/broker/grpc/inc/com/centreon/broker/grpc/stream.hh +++ b/broker/grpc/inc/com/centreon/broker/grpc/stream.hh @@ -32,14 +32,6 @@ std::ostream& operator<<(std::ostream&, const CentreonEvent&); namespace grpc { extern const std::string authorization_header; -constexpr uint32_t calc_accept_all_compression_mask() { - uint32_t ret = 0; - for (size_t algo_ind = 0; algo_ind < GRPC_COMPRESS_ALGORITHMS_COUNT; - algo_ind++) { - ret += (1u << algo_ind); - } - return ret; -} struct detail_centreon_event; std::ostream& operator<<(std::ostream&, const detail_centreon_event&); diff --git a/broker/grpc/src/acceptor.cc b/broker/grpc/src/acceptor.cc index be32e89be90..42ef53fd8cb 100644 --- a/broker/grpc/src/acceptor.cc +++ b/broker/grpc/src/acceptor.cc @@ -21,6 +21,7 @@ #include "com/centreon/broker/grpc/acceptor.hh" #include "com/centreon/broker/grpc/stream.hh" +#include "com/centreon/common/pool.hh" #include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; @@ -95,6 +96,20 @@ void server_stream::OnDone() { */ service_impl::service_impl(const grpc_config::pointer& conf) : _conf(conf) {} +/** + * @brief to call after construction + * + */ +void service_impl::init() { + ::grpc::Service::MarkMethodCallback( + 0, new ::grpc::internal::CallbackBidiHandler< + ::com::centreon::broker::stream::CentreonEvent, + ::com::centreon::broker::stream::CentreonEvent>( + [me = shared_from_this()](::grpc::CallbackServerContext* context) { + return me->exchange(context); + })); +} + /** * @brief called on every stream creation * every accepted stream is pushed in _wait_to_open queue @@ -136,7 +151,7 @@ service_impl::exchange(::grpc::CallbackServerContext* context) { server_stream::register_stream(next_stream); next_stream->start_read(); { - std::unique_lock l(_wait_m); + std::lock_guard l(_wait_m); _wait_to_open.push_back(next_stream); } _wait_cond.notify_one(); @@ -249,6 +264,7 @@ acceptor::acceptor(const grpc_config::pointer& conf) _init([this](::grpc::ServerBuilder& builder) { _service = std::make_shared( std::static_pointer_cast(get_conf())); + _service->init(); builder.RegisterService(_service.get()); }); } diff --git a/broker/lua/CMakeLists.txt b/broker/lua/CMakeLists.txt index 26ad625fd45..52cfcedd95a 100644 --- a/broker/lua/CMakeLists.txt +++ b/broker/lua/CMakeLists.txt @@ -61,7 +61,8 @@ add_dependencies(${LUA} pb_neb_lib pb_header_lib pb_storage_lib - pb_bam_lib) + pb_bam_lib + pb_open_telemetry_lib) target_link_libraries("${LUA}" ${LUA_LIBRARIES} crypto ssl bbdo_storage bbdo_bam spdlog::spdlog pb_storage_lib) target_precompile_headers(${LUA} PRIVATE precomp_inc/precomp.hpp) diff --git a/broker/neb/CMakeLists.txt b/broker/neb/CMakeLists.txt index f18a83c97b0..b465e8b3942 100644 --- a/broker/neb/CMakeLists.txt +++ b/broker/neb/CMakeLists.txt @@ -175,6 +175,8 @@ endif() set_target_properties("${CBMOD}" PROPERTIES PREFIX "") target_precompile_headers(${CBMOD} PRIVATE precomp_inc/precomp.hpp) +target_include_directories(${CBMOD} PRIVATE ${CMAKE_SOURCE_DIR}/bbdo) + # Testing. if(WITH_TESTING) set(TESTS_SOURCES diff --git a/broker/simu/CMakeLists.txt b/broker/simu/CMakeLists.txt index ce3e2215faa..4dbedc26cc1 100644 --- a/broker/simu/CMakeLists.txt +++ b/broker/simu/CMakeLists.txt @@ -48,7 +48,8 @@ add_dependencies(${SIMU} pb_neb_lib pb_header_lib pb_storage_lib - pb_bam_lib) + pb_bam_lib + pb_open_telemetry_lib) target_link_libraries("${SIMU}" ${LUA_LIBRARIES} spdlog::spdlog) target_precompile_headers(${SIMU} PRIVATE precomp_inc/precomp.hpp) diff --git a/broker/sql/CMakeLists.txt b/broker/sql/CMakeLists.txt index 32d231a5fc4..00789ede713 100644 --- a/broker/sql/CMakeLists.txt +++ b/broker/sql/CMakeLists.txt @@ -44,6 +44,7 @@ add_library("${SQL}" SHARED add_dependencies(${SQL} pb_neb_lib pb_header_lib + pb_open_telemetry_lib ) set_target_properties("${SQL}" PROPERTIES diff --git a/broker/storage/CMakeLists.txt b/broker/storage/CMakeLists.txt index efa4de6f392..1a7cc17974d 100644 --- a/broker/storage/CMakeLists.txt +++ b/broker/storage/CMakeLists.txt @@ -43,6 +43,7 @@ add_dependencies(conflictmgr pb_neb_lib pb_header_lib pb_storage_lib + pb_open_telemetry_lib ) set_target_properties(conflictmgr PROPERTIES COMPILE_FLAGS "-fPIC") diff --git a/broker/unified_sql/CMakeLists.txt b/broker/unified_sql/CMakeLists.txt index 96232087b08..47ff4ee4e21 100644 --- a/broker/unified_sql/CMakeLists.txt +++ b/broker/unified_sql/CMakeLists.txt @@ -56,7 +56,9 @@ add_library( set_target_properties("${UNIFIED_SQL}" PROPERTIES PREFIX "" COMPILE_FLAGS "-fPIC") add_dependencies("${UNIFIED_SQL}" target_rebuild_message - target_remove_graph_message target_neb) + target_remove_graph_message + target_neb + pb_open_telemetry_lib) target_precompile_headers(${UNIFIED_SQL} PRIVATE precomp_inc/precomp.hpp) target_link_libraries( ${UNIFIED_SQL} diff --git a/common/grpc/inc/com/centreon/common/grpc/grpc_config.hh b/common/grpc/inc/com/centreon/common/grpc/grpc_config.hh index a469ad5129f..2d8b5978be9 100644 --- a/common/grpc/inc/com/centreon/common/grpc/grpc_config.hh +++ b/common/grpc/inc/com/centreon/common/grpc/grpc_config.hh @@ -48,12 +48,12 @@ class grpc_config { * server case: address/port to listen * */ - const std::string _hostport; - const bool _crypted = false; - const std::string _certificate, _cert_key, _ca_cert; - const std::string _ca_name; - const bool _compress; - const int _second_keepalive_interval; + std::string _hostport; + bool _crypted = false; + std::string _certificate, _cert_key, _ca_cert; + std::string _ca_name; + bool _compress; + int _second_keepalive_interval; public: using pointer = std::shared_ptr; @@ -61,6 +61,11 @@ class grpc_config { grpc_config() : _compress(false), _second_keepalive_interval(30) {} grpc_config(const std::string& hostp) : _hostport(hostp), _compress(false), _second_keepalive_interval(30) {} + grpc_config(const std::string& hostp, bool crypted) + : _hostport(hostp), + _crypted(crypted), + _compress(false), + _second_keepalive_interval(30) {} grpc_config(const std::string& hostp, bool crypted, const std::string& certificate, @@ -78,16 +83,24 @@ class grpc_config { _compress(compression), _second_keepalive_interval(second_keepalive_interval) {} - constexpr const std::string& get_hostport() const { return _hostport; } - constexpr bool is_crypted() const { return _crypted; } - constexpr const std::string& get_cert() const { return _certificate; } - constexpr const std::string& get_key() const { return _cert_key; } - constexpr const std::string& get_ca() const { return _ca_cert; } + const std::string& get_hostport() const { return _hostport; } + bool is_crypted() const { return _crypted; } + const std::string& get_cert() const { return _certificate; } + const std::string& get_key() const { return _cert_key; } + const std::string& get_ca() const { return _ca_cert; } const std::string& get_ca_name() const { return _ca_name; } - constexpr bool is_compressed() const { return _compress; } + bool is_compressed() const { return _compress; } int get_second_keepalive_interval() const { return _second_keepalive_interval; } + + bool operator==(const grpc_config& right) const { + return _hostport == right._hostport && _crypted == right._crypted && + _certificate == right._certificate && _cert_key == right._cert_key && + _ca_cert == right._ca_cert && _ca_name == right._ca_name && + _compress == right._compress && + _second_keepalive_interval == right._second_keepalive_interval; + } }; } // namespace com::centreon::common::grpc diff --git a/common/grpc/inc/com/centreon/common/grpc/grpc_server.hh b/common/grpc/inc/com/centreon/common/grpc/grpc_server.hh index c908c0916d8..20afb0c9b3e 100644 --- a/common/grpc/inc/com/centreon/common/grpc/grpc_server.hh +++ b/common/grpc/inc/com/centreon/common/grpc/grpc_server.hh @@ -44,6 +44,8 @@ class grpc_server_base { virtual ~grpc_server_base(); + void shutdown(const std::chrono::system_clock::duration& timeout); + grpc_server_base(const grpc_server_base&) = delete; grpc_server_base& operator=(const grpc_server_base&) = delete; diff --git a/common/grpc/src/grpc_server.cc b/common/grpc/src/grpc_server.cc index 1fb0b657598..340cef4272b 100644 --- a/common/grpc/src/grpc_server.cc +++ b/common/grpc/src/grpc_server.cc @@ -92,12 +92,25 @@ void grpc_server_base::_init(const builder_option& options) { * */ grpc_server_base::~grpc_server_base() { - if (_server) { - SPDLOG_LOGGER_DEBUG(_logger, "begin shutdown of grpc server {} ", - _conf->get_hostport()); - _server->Shutdown(std::chrono::system_clock::now() + - std::chrono::seconds(15)); - SPDLOG_LOGGER_DEBUG(_logger, "end shutdown of grpc server {} ", - _conf->get_hostport()); + shutdown(std::chrono::seconds(15)); +} + +/** + * @brief shutdown server + * + * @param timeout after this timeout, grpc server will be stopped + */ +void grpc_server_base::shutdown( + const std::chrono::system_clock::duration& timeout) { + std::unique_ptr<::grpc::Server> to_shutdown; + if (!_server) { + return; } + to_shutdown = std::move(_server); + SPDLOG_LOGGER_INFO(_logger, "{:p} begin shutdown of grpc server {}", + static_cast(this), _conf->get_hostport()); + to_shutdown->Shutdown(std::chrono::system_clock::now() + timeout); + to_shutdown->Wait(); + SPDLOG_LOGGER_INFO(_logger, "{:p} end shutdown of grpc server {}", + static_cast(this), _conf->get_hostport()); } diff --git a/common/http/inc/com/centreon/common/http/http_config.hh b/common/http/inc/com/centreon/common/http/http_config.hh index 90c0bce3aa8..c20fdf5065c 100644 --- a/common/http/inc/com/centreon/common/http/http_config.hh +++ b/common/http/inc/com/centreon/common/http/http_config.hh @@ -22,6 +22,10 @@ namespace com::centreon::common::http { +using system_clock = std::chrono::system_clock; +using time_point = system_clock::time_point; +using duration = system_clock::duration; + /** * @brief this class is a bean that contains all config parameters * @@ -42,6 +46,8 @@ class http_config { asio::ssl::context_base::method _ssl_method; // path of certificate file std::string _certificate_path; + // path to key file (server case) + std::string _key_path; public: using pointer = std::shared_ptr; @@ -59,7 +65,8 @@ class http_config { unsigned max_connections = 10, asio::ssl::context_base::method ssl_method = asio::ssl::context_base::tlsv13_client, - const std::string& certificate_path = "") + const std::string& certificate_path = "", + const std::string& key_path = "") : _endpoint(endpoint), _server_name(server_name), _crypted(crypted), @@ -72,7 +79,8 @@ class http_config { _default_http_keepalive_duration(default_http_keepalive_duration), _max_connections(max_connections), _ssl_method(ssl_method), - _certificate_path(certificate_path) {} + _certificate_path(certificate_path), + _key_path(key_path) {} http_config() : _crypted(false), @@ -97,6 +105,7 @@ class http_config { unsigned get_max_connections() const { return _max_connections; } asio::ssl::context_base::method get_ssl_method() const { return _ssl_method; } const std::string& get_certificate_path() const { return _certificate_path; } + const std::string& get_key_path() const { return _key_path; } }; } // namespace com::centreon::common::http diff --git a/common/log_v2/log_v2.cc b/common/log_v2/log_v2.cc index a243adb9d55..8c80518270c 100644 --- a/common/log_v2/log_v2.cc +++ b/common/log_v2/log_v2.cc @@ -66,7 +66,8 @@ const std::array log_v2::_logger_name = { "downtimes", "comments", "macros", - "runtime"}; + "runtime", + "otel"}; /** * @brief this function is passed to grpc in order to log grpc layer's events to @@ -112,11 +113,9 @@ static void grpc_logger(gpr_log_func_args* args) { } /** - * @brief Initialization of the log_v2 instance. Initialized loggers are given - * in ilist. + * @brief Initialization of the log_v2 instance. * * @param name The name of the logger. - * @param ilist The list of loggers to initialize. */ void log_v2::load(std::string name) { if (!_instance) @@ -147,6 +146,15 @@ log_v2::log_v2(std::string name) : _log_name{std::move(name)} { create_loggers(config::logger_type::LOGGER_STDOUT); } +/** + * @brief Destroy the log v2::log v2 object + * + */ +log_v2::~log_v2() noexcept { + // grpc_logger mustn't be called after log_v2 destruction + gpr_set_log_function(nullptr); +} + /** * @brief Static method to get the current log_v2 running instance. * diff --git a/common/log_v2/log_v2.hh b/common/log_v2/log_v2.hh index 3fe6b0f4ad4..efcec015be5 100644 --- a/common/log_v2/log_v2.hh +++ b/common/log_v2/log_v2.hh @@ -82,6 +82,7 @@ class log_v2 { COMMENTS = 26, MACROS = 27, RUNTIME = 28, + OTEL = 29, LOGGER_SIZE }; @@ -104,7 +105,7 @@ class log_v2 { log_v2(std::string name); log_v2(const log_v2&) = delete; log_v2& operator=(const log_v2&) = delete; - ~log_v2() noexcept = default; + ~log_v2() noexcept; logger_id get_id(const std::string& name) const noexcept; std::chrono::seconds flush_interval(); diff --git a/engine/CMakeLists.txt b/engine/CMakeLists.txt index cabec0afbfb..2415b6ea35d 100644 --- a/engine/CMakeLists.txt +++ b/engine/CMakeLists.txt @@ -505,7 +505,6 @@ target_precompile_headers(cce_core PRIVATE ${PRECOMP_HEADER}) # Link target with required libraries. target_link_libraries( cce_core - nlohmann_json::nlohmann_json ${MATH_LIBRARIES} ${PTHREAD_LIBRARIES} ${SOCKET_LIBRARIES} @@ -527,12 +526,12 @@ target_link_libraries( log_v2 "-Wl,-whole-archive" enginerpc + centreon_grpc cce_core gRPC::grpc++ "-Wl,--no-whole-archive" gRPC::gpr gRPC::grpc - gRPC::grpc++ gRPC::grpc++_alts absl::any absl::log diff --git a/engine/doc/engine-doc.md b/engine/doc/engine-doc.md index aa1fa21912f..6839ce6647c 100644 --- a/engine/doc/engine-doc.md +++ b/engine/doc/engine-doc.md @@ -57,3 +57,150 @@ In `state.cc` all setters have two methods: * `apply_from_json`. On configuration update, we first parse the `centengine.cfg` and all the `*.cfg` files, and then we parse additional configuration files. + +## Open-telemetry +### Principe +Engine can receive open telemetry data on a grpc server +A new module is added opentelemetry +It works like that: +* metrics are received +* extractors tries to extract host name and service description for each data_point. On success, data_point are pushed on fifos indexed by host, service +* a service that used these datas wants to do a check. The cmd line identifies the otl_converter that will construct check result from host service data_point fifos. If converter achieves to build a result from metrics, it returns right now, if it doesn't, a handler will be called as soon as needed metrics will be available or timeout expires. + +### open telemetry request +The proto is organized like that +```json +{ + "resourceMetrics": [ + { + "resource": { + "attributes": [ + { + "key": "attrib1", + "value": { + "stringValue": "attrib value" + } + } + ] + }, + "scopeMetrics": [ + { + "scope": { + "attributes": [ + { + "key": "attrib1", + "value": { + "stringValue": "attrib value" + } + } + ] + }, + "metrics": [ + { + "name": "check_icmp_warning_gt", + "gauge": { + "dataPoints": [ + { + "timeUnixNano": "1707744430000000000", + "asDouble": 200, + "attributes": [ + { + "key": "host", + "value": { + "stringValue": "localhost" + } + }, + { + "key": "perfdata", + "value": { + "stringValue": "rta" + } + }, + { + "key": "service", + "value": { + "stringValue": "check_icmp" + } + }, + { + "key": "unit", + "value": { + "stringValue": "ms" + } + } + ] + }, + { + "timeUnixNano": "1707744430000000000", + "asDouble": 40, + "attributes": [ + { + "key": "host", + "value": { + "stringValue": "localhost" + } + }, + { + "key": "perfdata", + "value": { + "stringValue": "pl" + } + }, + { + "key": "service", + "value": { + "stringValue": "check_icmp" + } + }, + { + "key": "unit", + "value": { + "stringValue": "%" + } + } + ] + } + ] + } + } + ] + } + ] + } + ] +} + +``` + +### Concepts and classes +* data_point: data_point is the smallest unit of received request, data_point class contains data_point protobuf object and all his parents (resource, scope, metric) +* host serv extractors: When we receive otel metrics, we must extract host and service, this is his job. It can be configurable in order for example to search host name in data_point attribute or in scope. host serv extractors also contains host serv allowed. This list is updated by register_host_serv command method +* data_point fifo: a container that contains data points indexed by timestamp +* data_point fifo container: fifos indexed by host service +* otel_command: a fake connector that is used to make the link between engine and otel module +* otl_server: a grpc server that accept otel collector incoming connections +* otl_converter: This short lived object is created each time engine wants to do a check. His final class as his configuration is done from the command line of the check. His job is to create a check result from data_point fifo container datas. It's destroyed when he achieved to create a check result or when timeout expires. +* host_serv_list: in order to extract host and service, an host_serv extractor must known allowed host service pairs. As otel_command may be notified of host service using it by register_host_serv method while otel module is not yet loaded. This object shared between otel_command and host_serv_extractor is actualized from otel_command::register_host_serv. + +### How engine access to otl object +In otel_interface.hh, otel object interface are defined in engine commands namespace. +Object used by both otel module and engine are inherited from these interfaces. +Engine only knows a singleton of the interface open_telemetry_base. This singleton is initialized at otl module loading. + +### How to configure it +We use a fake connector. When configuration is loaded, if a connector command line begins with "open_telemetry", we create an otel_command. Arguments following "open_telemetry" are used to create an host service extractor. If otel module is loaded, we create extractor, otherwise, the otel_command initialization will be done at otel module loading. +So user has to build one connector by host serv extractor configuration. +Then commands can use these fake connectors (class otel_command) to run checks. + +### How a service do a check +When otel_command::run is called, it calls the check method of open_telemetry singleton. +The check method of open_telemetry object will use command line passed to run to create an otl_converter object that has to convert metrics to check result. +The open_telemetry call sync_build_result_from_metrics, if it can't achieve to build a result, otl_converter is stored in a container. +When a metric of a waiting service is received, async_build_result_from_metrics of otl_converter is called. +In open_telemetry object, a second timer is also used to call async_time_out of otl_converter on timeout expire. + +### other configuration +other configuration parameters are stored in a dedicated json file. The path of this file is passed as argument in centengine.cfg +Example: broker_module=lib/libopentelemetry.so /etc/centreon_engine/otl_server.json +In this file there are grpc server parameters and some other parameters. + diff --git a/engine/enginerpc/precomp_inc/precomp.hh b/engine/enginerpc/precomp_inc/precomp.hh index 42cc86b8b43..881d104529a 100644 --- a/engine/enginerpc/precomp_inc/precomp.hh +++ b/engine/enginerpc/precomp_inc/precomp.hh @@ -24,6 +24,7 @@ #include #include +#include #include diff --git a/engine/inc/com/centreon/engine/anomalydetection.hh b/engine/inc/com/centreon/engine/anomalydetection.hh index c608ba53de4..d11f3038023 100644 --- a/engine/inc/com/centreon/engine/anomalydetection.hh +++ b/engine/inc/com/centreon/engine/anomalydetection.hh @@ -23,7 +23,7 @@ #include #include -#include +#include #include #include "com/centreon/engine/service.hh" @@ -45,7 +45,7 @@ class anomalydetection : public service { public: threshold_point(time_t timepoint, double factor, - const nlohmann::json& json_data); + const rapidjson::Value& json_data); threshold_point(time_t timepoint); void set_factor(double factor); @@ -124,10 +124,10 @@ class anomalydetection : public service { void set_thresholds_lock(const std::string& filename, double json_sensitivity, - const nlohmann::json& thresholds); + const rapidjson::Value& thresholds); void set_thresholds_no_lock(const std::string& filename, double json_sensitivity, - const nlohmann::json& thresholds); + const rapidjson::Value& thresholds); void set_sensitivity(double sensitivity); double get_sensitivity() const { return _sensitivity; } @@ -152,7 +152,7 @@ class anomalydetection : public service { static const pointer_set& get_anomaly(uint64_t dependent_service_id); }; -} +} // namespace com::centreon::engine com::centreon::engine::anomalydetection* add_anomalydetection( uint64_t host_id, diff --git a/engine/inc/com/centreon/engine/checkable.hh b/engine/inc/com/centreon/engine/checkable.hh index 0d378c1fe52..60205ca6487 100644 --- a/engine/inc/com/centreon/engine/checkable.hh +++ b/engine/inc/com/centreon/engine/checkable.hh @@ -183,6 +183,7 @@ class checkable { * */ struct whitelist_last_result { + whitelist_last_result() : whitelist_instance_id(0), allowed(false) {} unsigned whitelist_instance_id; std::string process_cmd; bool allowed; @@ -240,6 +241,6 @@ class checkable { whitelist_last_result _whitelist_last_result; }; -} +} // namespace com::centreon::engine #endif /* !CCE_CHECKABLE */ diff --git a/engine/inc/com/centreon/engine/commands/otel_interface.hh b/engine/inc/com/centreon/engine/commands/otel_interface.hh new file mode 100644 index 00000000000..2d302e34409 --- /dev/null +++ b/engine/inc/com/centreon/engine/commands/otel_interface.hh @@ -0,0 +1,121 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#ifndef CCE_COMMANDS_OTEL_INTERFACE_HH +#define CCE_COMMANDS_OTEL_INTERFACE_HH + +#include "com/centreon/engine/commands/result.hh" +#include "com/centreon/engine/macros/defines.hh" + +namespace com::centreon::engine::commands::otel { + +/** + * @brief struct returned by otl_converter::extract_host_serv_metric + * success if host not empty + * service may be empty if it's a host check + * + */ +struct host_serv_metric { + std::string_view host; + std::string_view service; + std::string_view metric; + + bool operator<(const host_serv_metric& right) const { + int ret = host.compare(right.host); + if (ret < 0) + return true; + if (ret > 0) + return false; + ret = service.compare(right.service); + if (ret < 0) + return true; + if (ret > 0) + return false; + return metric.compare(right.metric) < 0; + } +}; + +/** + * @brief this list is the list of host service(may be empty) pairs + * This list is shared between otel_command and his extractor + * + */ +class host_serv_list { + absl::flat_hash_map> _data; + mutable std::mutex _data_m; + + public: + using pointer = std::shared_ptr; + + void register_host_serv(const std::string& host, + const std::string& service_description); + void unregister_host_serv(const std::string& host, + const std::string& service_description); + + bool is_allowed(const std::string& host, + const std::string& service_description) const; + + template + host_serv_metric is_allowed(const host_set& hosts, + const service_set& services) const; +}; + +template +host_serv_metric host_serv_list::is_allowed(const host_set& hosts, + const service_set& services) const { + host_serv_metric ret; + std::lock_guard l(_data_m); + for (const auto& host : hosts) { + auto host_search = _data.find(host); + if (host_search != _data.end()) { + const absl::flat_hash_set& allowed_services = + host_search->second; + if (services.empty() && allowed_services.contains("")) { + ret.host = host; + return ret; + } + for (const auto serv : services) { + if (allowed_services.contains(serv)) { + ret.host = host; + ret.service = serv; + return ret; + } + } + } + } + return ret; +} + +using result_callback = std::function; + +class open_telemetry_base; + +class open_telemetry_base + : public std::enable_shared_from_this { + protected: + static std::shared_ptr _instance; + + public: + virtual ~open_telemetry_base() = default; + + static std::shared_ptr& instance() { return _instance; } +}; + +}; // namespace com::centreon::engine::commands::otel + +#endif diff --git a/engine/modules/CMakeLists.txt b/engine/modules/CMakeLists.txt index 0a0fa235633..fc4be6d17d5 100644 --- a/engine/modules/CMakeLists.txt +++ b/engine/modules/CMakeLists.txt @@ -1,25 +1,29 @@ -## -## Copyright 2011-2013,2015 Merethis -## -## This file is part of Centreon Engine. -## -## Centreon Engine is free software: you can redistribute it and/or -## modify it under the terms of the GNU General Public License version 2 -## as published by the Free Software Foundation. -## -## Centreon Engine is distributed in the hope that it will be useful, -## but WITHOUT ANY WARRANTY; without even the implied warranty of -## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -## General Public License for more details. -## -## You should have received a copy of the GNU General Public License -## along with Centreon Engine. If not, see -## . -## +# +# Copyright 2024 Centreon +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may not +# use this file except in compliance with the License. You may obtain a copy of +# the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations under +# the License. +# +# For more information : contact@centreon.com +# # External commands module is required. add_subdirectory("external_commands") -set(EXTERNALCMD_MODULE "${EXTERNALCMD_MODULE}" PARENT_SCOPE) +set(EXTERNALCMD_MODULE + "${EXTERNALCMD_MODULE}" + PARENT_SCOPE) # Benchmark module. add_subdirectory("bench") + +# opentelemetry module +add_subdirectory("opentelemetry") diff --git a/engine/modules/opentelemetry/CMakeLists.txt b/engine/modules/opentelemetry/CMakeLists.txt new file mode 100644 index 00000000000..4214596366a --- /dev/null +++ b/engine/modules/opentelemetry/CMakeLists.txt @@ -0,0 +1,83 @@ +# +# Copyright 2024 Centreon +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may not +# use this file except in compliance with the License. You may obtain a copy of +# the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations under +# the License. +# +# For more information : contact@centreon.com +# + +# Set directories. +set(MODULE_DIR "${PROJECT_SOURCE_DIR}/modules/opentelemetry") +set(SRC_DIR "${MODULE_DIR}/src") + + +#protobuf service +set(service_files + opentelemetry/proto/collector/metrics/v1/metrics_service +) + +foreach(name IN LISTS service_files) + set(proto_file "${name}.proto") + add_custom_command( + OUTPUT "${SRC_DIR}/${name}.grpc.pb.cc" + COMMENT "Generating grpc files of the otl service file ${proto_file}" + DEPENDS opentelemetry-proto-files + COMMAND + ${Protobuf_PROTOC_EXECUTABLE} ARGS + --plugin=protoc-gen-grpc=${GRPC_CPP_PLUGIN} + --proto_path=${CMAKE_SOURCE_DIR}/opentelemetry-proto + --grpc_out=${SRC_DIR} ${proto_file} + VERBATIM + WORKING_DIRECTORY ${CMAKE_BINARY_DIR}) + +endforeach() + + +# mod_externalcmd target. +add_library(opentelemetry SHARED +${SRC_DIR}/grpc_config.cc +${SRC_DIR}/open_telemetry.cc +${SRC_DIR}/otl_config.cc +${SRC_DIR}/otl_data_point.cc +${SRC_DIR}/otl_server.cc +${SRC_DIR}/main.cc +${SRC_DIR}/opentelemetry/proto/collector/metrics/v1/metrics_service.grpc.pb.cc +) + +target_precompile_headers(opentelemetry PRIVATE precomp_inc/precomp.hh) + +# set(EXTERNALCMD_MODULE "${EXTERNALCMD_MODULE}" PARENT_SCOPE) +target_link_libraries(opentelemetry spdlog::spdlog) + +add_dependencies(opentelemetry + pb_open_telemetry_lib + pb_neb_lib + pb_tag_lib) + +target_include_directories(opentelemetry PRIVATE + "${MODULE_DIR}/inc/com/centreon/engine/modules/opentelemetry" + "${CMAKE_SOURCE_DIR}/bbdo" + "${MODULE_DIR}/inc" + ${CMAKE_SOURCE_DIR}/common/inc + ${CMAKE_SOURCE_DIR}/common/http/inc + ${CMAKE_SOURCE_DIR}/common/grpc/inc + src + ${PROJECT_SOURCE_DIR}/enginerpc + ${CMAKE_SOURCE_DIR}/common/src + ) + +# Install rule. +install( + TARGETS "opentelemetry" + DESTINATION "${ENGINE_MODULES_DIR}" + COMPONENT "runtime") diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/grpc_config.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/grpc_config.hh new file mode 100644 index 00000000000..a31149670f7 --- /dev/null +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/grpc_config.hh @@ -0,0 +1,48 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#ifndef CCE_MOD_OTL_SERVER_GRPC_CONFIG_HH +#define CCE_MOD_OTL_SERVER_GRPC_CONFIG_HH + +#include "com/centreon/common/grpc/grpc_config.hh" + +namespace com::centreon::engine::modules::opentelemetry { + +class grpc_config : public common::grpc::grpc_config { + static void read_file(const rapidjson::Value& json_config, + const std::string_view& key, + std::string& file_content); + + public: + using pointer = std::shared_ptr; + + grpc_config() {} + grpc_config(const std::string& hostp, bool crypted) + : common::grpc::grpc_config(hostp, crypted) {} + + grpc_config(const rapidjson::Value& json_config); + + bool operator==(const grpc_config& right) const; + + inline bool operator!=(const grpc_config& right) const { + return !(*this == right); + } +}; +} // namespace com::centreon::engine::modules::opentelemetry + +#endif // !CCE_MOD_OTL_SERVER_GRPC_CONFIG_HH diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/open_telemetry.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/open_telemetry.hh new file mode 100644 index 00000000000..d9206570b46 --- /dev/null +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/open_telemetry.hh @@ -0,0 +1,90 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ +#ifndef CCE_MOD_OTL_SERVER_OPENTELEMETRY_HH +#define CCE_MOD_OTL_SERVER_OPENTELEMETRY_HH + +#include "com/centreon/engine/commands/otel_interface.hh" + +#include "otl_config.hh" +#include "otl_data_point.hh" + +namespace com::centreon::engine::modules::opentelemetry { + +using host_serv_metric = commands::otel::host_serv_metric; + +class otl_server; + +/** + * @brief This class is the main high-level class of the otel module. + * It needs a json configuration file whose path is passed on loading, and an + * io_context for the second timer. The two methods used at runtime are + * create_extractor() and check(). a second period timer is also used to process + * check timeouts + * All attributes are (timers, _conf, _otl_server) are protected by _protect + * mutex + * + */ +class open_telemetry : public commands::otel::open_telemetry_base { + asio::system_timer _second_timer; + std::shared_ptr _otl_server; + + std::string _config_file_path; + std::unique_ptr _conf; + std::shared_ptr _logger; + + std::shared_ptr _io_context; + mutable std::mutex _protect; + + void _forward_to_broker(const std::vector& unknown); + + void _second_timer_handler(); + + protected: + virtual void _create_otl_server(const grpc_config::pointer& server_conf); + void _on_metric(const metric_request_ptr& metric); + void _reload(); + void _start_second_timer(); + void _shutdown(); + + public: + open_telemetry(const std::string_view config_file_path, + const std::shared_ptr& io_context, + const std::shared_ptr& logger); + + std::shared_ptr shared_from_this() { + return std::static_pointer_cast( + commands::otel::open_telemetry_base::shared_from_this()); + } + + static std::shared_ptr load( + const std::string_view& config_path, + const std::shared_ptr& io_context, + const std::shared_ptr& logger); + + static void reload(const std::shared_ptr& logger); + + static std::shared_ptr instance() { + return std::static_pointer_cast(_instance); + } + + static void unload(const std::shared_ptr& logger); +}; + +} // namespace com::centreon::engine::modules::opentelemetry + +#endif diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_config.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_config.hh new file mode 100644 index 00000000000..63db1e48e63 --- /dev/null +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_config.hh @@ -0,0 +1,57 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#ifndef CCE_MOD_OTL_SERVER_OTLCONFIG_HH +#define CCE_MOD_OTL_SERVER_OTLCONFIG_HH + +#include "grpc_config.hh" + +namespace com::centreon::engine::modules::opentelemetry { +class otl_config { + grpc_config::pointer _grpc_conf; + + int _max_length_grpc_log = -1; // all otel are logged if negative + bool _json_grpc_log = false; // if true, otel object are logged in json + // format instead of protobuf debug format + + // this two attributes are limits used by otel data_point fifos + // if fifo size exceed _max_fifo_size, oldest data_points are removed + // Also, data_points older than _second_fifo_expiry are removed from fifos + unsigned _second_fifo_expiry; + size_t _max_fifo_size; + + public: + otl_config(const std::string_view& file_path, asio::io_context& io_context); + + grpc_config::pointer get_grpc_config() const { return _grpc_conf; } + + int get_max_length_grpc_log() const { return _max_length_grpc_log; } + bool get_json_grpc_log() const { return _json_grpc_log; } + + unsigned get_second_fifo_expiry() const { return _second_fifo_expiry; } + size_t get_max_fifo_size() const { return _max_fifo_size; } + + bool operator==(const otl_config& right) const; + + inline bool operator!=(const otl_config& right) const { + return !(*this == right); + } +}; + +} // namespace com::centreon::engine::modules::opentelemetry +#endif \ No newline at end of file diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_data_point.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_data_point.hh new file mode 100644 index 00000000000..0011fc1617a --- /dev/null +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_data_point.hh @@ -0,0 +1,211 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#ifndef CCE_MOD_OTL_SERVER_METRIC_HH +#define CCE_MOD_OTL_SERVER_METRIC_HH + +namespace com::centreon::engine::modules::opentelemetry { + +/** + * @brief pair with host_name in first and serv in second + * + */ +using host_serv = std::pair; + +/** + * @brief This struct is used to lookup in a host_serv indexed container with + * a std::pair + * + */ +struct host_serv_hash_eq { + using is_transparent = void; + using host_serv_string_view = std::pair; + + size_t operator()(const host_serv& to_hash) const { + return absl::Hash()(to_hash); + } + size_t operator()(const host_serv_string_view& to_hash) const { + return absl::Hash()(to_hash); + } + + bool operator()(const host_serv& left, const host_serv& right) const { + return left == right; + } + bool operator()(const host_serv& left, + const host_serv_string_view& right) const { + return left.first == right.first && left.second == right.second; + } + bool operator()(const host_serv_string_view& left, + const host_serv& right) const { + return left.first == right.first && left.second == right.second; + } + bool operator()(const host_serv_string_view& left, + const host_serv_string_view& right) const { + return left == right; + } +}; + +using metric_request_ptr = + std::shared_ptr<::opentelemetry::proto::collector::metrics::v1:: + ExportMetricsServiceRequest>; + +/** + * @brief some metrics will be computed and other not + * This bean represents a DataPoint, it embeds all ExportMetricsServiceRequest + * (_parent attribute) in order to avoid useless copies. Many attributes are + * references to _parent attribute + * As we can receive several types of data_point, we tries to expose common data + * by unique getters + */ +class data_point { + public: + enum class data_point_type { + number, + histogram, + exponential_histogram, + summary + }; + + private: + const metric_request_ptr _parent; + const ::opentelemetry::proto::resource::v1::Resource& _resource; + const ::opentelemetry::proto::common::v1::InstrumentationScope& _scope; + const ::opentelemetry::proto::metrics::v1::Metric& _metric; + const google::protobuf::Message& _data_point; + const ::google::protobuf::RepeatedPtrField< + ::opentelemetry::proto::common::v1::KeyValue>& _data_point_attributes; + uint64_t _nano_timestamp; + data_point_type _type; + double _value; + + data_point( + const metric_request_ptr& parent, + const ::opentelemetry::proto::resource::v1::Resource& resource, + const ::opentelemetry::proto::common::v1::InstrumentationScope& scope, + const ::opentelemetry::proto::metrics::v1::Metric& metric, + const ::opentelemetry::proto::metrics::v1::NumberDataPoint& data_pt); + + data_point( + const metric_request_ptr& parent, + const ::opentelemetry::proto::resource::v1::Resource& resource, + const ::opentelemetry::proto::common::v1::InstrumentationScope& scope, + const ::opentelemetry::proto::metrics::v1::Metric& metric, + const ::opentelemetry::proto::metrics::v1::HistogramDataPoint& data_pt); + + data_point( + const metric_request_ptr& parent, + const ::opentelemetry::proto::resource::v1::Resource& resource, + const ::opentelemetry::proto::common::v1::InstrumentationScope& scope, + const ::opentelemetry::proto::metrics::v1::Metric& metric, + const ::opentelemetry::proto::metrics::v1::ExponentialHistogramDataPoint& + data_pt); + + data_point( + const metric_request_ptr& parent, + const ::opentelemetry::proto::resource::v1::Resource& resource, + const ::opentelemetry::proto::common::v1::InstrumentationScope& scope, + const ::opentelemetry::proto::metrics::v1::Metric& metric, + const ::opentelemetry::proto::metrics::v1::SummaryDataPoint& data_pt); + + public: + const ::opentelemetry::proto::resource::v1::Resource& get_resource() const { + return _resource; + } + + const ::opentelemetry::proto::common::v1::InstrumentationScope& get_scope() + const { + return _scope; + } + + const ::opentelemetry::proto::metrics::v1::Metric& get_metric() const { + return _metric; + } + + const google::protobuf::Message& get_data_point() const { + return _data_point; + } + + uint64_t get_nano_timestamp() const { return _nano_timestamp; } + + data_point_type get_type() { return _type; } + + const ::google::protobuf::RepeatedPtrField< + ::opentelemetry::proto::common::v1::KeyValue>& + get_data_point_attributes() const { + return _data_point_attributes; + } + + double get_value() const { return _value; } + + template + static void extract_data_points(const metric_request_ptr& metrics, + data_point_handler&& handler); +}; + +/** + * @brief extracts all data_points from an ExportMetricsServiceRequest object + * + * @tparam data_point_handler + * @param metrics + * @param handler called on every data point found + */ +template +void data_point::extract_data_points(const metric_request_ptr& metrics, + data_point_handler&& handler) { + using namespace ::opentelemetry::proto::metrics::v1; + for (const ResourceMetrics& resource_metric : metrics->resource_metrics()) { + const ::opentelemetry::proto::resource::v1::Resource& resource = + resource_metric.resource(); + for (const ScopeMetrics& scope_metrics : resource_metric.scope_metrics()) { + const ::opentelemetry::proto::common::v1::InstrumentationScope& scope = + scope_metrics.scope(); + + for (const Metric& pb_metric : scope_metrics.metrics()) { + switch (pb_metric.data_case()) { + case Metric::kGauge: + for (const NumberDataPoint& iter : pb_metric.gauge().data_points()) + handler(data_point(metrics, resource, scope, pb_metric, iter)); + break; + case Metric::kSum: + for (const NumberDataPoint& iter : pb_metric.sum().data_points()) + handler(data_point(metrics, resource, scope, pb_metric, iter)); + break; + case Metric::kHistogram: + for (const HistogramDataPoint& iter : + pb_metric.histogram().data_points()) + handler(data_point(metrics, resource, scope, pb_metric, iter)); + break; + case Metric::kExponentialHistogram: + for (const ExponentialHistogramDataPoint& iter : + pb_metric.exponential_histogram().data_points()) + handler(data_point(metrics, resource, scope, pb_metric, iter)); + break; + case Metric::kSummary: + for (const SummaryDataPoint& iter : + pb_metric.summary().data_points()) + handler(data_point(metrics, resource, scope, pb_metric, iter)); + break; + } + } + } + } +} + +}; // namespace com::centreon::engine::modules::opentelemetry + +#endif \ No newline at end of file diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_fmt.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_fmt.hh new file mode 100644 index 00000000000..c50048a6d0b --- /dev/null +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_fmt.hh @@ -0,0 +1,68 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#ifndef CCE_MOD_OTL_SERVER_OTL_FMT_HH +#define CCE_MOD_OTL_SERVER_OTL_FMT_HH + +#include + +namespace fmt { + +/** + * @brief this specialization is used by fmt to dump an + * ExportMetricsServiceRequest + * + * @code {.c++} + * ::opentelemetry::proto::collector::metrics::v1::ExportMetricsServiceRequest + * request; SPDLOG_LOGGER_TRACE(log_v2::otl(), "receive {}", request); + * @endcode + * + * + */ +template <> +struct formatter< + ::opentelemetry::proto::collector::metrics::v1::ExportMetricsServiceRequest> + : formatter { + /** + * @brief if this static parameter is < 0, we dump all request, otherwise, we + * limit dump length to this value + * + */ + static int max_length_log; + static bool json_grpc_format; + template + auto format(const ::opentelemetry::proto::collector::metrics::v1:: + ExportMetricsServiceRequest& p, + FormatContext& ctx) const -> decltype(ctx.out()) { + if (json_grpc_format) { + std::string output; + google::protobuf::util::MessageToJsonString(p, &output); + return formatter::format( + max_length_log > 0 ? output.substr(0, max_length_log) : output, ctx); + } else { + return formatter::format( + max_length_log > 0 ? p.ShortDebugString().substr(0, max_length_log) + : p.ShortDebugString(), + ctx); + } + } +}; + +}; // namespace fmt + +#endif diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_server.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_server.hh new file mode 100644 index 00000000000..0dd766bb982 --- /dev/null +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_server.hh @@ -0,0 +1,66 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#ifndef CCE_MOD_OTL_SERVER_OTLSERVER_HH +#define CCE_MOD_OTL_SERVER_OTLSERVER_HH + +#include "grpc_config.hh" + +#include "otl_data_point.hh" + +#include "com/centreon/common/grpc/grpc_server.hh" + +namespace com::centreon::engine::modules::opentelemetry { + +namespace detail { +class metric_service; +}; + +/** + * @brief the server grpc model used is the callback model + * So you need to give to the server this handler to handle incoming requests + * + */ +using metric_handler = std::function; + +/** + * @brief grpc metric receiver server + * must be constructed with load method + * + */ +class otl_server : public common::grpc::grpc_server_base { + std::shared_ptr _service; + + otl_server(const grpc_config::pointer& conf, + const metric_handler& handler, + const std::shared_ptr& logger); + void start(); + + public: + using pointer = std::shared_ptr; + + ~otl_server(); + + static pointer load(const grpc_config::pointer& conf, + const metric_handler& handler, + const std::shared_ptr& logger); +}; + +} // namespace com::centreon::engine::modules::opentelemetry + +#endif diff --git a/engine/modules/opentelemetry/precomp_inc/precomp.hh b/engine/modules/opentelemetry/precomp_inc/precomp.hh new file mode 100644 index 00000000000..1a2550abd95 --- /dev/null +++ b/engine/modules/opentelemetry/precomp_inc/precomp.hh @@ -0,0 +1,62 @@ +/** + * Copyright 2024 Centreon (https://www.centreon.com/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ + +#ifndef CCE_MOD_OTL_SERVER_PRECOMP_HH +#define CCE_MOD_OTL_SERVER_PRECOMP_HH + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +namespace asio = boost::asio; +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include + +#include + +#include "opentelemetry/proto/collector/metrics/v1/metrics_service.pb.h" +#include "opentelemetry/proto/common/v1/common.pb.h" +#include "opentelemetry/proto/metrics/v1/metrics.pb.h" + +#include "com/centreon/common/http/http_server.hh" +#include "com/centreon/common/rapidjson_helper.hh" + +#include "com/centreon/exceptions/msg_fmt.hh" + +#endif diff --git a/engine/modules/opentelemetry/src/grpc_config.cc b/engine/modules/opentelemetry/src/grpc_config.cc new file mode 100644 index 00000000000..0cf4569f2ff --- /dev/null +++ b/engine/modules/opentelemetry/src/grpc_config.cc @@ -0,0 +1,164 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#include "grpc_config.hh" +#include "com/centreon/common/rapidjson_helper.hh" +#include "com/centreon/engine/globals.hh" + +using com::centreon::common::rapidjson_helper; + +static constexpr std::string_view _grpc_config_schema(R"( +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "title": "grpc config", + "properties": { + "host": { + "description": "IP or dns name", + "type": "string", + "minLength": 5 + }, + "port": { + "description": "port to listen", + "type": "integer", + "minimum": 1024, + "maximum": 65535 + }, + "encryption": { + "description": "true if https", + "type": "boolean" + }, + "public_cert": { + "description": "path of certificate file .crt", + "type": "string" + }, + "private_key": { + "description": "path of certificate file .key", + "type": "string" + }, + "ca_certificate": { + "description": "path of authority certificate file .crt", + "type": "string" + }, + "ca_name": { + "description": "name of authority certificate", + "type": "string" + }, + "compression": { + "description": "activate compression", + "type": "boolean" + }, + "keepalive_interval": { + "description": "delay between 2 keepalive tcp packet", + "type": "integer", + "minimum": -1, + "maximum": 3600 + } + }, + "required": [ + "host", + "port" + ], + "type": "object" +} + +)"); + +using namespace com::centreon::engine::modules::opentelemetry; + +/** + * @brief Construct a new grpc config::grpc config object + * + * @param json_config_v content of the json config file + */ +grpc_config::grpc_config(const rapidjson::Value& json_config_v) { + common::rapidjson_helper json_config(json_config_v); + + static common::json_validator validator(_grpc_config_schema); + try { + json_config.validate(validator); + } catch (const std::exception& e) { + SPDLOG_LOGGER_ERROR(config_logger, + "forbidden values in grpc otl config: {}", e.what()); + throw; + } + + std::string hostport = fmt::format("{}:{}", json_config.get_string("host"), + json_config.get_unsigned("port")); + bool crypted = false; + std::string certificate, cert_key, ca_cert; + std::string ca_name; + bool compress = false; + int second_keepalive_interval; + + if (json_config.has_member("encryption")) + crypted = json_config.get_bool("encryption"); + + read_file(json_config_v, "public_cert", certificate); + read_file(json_config_v, "private_key", cert_key); + read_file(json_config_v, "ca_certificate", ca_cert); + if (json_config.has_member("ca_name")) + ca_name = json_config.get_string("ca_name"); + if (json_config.has_member("compression")) + compress = json_config.get_bool("compression"); + + if (json_config.has_member("keepalive_interval")) + second_keepalive_interval = json_config.get_int("keepalive_interval"); + else + second_keepalive_interval = 30; + + static_cast(*this) = common::grpc::grpc_config( + hostport, crypted, certificate, cert_key, ca_cert, ca_name, compress, + second_keepalive_interval); +} + +/** + * @brief read a file as certificate + * + * @param json_config + * @param key json key that contains file path + * @param file_content out: file content + */ +void grpc_config::read_file(const rapidjson::Value& json_config, + const std::string_view& key, + std::string& file_content) { + std::string path; + try { + path = rapidjson_helper(json_config).get_string(key.data()); + } catch (const std::exception&) { + return; + } + try { + boost::trim(path); + if (path.empty()) { + return; + } + std::ifstream file(path); + std::stringstream ss; + ss << file.rdbuf(); + file.close(); + file_content = ss.str(); + } catch (const std::exception& e) { + SPDLOG_LOGGER_ERROR(config_logger, "fail to read {}: {}", path, e.what()); + throw; + } +} + +bool grpc_config::operator==(const grpc_config& right) const { + return static_cast(*this) == + static_cast(right); +} diff --git a/engine/modules/opentelemetry/src/main.cc b/engine/modules/opentelemetry/src/main.cc new file mode 100644 index 00000000000..da9d40945c6 --- /dev/null +++ b/engine/modules/opentelemetry/src/main.cc @@ -0,0 +1,121 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#include "com/centreon/engine/nebmods.hh" +#include "com/centreon/engine/nebmodules.hh" +#include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" + +#include "com/centreon/engine/modules/opentelemetry/open_telemetry.hh" + +using namespace com::centreon::engine; +using namespace com::centreon::engine::modules::opentelemetry; +using namespace com::centreon::exceptions; +using log_v2 = com::centreon::common::log_v2::log_v2; + +// Specify the event broker API version. +NEB_API_VERSION(CURRENT_NEB_API_VERSION) + +// Module handle +static void* gl_mod_handle(NULL); + +extern std::shared_ptr g_io_context; + +/************************************** + * * + * Exported Functions * + * * + **************************************/ + +/** + * @brief Module exit point. + * + * This function is called when the module gets unloaded by Centreon-Engine. + * It will deregister all previously registered callbacks and perform + * some shutdown stuff. + * + * @param[in] flags Unused. + * @param[in] reason Unused. + * + * @return 0 on success, any other value on failure. + */ +extern "C" int nebmodule_deinit(int /*flags*/, int /*reason*/) { + open_telemetry::unload(log_v2::instance().get(log_v2::OTEL)); + return 0; +} + +/** + * @brief Module entry point. + * + * This function is called when the module gets loaded by Centreon-Engine. It + * will register callbacks to catch events and perform some initialization + * stuff like config file parsing, thread creation, ... + * + * @param[in] flags Unused. + * @param[in] args Unused. + * @param[in] handle The module handle. + * + * @return 0 on success, any other value on failure. + */ +extern "C" int nebmodule_init(int flags, char const* args, void* handle) { + (void)args; + (void)flags; + + // Save module handle for future use. + gl_mod_handle = handle; + + // Set module informations. + neb_set_module_info(gl_mod_handle, NEBMODULE_MODINFO_TITLE, + "Centreon-Engine's OpenTelemetry module"); + neb_set_module_info(gl_mod_handle, NEBMODULE_MODINFO_AUTHOR, "Merethis"); + neb_set_module_info(gl_mod_handle, NEBMODULE_MODINFO_COPYRIGHT, + "Copyright 2024 Centreon"); + neb_set_module_info(gl_mod_handle, NEBMODULE_MODINFO_VERSION, "1.0.0"); + neb_set_module_info(gl_mod_handle, NEBMODULE_MODINFO_LICENSE, + "GPL version 2"); + neb_set_module_info( + gl_mod_handle, NEBMODULE_MODINFO_DESC, + "Centreon-Engine's open telemetry grpc server. It provides grpc otl " + "server and inject incomming metrics in centreon system."); + + std::string_view conf_file_path; + if (args) { + const std::string_view config_file("config_file="); + const std::string_view arg(args); + if (!config_file.compare(0, config_file.length(), arg)) { + conf_file_path = arg.substr(config_file.length()); + } else { + conf_file_path = arg; + } + } else + throw msg_fmt("main: no configuration file provided"); + + open_telemetry::load(conf_file_path, g_io_context, + log_v2::instance().get(log_v2::OTEL)); + + return 0; +} + +/** + * @brief Reload module after configuration reload. + * + */ +extern "C" int nebmodule_reload() { + open_telemetry::reload(log_v2::instance().get(log_v2::OTEL)); + return 0; +} diff --git a/engine/modules/opentelemetry/src/open_telemetry.cc b/engine/modules/opentelemetry/src/open_telemetry.cc new file mode 100644 index 00000000000..8babb8cb317 --- /dev/null +++ b/engine/modules/opentelemetry/src/open_telemetry.cc @@ -0,0 +1,279 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#include "com/centreon/exceptions/msg_fmt.hh" + +#include "com/centreon/engine/modules/opentelemetry/open_telemetry.hh" + +#include "otl_fmt.hh" +#include "otl_server.hh" + +using namespace com::centreon::engine::modules::opentelemetry; + +/** + * @brief Construct a new open telemetry::open telemetry object + * + * @param config_file_path + * @param io_context + */ +open_telemetry::open_telemetry( + const std::string_view config_file_path, + const std::shared_ptr& io_context, + const std::shared_ptr& logger) + : _second_timer(*io_context), + _config_file_path(config_file_path), + _logger(logger), + _io_context(io_context) { + SPDLOG_LOGGER_INFO(_logger, "load of open telemetry module"); +} + +/** + * @brief to call when configuration changes + * + */ +void open_telemetry::_reload() { + std::unique_ptr new_conf = + std::make_unique(_config_file_path, *_io_context); + if (!_conf || *new_conf->get_grpc_config() != *_conf->get_grpc_config()) { + this->_create_otl_server(new_conf->get_grpc_config()); + } + + if (!_conf || *_conf != *new_conf) { + fmt::formatter<::opentelemetry::proto::collector::metrics::v1:: + ExportMetricsServiceRequest>::max_length_log = + new_conf->get_max_length_grpc_log(); + fmt::formatter<::opentelemetry::proto::collector::metrics::v1:: + ExportMetricsServiceRequest>::json_grpc_format = + new_conf->get_json_grpc_log(); + + _conf = std::move(new_conf); + } +} + +/** + * @brief static creator of singleton + * + * @param config_path + * @param io_context + * @return std::shared_ptr + */ +std::shared_ptr open_telemetry::load( + const std::string_view& config_path, + const std::shared_ptr& io_context, + const std::shared_ptr& logger) { + if (!_instance) { + _instance = + std::make_shared(config_path, io_context, logger); + instance()->_reload(); + instance()->_start_second_timer(); + } + return instance(); +} + +/** + * @brief create grpc server witch accept otel collector connections + * + * @param server_conf json server config + */ +void open_telemetry::_create_otl_server( + const grpc_config::pointer& server_conf) { + try { + std::shared_ptr to_shutdown = std::move(_otl_server); + if (to_shutdown) { + to_shutdown->shutdown(std::chrono::seconds(10)); + } + _otl_server = otl_server::load( + server_conf, + [me = shared_from_this()](const metric_request_ptr& request) { + me->_on_metric(request); + }, + _logger); + } catch (const std::exception& e) { + SPDLOG_LOGGER_ERROR(_logger, "fail to create opentelemetry grpc server: {}", + e.what()); + throw; + } +} + +/** + * @brief static method used to make singleton reload is configuration + * + */ +void open_telemetry::reload(const std::shared_ptr& logger) { + if (_instance) { + try { + SPDLOG_LOGGER_INFO(logger, "reload of open telemetry module"); + instance()->_reload(); + } catch (const std::exception& e) { + SPDLOG_LOGGER_ERROR( + logger, + "bad configuration, new configuration not taken into account: {}", + e.what()); + } + } +} + +/** + * @brief shutdown singleton and dereference it. It may continue to live until + * no object has a reference on it + * + */ +void open_telemetry::unload(const std::shared_ptr& logger) { + if (_instance) { + SPDLOG_LOGGER_INFO(logger, "unload of open telemetry module"); + instance()->_shutdown(); + _instance.reset(); + } +} + +/** + * @brief shutdown grpc server and stop second timer + * + */ +void open_telemetry::_shutdown() { + std::shared_ptr to_shutdown = std::move(_otl_server); + if (to_shutdown) { + to_shutdown->shutdown(std::chrono::seconds(10)); + } + std::lock_guard l(_protect); + _second_timer.cancel(); +} + +/** + * @brief called on metric reception + * we first fill data_point fifos and then if a converter of a service is + * waiting for data_point, we call him. If it achieve to generate a check + * result, the handler of otl_converter is called + * unknown metrics are passed to _forward_to_broker + * + * @param metrics collector request + */ +void open_telemetry::_on_metric(const metric_request_ptr& metrics) { + std::vector unknown; + { + std::lock_guard l(_protect); + // if (_extractors.empty()) { + // data_point::extract_data_points(metrics, + // [&unknown](const data_point& data_pt) { + // unknown.push_back(data_pt); + // }); + // } else { + // waiting_converter::nth_index<0>::type& host_serv_index = + // _waiting.get<0>(); + // std::vector> to_notify; + // auto last_success = _extractors.begin(); + // data_point::extract_data_points(metrics, [this, &unknown, + // &last_success, + // &host_serv_index, + // &to_notify]( + // const data_point& data_pt) + // { + // bool data_point_known = false; + // // we try all extractors and we begin with the last witch has + // // achieved to extract host + // for (unsigned tries = 0; tries < _extractors.size(); ++tries) { + // host_serv_metric hostservmetric = + // last_success->second->extract_host_serv_metric(data_pt); + + // if (!hostservmetric.host.empty()) { + // _fifo.add_data_point(hostservmetric.host, hostservmetric.service, + // hostservmetric.metric, data_pt); + + // auto waiting = host_serv_index.equal_range( + // host_serv{hostservmetric.host, hostservmetric.service}); + // while (waiting.first != waiting.second) { + // to_notify.push_back(*waiting.first); + // waiting.first = host_serv_index.erase(waiting.first); + // } + // data_point_known = true; + // break; + // } + // ++last_success; + // if (last_success == _extractors.end()) { + // last_success = _extractors.begin(); + // } + // } + // if (!data_point_known) { + // unknown.push_back(data_pt); // unknown metric => forward to broker + // } + // }); + // SPDLOG_LOGGER_TRACE(_logger, "fifos:{}", _fifo); + // // we wait that all request datas have been computed to give us more + // // chance of converter success + // for (auto to_callback : to_notify) { + // if (!to_callback->async_build_result_from_metrics( + // _fifo)) { // not enough data => repush in _waiting + // _waiting.insert(to_callback); + // } + // } + // SPDLOG_LOGGER_TRACE(_logger, "fifos:{}", _fifo); + // } + } + if (!unknown.empty()) { + SPDLOG_LOGGER_TRACE(_logger, "{} unknown data_points", unknown.size()); + _forward_to_broker(unknown); + } +} + +/** + * @brief the second timer is used to handle converter timeouts + * + */ +void open_telemetry::_start_second_timer() { + std::lock_guard l(_protect); + _second_timer.expires_from_now(std::chrono::seconds(1)); + _second_timer.async_wait( + [me = shared_from_this()](const boost::system::error_code& err) { + if (!err) { + me->_second_timer_handler(); + } + }); +} + +/** + * @brief notify all timeouts + * + */ +void open_telemetry::_second_timer_handler() { + // std::vector> to_notify; + { + std::lock_guard l(_protect); + std::chrono::system_clock::time_point now = + std::chrono::system_clock::now(); + // waiting_converter::nth_index<1>::type& expiry_index = _waiting.get<1>(); + // while (!_waiting.empty()) { + // auto oldest = expiry_index.begin(); + // if ((*oldest)->get_time_out() > now) { + // break; + // } + // to_notify.push_back(*oldest); + // expiry_index.erase(oldest); + // } + } + + // notify all timeout + // for (std::shared_ptr to_not : to_notify) { + // SPDLOG_LOGGER_DEBUG(_logger, "time out: {}", *to_not); + // to_not->async_time_out(); + // } + + _start_second_timer(); +} + +void open_telemetry::_forward_to_broker( + const std::vector& unknown) {} diff --git a/engine/modules/opentelemetry/src/otl_config.cc b/engine/modules/opentelemetry/src/otl_config.cc new file mode 100644 index 00000000000..b4122d52784 --- /dev/null +++ b/engine/modules/opentelemetry/src/otl_config.cc @@ -0,0 +1,109 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#include "com/centreon/common/rapidjson_helper.hh" + +#include "otl_config.hh" +#include "otl_fmt.hh" + +int fmt::formatter< ::opentelemetry::proto::collector::metrics::v1:: + ExportMetricsServiceRequest>::max_length_log = -1; + +bool fmt::formatter< ::opentelemetry::proto::collector::metrics::v1:: + ExportMetricsServiceRequest>::json_grpc_format = false; + +using namespace com::centreon::engine::modules::opentelemetry; +using namespace com::centreon::common; + +static constexpr std::string_view _grpc_config_schema(R"( +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "title": "opentelemetry config", + "properties": { + "max_length_grpc_log": { + "description:": "max dump length of a otel grpc object", + "type": "integer", + "min": -1 + }, + "grpc_json_log": { + "description": "true if we log otl grpc object to json format", + "type": "boolean" + }, + "second_fifo_expiry": { + "description:": "lifetime of data points in fifos", + "type": "integer", + "min": 30 + }, + "max_fifo_size": { + "description:": "max number of data points in fifos", + "type": "integer", + "min": 1 + }, + "server": { + "description": "otel grpc config", + "type": "object" + } + }, + "required": [ + "server" + ], + "type": "object" +} +)"); + +/** + * @brief Construct a new otl config::otl config object + * + * @param file_path path of the config file + * @throw msg fmt if file can not be read or if json content is not accepted by + * validator + */ +otl_config::otl_config(const std::string_view& file_path, + asio::io_context& io_context) { + static json_validator validator(_grpc_config_schema); + rapidjson::Document file_content_d = + rapidjson_helper::read_from_file(file_path); + + rapidjson_helper file_content(file_content_d); + + file_content.validate(validator); + _max_length_grpc_log = file_content.get_unsigned("max_length_grpc_log", 400); + _json_grpc_log = file_content.get_bool("grpc_json_log", false); + _second_fifo_expiry = file_content.get_unsigned("second_fifo_expiry", 600); + _max_fifo_size = file_content.get_unsigned("max_fifo_size", 5); + _grpc_conf = std::make_shared(file_content.get_member("server")); +} + +/** + * @brief compare two otl_config + * + * @param right + * @return true if are equals + * @return false + */ +bool otl_config::operator==(const otl_config& right) const { + if (!_grpc_conf || !right._grpc_conf) { + return false; + } + bool ret = *_grpc_conf == *right._grpc_conf && + _max_length_grpc_log == right._max_length_grpc_log && + _json_grpc_log == right._json_grpc_log && + _second_fifo_expiry == right._second_fifo_expiry && + _max_fifo_size == right._max_fifo_size; + return ret; +} diff --git a/engine/modules/opentelemetry/src/otl_data_point.cc b/engine/modules/opentelemetry/src/otl_data_point.cc new file mode 100644 index 00000000000..0b7811b6fe1 --- /dev/null +++ b/engine/modules/opentelemetry/src/otl_data_point.cc @@ -0,0 +1,91 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#include "otl_data_point.hh" + +using namespace com::centreon::engine::modules::opentelemetry; +using namespace ::opentelemetry::proto::metrics::v1; + +data_point::data_point( + const metric_request_ptr& parent, + const ::opentelemetry::proto::resource::v1::Resource& resource, + const ::opentelemetry::proto::common::v1::InstrumentationScope& scope, + const ::opentelemetry::proto::metrics::v1::Metric& metric, + const ::opentelemetry::proto::metrics::v1::NumberDataPoint& data_pt) + : _parent(parent), + _resource(resource), + _scope(scope), + _metric(metric), + _data_point(data_pt), + _data_point_attributes(data_pt.attributes()), + _nano_timestamp(data_pt.time_unix_nano()), + _type(data_point_type::number) { + _value = data_pt.as_double() ? data_pt.as_double() : data_pt.as_int(); +} + +data_point::data_point( + const metric_request_ptr& parent, + const ::opentelemetry::proto::resource::v1::Resource& resource, + const ::opentelemetry::proto::common::v1::InstrumentationScope& scope, + const ::opentelemetry::proto::metrics::v1::Metric& metric, + const ::opentelemetry::proto::metrics::v1::HistogramDataPoint& data_pt) + : _parent(parent), + _resource(resource), + _scope(scope), + _metric(metric), + _data_point(data_pt), + _data_point_attributes(data_pt.attributes()), + _nano_timestamp(data_pt.time_unix_nano()), + _type(data_point_type::histogram) { + _value = data_pt.count(); +} + +data_point::data_point( + const metric_request_ptr& parent, + const ::opentelemetry::proto::resource::v1::Resource& resource, + const ::opentelemetry::proto::common::v1::InstrumentationScope& scope, + const ::opentelemetry::proto::metrics::v1::Metric& metric, + const ::opentelemetry::proto::metrics::v1::ExponentialHistogramDataPoint& + data_pt) + : _parent(parent), + _resource(resource), + _scope(scope), + _metric(metric), + _data_point(data_pt), + _data_point_attributes(data_pt.attributes()), + _nano_timestamp(data_pt.time_unix_nano()), + _type(data_point_type::exponential_histogram) { + _value = data_pt.count(); +} + +data_point::data_point( + const metric_request_ptr& parent, + const ::opentelemetry::proto::resource::v1::Resource& resource, + const ::opentelemetry::proto::common::v1::InstrumentationScope& scope, + const ::opentelemetry::proto::metrics::v1::Metric& metric, + const ::opentelemetry::proto::metrics::v1::SummaryDataPoint& data_pt) + : _parent(parent), + _resource(resource), + _scope(scope), + _metric(metric), + _data_point(data_pt), + _data_point_attributes(data_pt.attributes()), + _nano_timestamp(data_pt.time_unix_nano()), + _type(data_point_type::summary) { + _value = data_pt.count(); +} diff --git a/engine/modules/opentelemetry/src/otl_server.cc b/engine/modules/opentelemetry/src/otl_server.cc new file mode 100644 index 00000000000..b6b9097df78 --- /dev/null +++ b/engine/modules/opentelemetry/src/otl_server.cc @@ -0,0 +1,324 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#include +#include + +#include "opentelemetry/proto/collector/metrics/v1/metrics_service.grpc.pb.h" + +#include "otl_fmt.hh" +#include "otl_server.hh" + +namespace otl_col_metrics = ::opentelemetry::proto::collector::metrics::v1; +using namespace com::centreon::engine::modules::opentelemetry; + +namespace com::centreon::engine::modules::opentelemetry::detail { + +class request_response_allocator; +/** + * @brief the goal of this class is to work with shared_ptr + * + */ +class request_response_holder + : public ::grpc::MessageHolder< + otl_col_metrics::ExportMetricsServiceRequest, + otl_col_metrics::ExportMetricsServiceResponse> { + metric_request_ptr _request; + otl_col_metrics::ExportMetricsServiceResponse _response; + std::weak_ptr _allocator; + + public: + request_response_holder( + const std::shared_ptr& allocator) + : _request( + std::make_shared()), + _allocator(allocator) { + set_request(_request.get()); + set_response(&_response); + } + + const metric_request_ptr& get_request() const { return _request; } + + void Release() override; +}; + +/** + * @brief this allocator creates request_response_holder and stores request + * shared pointers + * + */ +class request_response_allocator + : public ::grpc::MessageAllocator< + otl_col_metrics::ExportMetricsServiceRequest, + otl_col_metrics::ExportMetricsServiceResponse>, + public std::enable_shared_from_this { + absl::btree_map + _allocated; + absl::Mutex _protect; + + public: + metric_request_ptr get_metric_request_ptr_from_raw( + const otl_col_metrics::ExportMetricsServiceRequest* raw_request); + + void release_request( + const otl_col_metrics::ExportMetricsServiceRequest* raw_request); + + ::grpc::MessageHolder* + AllocateMessages() override; +}; + +/** + * @brief grpc layers work with raw pointer, this method return shared_ptr from + * raw pointer + * + * @param raw_request request raw pointer + * @return metric_request_ptr shared_ptr that holds raw_request + */ +metric_request_ptr request_response_allocator::get_metric_request_ptr_from_raw( + const otl_col_metrics::ExportMetricsServiceRequest* raw_request) { + absl::MutexLock l(&_protect); + auto found = _allocated.find(raw_request); + if (found != _allocated.end()) { + return found->second; + } + return metric_request_ptr(); +} + +/** + * @brief this objects stores relationship between raw pointer and shared_ptr. + * This method releases a relationship + * + * @param raw_request + */ +void request_response_allocator::release_request( + const otl_col_metrics::ExportMetricsServiceRequest* raw_request) { + absl::MutexLock l(&_protect); + _allocated.erase(raw_request); +} + +/** + * @brief allocate a request response pair and store relationship between raw + * request pointer and shared_ptr + * + * @return ::grpc::MessageHolder* + */ +::grpc::MessageHolder* +request_response_allocator::AllocateMessages() { + request_response_holder* ret = + new request_response_holder(shared_from_this()); + absl::MutexLock l(&_protect); + _allocated.emplace(ret->request(), ret->get_request()); + return ret; +} + +/** + * @brief destructor of request_response_holder called by grpc layers + * it also call request_response_allocator::release_request + * + */ +void request_response_holder::Release() { + auto alloc = _allocator.lock(); + if (alloc) + alloc->release_request(request()); + delete this; +} + +/** + * @brief grpc metric service + * we make a custom WithCallbackMethod_Export in order to use a shared ptr + * instead a raw pointer + */ +class metric_service : public ::opentelemetry::proto::collector::metrics::v1:: + MetricsService::Service, + public std::enable_shared_from_this { + std::shared_ptr _allocator; + metric_handler _request_handler; + std::shared_ptr _logger; + + void init(); + + void SetMessageAllocatorFor_Export( + ::grpc::MessageAllocator<::opentelemetry::proto::collector::metrics::v1:: + ExportMetricsServiceRequest, + ::opentelemetry::proto::collector::metrics::v1:: + ExportMetricsServiceResponse>* allocator) { + ::grpc::internal::MethodHandler* const handler = + ::grpc::Service::GetHandler(0); + static_cast<::grpc::internal::CallbackUnaryHandler< + ::opentelemetry::proto::collector::metrics::v1:: + ExportMetricsServiceRequest, + ::opentelemetry::proto::collector::metrics::v1:: + ExportMetricsServiceResponse>*>(handler) + ->SetMessageAllocator(allocator); + } + + public: + metric_service(const metric_handler& request_handler, + const std::shared_ptr& logger); + + static std::shared_ptr load( + const metric_handler& request_handler, + const std::shared_ptr& logger); + + // disable synchronous version of this method + ::grpc::Status Export( + ::grpc::ServerContext* /*context*/, + const ::opentelemetry::proto::collector::metrics::v1:: + ExportMetricsServiceRequest* /*request*/, + ::opentelemetry::proto::collector::metrics::v1:: + ExportMetricsServiceResponse* /*response*/) override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + virtual ::grpc::ServerUnaryReactor* Export( + ::grpc::CallbackServerContext* /*context*/, + const ::opentelemetry::proto::collector::metrics::v1:: + ExportMetricsServiceRequest* /*request*/, + ::opentelemetry::proto::collector::metrics::v1:: + ExportMetricsServiceResponse* /*response*/); +}; + +/** + * @brief Construct a new metric service::metric service object + * this constructor must not be called by other objects, use load instead + * + * @param request_handler + */ +metric_service::metric_service(const metric_handler& request_handler, + const std::shared_ptr& logger) + : _allocator(std::make_shared()), + _request_handler(request_handler), + _logger(logger) {} + +/** + * @brief initialize service (set allocator and push callback) + * + */ +void metric_service::init() { + ::grpc::Service::MarkMethodCallback( + 0, new ::grpc::internal::CallbackUnaryHandler< + ::opentelemetry::proto::collector::metrics::v1:: + ExportMetricsServiceRequest, + ::opentelemetry::proto::collector::metrics::v1:: + ExportMetricsServiceResponse>( + [me = shared_from_this()]( + ::grpc::CallbackServerContext* context, + const ::opentelemetry::proto::collector::metrics::v1:: + ExportMetricsServiceRequest* request, + ::opentelemetry::proto::collector::metrics::v1:: + ExportMetricsServiceResponse* response) { + return me->Export(context, request, response); + })); + SetMessageAllocatorFor_Export(_allocator.get()); +} + +/** + * @brief the method to use to create a metric_service + * + * @param request_handler + * @return std::shared_ptr + */ +std::shared_ptr metric_service::load( + const metric_handler& request_handler, + const std::shared_ptr& logger) { + std::shared_ptr ret = + std::make_shared(request_handler, logger); + ret->init(); + return ret; +} + +/** + * @brief called on request + * + * @param context + * @param request + * @param response + * @return ::grpc::ServerUnaryReactor* + */ +::grpc::ServerUnaryReactor* metric_service::Export( + ::grpc::CallbackServerContext* context, + const otl_col_metrics::ExportMetricsServiceRequest* request, + otl_col_metrics::ExportMetricsServiceResponse* response) { + metric_request_ptr shared_request = + _allocator->get_metric_request_ptr_from_raw(request); + + SPDLOG_LOGGER_TRACE(_logger, "receive:{}", *request); + if (shared_request) { + _request_handler(shared_request); + } else { + SPDLOG_LOGGER_ERROR(_logger, " unknown raw pointer {:p}", + static_cast(request)); + } + + ::grpc::ServerUnaryReactor* reactor = context->DefaultReactor(); + reactor->Finish(::grpc::Status::OK); + return reactor; +} + +} // namespace com::centreon::engine::modules::opentelemetry::detail + +/** + * @brief Construct a new otl server::otl server object + * + * @param conf grpc configuration + * @param handler handler that will be called on every request + */ +otl_server::otl_server(const grpc_config::pointer& conf, + const metric_handler& handler, + const std::shared_ptr& logger) + + : common::grpc::grpc_server_base(conf, logger), + _service(detail::metric_service::load(handler, logger)) {} + +/** + * @brief Destroy the otl server::otl server object + * + */ +otl_server::~otl_server() { + shutdown(std::chrono::seconds(30)); +} + +/** + * @brief create and start a otl_server + * + * @param conf + * @param handler + * @return otl_server::pointer otl_server started + */ +otl_server::pointer otl_server::load( + const grpc_config::pointer& conf, + const metric_handler& handler, + const std::shared_ptr& logger) { + otl_server::pointer ret(new otl_server(conf, handler, logger)); + ret->start(); + return ret; +} + +/** + * @brief create and start a grpc server + * + */ +void otl_server::start() { + _init([this](::grpc::ServerBuilder& builder) { + builder.RegisterService(_service.get()); + }); +} diff --git a/engine/precomp_inc/precomp.hh b/engine/precomp_inc/precomp.hh index 0b573db6565..28b9f7f30d0 100644 --- a/engine/precomp_inc/precomp.hh +++ b/engine/precomp_inc/precomp.hh @@ -63,6 +63,7 @@ #include #include +#include #include #include #include diff --git a/engine/src/anomalydetection.cc b/engine/src/anomalydetection.cc index 08dcaadcd50..3d73cf162d5 100644 --- a/engine/src/anomalydetection.cc +++ b/engine/src/anomalydetection.cc @@ -19,6 +19,7 @@ #include "com/centreon/engine/anomalydetection.hh" +#include "com/centreon/common/rapidjson_helper.hh" #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/checks/checker.hh" #include "com/centreon/engine/globals.hh" @@ -33,6 +34,8 @@ #include "com/centreon/exceptions/interruption.hh" using namespace com::centreon::engine; + +using com::centreon::common::rapidjson_helper; using namespace com::centreon::engine::logging; namespace com::centreon::engine { @@ -53,19 +56,20 @@ anomalydetection::threshold_point::threshold_point(time_t timepoint) anomalydetection::threshold_point::threshold_point( time_t timepoint, double factor, - const nlohmann::json& json_data) + const rapidjson::Value& json_data) : threshold_point(timepoint) { - if (json_data.contains("upper") && json_data.contains("lower")) { - _upper = json_data.at("upper").get(); - _lower = json_data.at("lower").get(); - if (json_data.contains("fit")) { - _fit = json_data.at("fit").get(); + rapidjson_helper json(json_data); + if (json.has_member("upper") && json.has_member("lower")) { + _upper = json.get_double("upper"); + _lower = json.get_double("lower"); + if (json_data.HasMember("fit")) { + _fit = json.get_double("fit"); } _format = e_format::V1; } else { - _fit = json_data.at("fit").get(); - _lower_margin = json_data.at("lower_margin").get(); - _upper_margin = json_data.at("upper_margin").get(); + _fit = json.get_double("fit"); + _lower_margin = json.get_double("lower_margin"); + _upper_margin = json.get_double("upper_margin"); _format = e_format::V2; set_factor(factor); } @@ -1112,39 +1116,17 @@ void anomalydetection::init_thresholds() { << "Trying to read thresholds file '" << _thresholds_file << "'"; SPDLOG_LOGGER_DEBUG(config_logger, "Trying to read thresholds file '{}'", _thresholds_file); - std::ifstream t; - t.exceptions(t.exceptions() | std::ios::failbit); + + rapidjson::Document json_doc; try { - t.open(_thresholds_file); - } catch (const std::system_error& e) { - if (!verify_config) { - SPDLOG_LOGGER_ERROR(config_logger, - "Fail to read thresholds file '{}' : {}", - _thresholds_file, e.code().message()); - } - return; + json_doc = rapidjson_helper::read_from_file(_thresholds_file); } catch (const std::exception& e) { - SPDLOG_LOGGER_ERROR(config_logger, "Fail to read thresholds file '{}' : {}", - _thresholds_file, e.what()); + SPDLOG_LOGGER_ERROR(config_logger, "Fail to load {}: {}", _thresholds_file, + e.what()); return; } - std::stringstream buffer; - buffer << t.rdbuf(); - std::string err; - nlohmann::json json; - try { - json = nlohmann::json::parse(buffer.str()); - } catch (const nlohmann::json::parse_error& e) { - engine_logger(log_config_error, basic) - << "Error: the file '" << _thresholds_file - << "' contains errors: " << e.what(); - SPDLOG_LOGGER_ERROR(config_logger, - "Error: the file '{}' contains errors: {}", - _thresholds_file, e.what()); - return; - } - if (!json.is_array()) { + if (!json_doc.IsArray()) { engine_logger(log_config_error, basic) << "Error: the file '" << _thresholds_file << "' is not a thresholds file. Its global structure is not an array."; @@ -1156,21 +1138,23 @@ void anomalydetection::init_thresholds() { return; } + rapidjson_helper json(json_doc); + bool found = false; - for (auto it = json.begin(); it != json.end(); ++it) { + for (const auto& value : json) { uint64_t host_id, service_id; - std::string metric_name; - nlohmann::json predict; - auto item = it.value(); + std::string_view metric_name; + const rapidjson::Value* predict = nullptr; + rapidjson_helper item(value); double sensitivity = 0.0; try { - host_id = stoull(item.at("host_id").get()); - service_id = stoull(item.at("service_id").get()); - metric_name = item.at("metric_name").get(); - predict = item.at("predict"); + host_id = item.get_double("host_id"); + service_id = item.get_double("service_id"); + metric_name = item.get_string("metric_name"); + predict = &item.get_member("predict"); try { - sensitivity = item.at("sensitivity").get(); - } catch (std::exception const&) { // json sensitivity is not mandatory + sensitivity = item.get_double("sensitivity"); + } catch (const std::exception&) { // sensitivity is not mandatory } } catch (std::exception const& e) { engine_logger(log_config_error, basic) @@ -1187,11 +1171,11 @@ void anomalydetection::init_thresholds() { } if (host_id == this->host_id() && service_id == this->service_id() && metric_name == _metric_name) { - set_thresholds_no_lock(_thresholds_file, sensitivity, predict); + set_thresholds_no_lock(_thresholds_file, sensitivity, *predict); if (!_thresholds_file_viable) { SPDLOG_LOGGER_ERROR(config_logger, "{} don't contain at least 2 thresholds datas for " - "host_id {} and service_id {}", + "host_id{} and service_id {} ", _thresholds_file, this->host_id(), this->service_id()); } @@ -1220,37 +1204,16 @@ int anomalydetection::update_thresholds(const std::string& filename) { << "Reading thresholds file '" << filename << "'."; SPDLOG_LOGGER_INFO(checks_logger, "Reading thresholds file '{}'.", filename); - std::ifstream t; - t.exceptions(t.exceptions() | std::ios::failbit); + rapidjson::Document json_doc; try { - t.open(filename); - } catch (const std::system_error& e) { - SPDLOG_LOGGER_ERROR(config_logger, "Fail to read thresholds file '{}' : {}", - filename, e.code().message()); - return -1; + json_doc = rapidjson_helper::read_from_file(filename); } catch (const std::exception& e) { - SPDLOG_LOGGER_ERROR(config_logger, "Fail to read thresholds file '{}' : {}", - filename, e.what()); + SPDLOG_LOGGER_ERROR(config_logger, "Fail to load {}: {}", filename, + e.what()); return -1; } - std::stringstream buffer; - buffer << t.rdbuf(); - nlohmann::json json; - try { - json = nlohmann::json::parse(buffer.str()); - } catch (const nlohmann::json::parse_error& e) { - engine_logger(log_config_error, basic) - << "Error: The thresholds file '" << filename - << "' should be a json file: " << e.what(); - SPDLOG_LOGGER_ERROR( - config_logger, - "Error: The thresholds file '{}' should be a json file: {}", filename, - e.what()); - return -2; - } - - if (!json.is_array()) { + if (!json_doc.IsArray()) { engine_logger(log_config_error, basic) << "Error: the file '" << filename << "' is not a thresholds file. Its global structure is not an array."; @@ -1262,19 +1225,20 @@ int anomalydetection::update_thresholds(const std::string& filename) { return -3; } - for (auto it = json.begin(); it != json.end(); ++it) { + rapidjson_helper json(json_doc); + for (const auto& value : json) { uint64_t host_id, svc_id; - auto item = it.value(); double sensitivity = 0.0; - std::string metric_name; - nlohmann::json predict; + std::string_view metric_name; + rapidjson_helper item(value); + const rapidjson::Value* predict = nullptr; try { - host_id = stoull(item.at("host_id").get()); - svc_id = stoull(item.at("service_id").get()); - metric_name = item.at("metric_name"); - predict = item.at("predict"); + host_id = item.get_double("host_id"); + svc_id = item.get_double("service_id"); + metric_name = item.get_string("metric_name"); + predict = &item.get_member("predict"); try { - sensitivity = item.at("sensitivity").get(); + sensitivity = item.get_double("sensitivity"); } catch (const std::exception&) { // sensitivity is not mandatory } } catch (std::exception const& e) { @@ -1314,13 +1278,6 @@ int anomalydetection::update_thresholds(const std::string& filename) { std::static_pointer_cast(found->second); if (ad->get_metric_name() != metric_name) { - engine_logger(log_config_error, basic) - << "Error: The thresholds file contains thresholds for the anomaly " - "detection service (host_id: " - << ad->host_id() << ", service_id: " << ad->service_id() - << ") with metric_name='" << metric_name - << "' whereas the configured metric name is '" - << ad->get_metric_name() << "'"; SPDLOG_LOGGER_ERROR( config_logger, "Error: The thresholds file contains thresholds for the anomaly " @@ -1329,24 +1286,20 @@ int anomalydetection::update_thresholds(const std::string& filename) { ad->host_id(), ad->service_id(), metric_name, ad->get_metric_name()); continue; } - engine_logger(log_info_message, basic) - << "Filling thresholds in anomaly detection (host_id: " << ad->host_id() - << ", service_id: " << ad->service_id() - << ", metric: " << ad->get_metric_name() << ")"; SPDLOG_LOGGER_INFO( checks_logger, "Filling thresholds in anomaly detection (host_id: {}, service_id: {}, " "metric: {})", ad->host_id(), ad->service_id(), ad->get_metric_name()); - ad->set_thresholds_lock(filename, sensitivity, predict); + ad->set_thresholds_lock(filename, sensitivity, *predict); } return 0; } void anomalydetection::set_thresholds_lock(const std::string& filename, double json_sensitivity, - const nlohmann::json& thresholds) { + const rapidjson::Value& thresholds) { std::lock_guard _lock(_thresholds_m); set_thresholds_no_lock(filename, json_sensitivity, thresholds); } @@ -1361,7 +1314,7 @@ void anomalydetection::set_thresholds_lock(const std::string& filename, void anomalydetection::set_thresholds_no_lock( const std::string& filename, double json_sensitivity, - const nlohmann::json& thresholds) { + const rapidjson::Value& thresholds_val) { if (_thresholds_file != filename) { _thresholds_file = filename; } @@ -1372,22 +1325,17 @@ void anomalydetection::set_thresholds_no_lock( if (_sensitivity > 0) { sensitivity = _sensitivity; } - for (const nlohmann::json& threshold_obj : thresholds) { + rapidjson_helper thresholds(thresholds_val); + for (const auto& threshold_obj : thresholds) { try { - time_t timepoint = - static_cast(threshold_obj.at("timestamp").get()); + time_t timepoint = static_cast( + rapidjson_helper(threshold_obj).get_uint64_t("timestamp")); _thresholds.emplace_hint( _thresholds.end(), timepoint, threshold_point(timepoint, sensitivity, threshold_obj)); - } catch (const nlohmann::json::exception& e) { - SPDLOG_LOGGER_ERROR(config_logger, "fail to parse predict:{} cause:{}", - threshold_obj.dump(), e.what()); } catch (const std::exception& e) { SPDLOG_LOGGER_ERROR(config_logger, "fail to parse predict:{} cause {}", - threshold_obj.dump(), e.what()); - } catch (...) { - SPDLOG_LOGGER_ERROR(config_logger, "unknown exception {}", - threshold_obj.dump()); + thresholds_val, e.what()); } } if (_thresholds.size() > 1) { diff --git a/engine/src/commands/CMakeLists.txt b/engine/src/commands/CMakeLists.txt index 2c384be658e..a0c47ab186e 100644 --- a/engine/src/commands/CMakeLists.txt +++ b/engine/src/commands/CMakeLists.txt @@ -32,6 +32,7 @@ set( "${SRC_DIR}/connector.cc" "${SRC_DIR}/environment.cc" "${SRC_DIR}/forward.cc" + "${SRC_DIR}/otel_interface.cc" "${SRC_DIR}/processing.cc" "${SRC_DIR}/raw.cc" "${SRC_DIR}/result.cc" diff --git a/engine/src/commands/otel_interface.cc b/engine/src/commands/otel_interface.cc new file mode 100644 index 00000000000..45d64db7270 --- /dev/null +++ b/engine/src/commands/otel_interface.cc @@ -0,0 +1,58 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#include "com/centreon/engine/commands/otel_interface.hh" + +using namespace com::centreon::engine::commands::otel; + +/** + * @brief singleton used to make the bridge between engine and otel module + * + */ +std::shared_ptr + com::centreon::engine::commands::otel::open_telemetry_base::_instance; + +void host_serv_list::register_host_serv( + const std::string& host, + const std::string& service_description) { + std::lock_guard l(_data_m); + _data[host].insert(service_description); +} + +void host_serv_list::unregister_host_serv( + const std::string& host, + const std::string& service_description) { + std::lock_guard l(_data_m); + auto host_search = _data.find(host); + if (host_search != _data.end()) { + host_search->second.erase(service_description); + if (host_search->second.empty()) { + _data.erase(host_search); + } + } +} + +bool host_serv_list::is_allowed(const std::string& host, + const std::string& service_description) const { + std::lock_guard l(_data_m); + auto host_search = _data.find(host); + if (host_search != _data.end()) { + return host_search->second.contains(service_description); + } + return false; +} diff --git a/engine/tests/CMakeLists.txt b/engine/tests/CMakeLists.txt index 45fd6113cda..45bbaf7455f 100755 --- a/engine/tests/CMakeLists.txt +++ b/engine/tests/CMakeLists.txt @@ -21,8 +21,12 @@ if(WITH_TESTING) # Tests directory. Add root inclusion direction. set(MODULE_DIR "${PROJECT_SOURCE_DIR}/modules/external_commands") set(INC_DIR "${MODULE_DIR}/inc/com/centreon/engine/modules/external_commands") - include_directories(${CMAKE_SOURCE_DIR} ${CMAKE_SOURCE_DIR}/common/inc - ${PROJECT_SOURCE_DIR} ${MODULE_DIR}/inc) + set(MODULE_DIR_OTL "${PROJECT_SOURCE_DIR}/modules/opentelemetry") + + include_directories(${PROJECT_SOURCE_DIR} ${MODULE_DIR}/inc + ${MODULE_DIR_OTL}/inc + ${CMAKE_SOURCE_DIR}/bbdo + ${CMAKE_SOURCE_DIR}/common/http/inc) # Set directory. set(TESTS_DIR "${PROJECT_SOURCE_DIR}/tests") @@ -107,6 +111,8 @@ if(WITH_TESTING) "${TESTS_DIR}/notifications/service_timeperiod_notification.cc" "${TESTS_DIR}/notifications/service_flapping_notification.cc" "${TESTS_DIR}/notifications/service_downtime_notification_test.cc" + "${TESTS_DIR}/opentelemetry/grpc_config_test.cc" + "${TESTS_DIR}/opentelemetry/otl_server_test.cc" "${TESTS_DIR}/perfdata/perfdata.cc" "${TESTS_DIR}/retention/host.cc" "${TESTS_DIR}/retention/service.cc" @@ -146,6 +152,10 @@ if(WITH_TESTING) add_library(ut_engine_utils STATIC "${TESTS_DIR}/timeperiod/utils.cc") add_executable(ut_engine ${ut_sources}) + target_include_directories(ut_engine PRIVATE + ${MODULE_DIR_OTL}/src + ${CMAKE_SOURCE_DIR}/common/grpc/inc) + target_precompile_headers(ut_engine REUSE_FROM cce_core) set_target_properties( @@ -176,8 +186,13 @@ if(WITH_TESTING) PRIVATE -L${PROTOBUF_LIB_DIR} ${ENGINERPC} ut_engine_utils + "-Wl,-whole-archive" cce_core log_v2 + opentelemetry + "-Wl,-no-whole-archive" + pb_open_telemetry_lib + centreon_grpc pthread ${GCOV} GTest::gtest diff --git a/engine/tests/checks/anomalydetection.cc b/engine/tests/checks/anomalydetection.cc index 0d55cd2e373..7d1a9e7981f 100644 --- a/engine/tests/checks/anomalydetection.cc +++ b/engine/tests/checks/anomalydetection.cc @@ -48,6 +48,7 @@ using namespace com::centreon::engine::configuration::applier; class AnomalydetectionCheck : public TestEngine { public: void SetUp() override { + ::unlink("/tmp/thresholds_status_change.json"); init_config_state(); checks_logger->set_level(spdlog::level::trace); diff --git a/engine/tests/opentelemetry/grpc_config_test.cc b/engine/tests/opentelemetry/grpc_config_test.cc new file mode 100644 index 00000000000..eb0cfcdb333 --- /dev/null +++ b/engine/tests/opentelemetry/grpc_config_test.cc @@ -0,0 +1,110 @@ +/** + * Copyright 2024 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ + +#include + +#include "com/centreon/common/rapidjson_helper.hh" + +#include "com/centreon/engine/modules/opentelemetry/grpc_config.hh" + +using namespace com::centreon::engine::modules::opentelemetry; +using namespace com::centreon::common::literals; + +TEST(otl_grpc_config, nor_host_nor_port_json) { + ASSERT_THROW(grpc_config t(R"( +{ "toto":5 +})"_json), + std::exception); +} + +TEST(otl_grpc_config, no_port_json) { + ASSERT_THROW(grpc_config t(R"( +{ "host":"127.0.0.1" +})"_json), + std::exception); +} + +TEST(otl_grpc_config, no_host_json) { + ASSERT_THROW(grpc_config t(R"( +{ "port":5678 +})"_json), + std::exception); +} + +TEST(otl_grpc_config, bad_port_json) { + ASSERT_THROW(grpc_config t(R"( +{ + "host":"127.0.0.1", + "port":1000 +})"_json), + std::exception); +} + +TEST(otl_grpc_config, bad_port_json2) { + ASSERT_THROW(grpc_config t(R"( +{ + "host":"127.0.0.1", + "port":"2500" +})"_json), + std::exception); +} + +TEST(otl_grpc_config, bad_port_json3) { + ASSERT_THROW(grpc_config t(R"( +{ + "host":"127.0.0.1", + "port":250000 +})"_json), + std::exception); +} + +TEST(otl_grpc_config, good_host_port) { + grpc_config c(R"( +{ + "host":"127.0.0.1", + "port":2500 +})"_json); + ASSERT_EQ(c.get_hostport(), "127.0.0.1:2500"); + ASSERT_FALSE(c.is_compressed()); + ASSERT_FALSE(c.is_crypted()); + ASSERT_TRUE(c.get_cert().empty()); + ASSERT_TRUE(c.get_key().empty()); + ASSERT_TRUE(c.get_ca().empty()); + ASSERT_TRUE(c.get_ca_name().empty()); + ASSERT_EQ(c.get_second_keepalive_interval(), 30); +} + +TEST(otl_grpc_config, good_host_port2) { + grpc_config c(R"( +{ + "host":"127.0.0.1", + "port":2500, + "encryption":true, + "compression": true, + "ca_name":"toto" +})"_json); + ASSERT_EQ(c.get_hostport(), "127.0.0.1:2500"); + ASSERT_TRUE(c.is_compressed()); + ASSERT_TRUE(c.is_crypted()); + ASSERT_TRUE(c.get_cert().empty()); + ASSERT_TRUE(c.get_key().empty()); + ASSERT_EQ(c.get_ca_name(), "toto"); + ASSERT_TRUE(c.get_ca().empty()); + ASSERT_EQ(c.get_second_keepalive_interval(), 30); +} diff --git a/engine/tests/opentelemetry/otl_server_test.cc b/engine/tests/opentelemetry/otl_server_test.cc new file mode 100644 index 00000000000..8c99d849c64 --- /dev/null +++ b/engine/tests/opentelemetry/otl_server_test.cc @@ -0,0 +1,116 @@ +/** + * Copyright 2024 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ + +#include + +#include +#include + +#include + +#include "opentelemetry/proto/collector/metrics/v1/metrics_service.grpc.pb.h" +#include "opentelemetry/proto/metrics/v1/metrics.pb.h" + +#include "com/centreon/engine/modules/opentelemetry/otl_server.hh" + +using namespace com::centreon::engine::modules::opentelemetry; +using namespace ::opentelemetry::proto::collector::metrics::v1; + +class otl_client { + std::shared_ptr<::grpc::Channel> _channel; + std::unique_ptr _stub; + ::grpc::ClientContext _client_context; + + public: + otl_client(const std::string&, + const std::shared_ptr<::grpc::ChannelCredentials>& credentials = + ::grpc::InsecureChannelCredentials()); + ~otl_client(); + + ::grpc::Status expor(const ExportMetricsServiceRequest& request, + ExportMetricsServiceResponse* response); +}; + +otl_client::otl_client( + const std::string& hostport, + const std::shared_ptr<::grpc::ChannelCredentials>& credentials) { + _channel = ::grpc::CreateChannel(hostport, credentials); + _stub = MetricsService::NewStub(_channel); +} + +otl_client::~otl_client() { + _stub.reset(); + + _channel.reset(); +} + +::grpc::Status otl_client::expor(const ExportMetricsServiceRequest& request, + ExportMetricsServiceResponse* response) { + return _stub->Export(&_client_context, request, response); +} + +class otl_server_test : public ::testing::Test { + std::shared_ptr _server; + + public: + void SetUp() override {} + + void TearDown() override { + if (_server) { + _server->shutdown(std::chrono::seconds(15)); + _server.reset(); + } + } + + template + void start_server(const grpc_config::pointer& conf, + const metric_handler_type& handler) { + _server = otl_server::load(conf, handler, spdlog::default_logger()); + } +}; + +TEST_F(otl_server_test, unsecure_client_server) { + grpc_config::pointer serv_conf = + std::make_shared("127.0.0.1:6789", false); + std::shared_ptr received; + auto handler = + [&](const std::shared_ptr& request) { + received = request; + }; + start_server(serv_conf, handler); + + otl_client client("127.0.0.1:6789"); + + ExportMetricsServiceRequest request; + ExportMetricsServiceResponse response; + + auto metrics = request.add_resource_metrics(); + metrics->set_schema_url("hello opentelemetry"); + auto metric = metrics->add_scope_metrics()->add_metrics(); + metric->set_name("metric cpu"); + metric->set_description("metric to send"); + metric->set_unit("%"); + auto gauge = metric->mutable_gauge(); + auto point = gauge->add_data_points(); + point->set_time_unix_nano(time(nullptr)); + + ::grpc::Status status = client.expor(request, &response); + + ASSERT_TRUE(status.ok()); +} diff --git a/packaging/centreon-broker-stats-exporter-debuginfo.yaml b/packaging/centreon-broker-stats-exporter-debuginfo.yaml deleted file mode 100644 index 0062e784d34..00000000000 --- a/packaging/centreon-broker-stats-exporter-debuginfo.yaml +++ /dev/null @@ -1,41 +0,0 @@ -name: "centreon-broker-stats-exporter-debuginfo" -arch: "${ARCH}" -platform: "linux" -version_schema: "none" -version: "${VERSION}" -release: "${RELEASE}${DIST}" -section: "default" -priority: "optional" -maintainer: "Centreon " -description: | - Debuginfo package for centreon-broker-stats-exporter. - Commit: @COMMIT_HASH@ -vendor: "Centreon" -homepage: "https://www.centreon.com" -license: "Apache-2.0" - -contents: - - src: "../build/broker/stats_exporter/15-stats_exporter.so.debug" - dst: "/usr/lib/debug/usr/share/centreon/lib/centreon-broker/" - -overrides: - rpm: - depends: - - centreon-broker-stats-exporter = ${VERSION}-${RELEASE}${DIST} - deb: - depends: - - centreon-broker-stats-exporter (= ${VERSION}-${RELEASE}${DIST}) - - libcurl4 - conflicts: - - centreon-broker-stats-exporter-dbgsym - replaces: - - centreon-broker-stats-exporter-dbgsym - provides: - - centreon-broker-stats-exporter-dbgsym - -rpm: - summary: Debuginfo package for centreon-broker-stats-exporter. - compression: zstd - signature: - key_file: ${RPM_SIGNING_KEY_FILE} - key_id: ${RPM_SIGNING_KEY_ID} diff --git a/packaging/centreon-broker-stats-exporter.yaml b/packaging/centreon-broker-stats-exporter.yaml deleted file mode 100644 index c40f9f8a11d..00000000000 --- a/packaging/centreon-broker-stats-exporter.yaml +++ /dev/null @@ -1,36 +0,0 @@ -name: "centreon-broker-stats-exporter" -arch: "${ARCH}" -platform: "linux" -version_schema: "none" -version: "${VERSION}" -release: "${RELEASE}${DIST}" -section: "default" -priority: "optional" -maintainer: "Centreon " -description: | - This module of Centreon Broker allows you to send broker statistics to - an Opentelemetry Exporter. It can be configured to use gRPC or http - protocols. - Commit: @COMMIT_HASH@ -vendor: "Centreon" -homepage: "https://www.centreon.com" -license: "Apache-2.0" - -contents: - - src: "../build/broker/stats_exporter/15-stats_exporter.so" - dst: "/usr/share/centreon/lib/centreon-broker/" - -overrides: - rpm: - depends: - - centreon-broker-core = ${VERSION}-${RELEASE}${DIST} - deb: - depends: - - centreon-broker-core (= ${VERSION}-${RELEASE}${DIST}) - -rpm: - summary: Export Centreon Statistics to an OpenTelemetry Exporter. - compression: zstd - signature: - key_file: ${RPM_SIGNING_KEY_FILE} - key_id: ${RPM_SIGNING_KEY_ID} diff --git a/tests/broker-engine/external-commands2.robot b/tests/broker-engine/external-commands2.robot index a0349827d7b..65c6b7dc848 100644 --- a/tests/broker-engine/external-commands2.robot +++ b/tests/broker-engine/external-commands2.robot @@ -951,7 +951,9 @@ BEEXTCMD_REVERSE_GRPC1 ${start} Ctn Get Round Current Date Ctn Start Broker Ctn Start engine - Ctn Wait For Engine To Be Ready ${1} + Ctn Wait For Engine To Be Ready ${1} + #lets time to grpc to start + Sleep 0.1 Ctn Change Normal Svc Check Interval ${use_grpc} host_1 service_1 10 diff --git a/vcpkg.json b/vcpkg.json index 5a23bcb978f..dc44f161886 100644 --- a/vcpkg.json +++ b/vcpkg.json @@ -21,15 +21,9 @@ "boost-interprocess", "boost-exception", "boost-serialization", - { - "name": "opentelemetry-cpp", - "features": [ - "otlp-grpc", - "otlp-http" - ] - }, + "boost-url", "nlohmann-json", "rapidjson", "gtest" ] -} \ No newline at end of file +} From e9b847151844a2f3dc5bac29f27131ee7396c83f Mon Sep 17 00:00:00 2001 From: David Boucher Date: Mon, 3 Jun 2024 11:07:06 +0200 Subject: [PATCH 18/60] enh(engine/whitelist): whitelist for everything (#1382) REFS: MON-75741 --- common/log_v2/log_v2.cc | 7 +- engine/inc/com/centreon/engine/checkable.hh | 159 +++-- .../engine/configuration/whitelist.hh | 2 +- engine/inc/com/centreon/engine/utils.hh | 2 +- engine/src/checkable.cc | 45 +- engine/src/checks/checker.cc | 4 +- engine/src/host.cc | 33 +- engine/src/notification.cc | 2 +- engine/src/sehandlers.cc | 172 +++-- engine/src/service.cc | 70 +- engine/src/utils.cc | 2 +- engine/src/xpddefault.cc | 16 +- tests/README.md | 619 ++++++++++-------- tests/broker-engine/notifications.robot | 350 ++++++---- tests/broker-engine/whitelist.robot | 59 +- tests/resources/Broker.py | 21 + tests/resources/Common.py | 21 + tests/resources/Engine.py | 21 + tests/resources/engine-scripts/check.pl | 24 +- tests/robot.sh | 2 + tests/update-doc.py | 47 +- 21 files changed, 1076 insertions(+), 602 deletions(-) diff --git a/common/log_v2/log_v2.cc b/common/log_v2/log_v2.cc index 8c80518270c..94e857bc736 100644 --- a/common/log_v2/log_v2.cc +++ b/common/log_v2/log_v2.cc @@ -1,5 +1,5 @@ /** - * Copyright 2022-2023 Centreon + * Copyright 2022-2024 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -147,11 +147,10 @@ log_v2::log_v2(std::string name) : _log_name{std::move(name)} { } /** - * @brief Destroy the log v2::log v2 object - * + * @brief Destructor. */ log_v2::~log_v2() noexcept { - // grpc_logger mustn't be called after log_v2 destruction + /* When log_v2 is stopped, grpc mustn't log anymore. */ gpr_set_log_function(nullptr); } diff --git a/engine/inc/com/centreon/engine/checkable.hh b/engine/inc/com/centreon/engine/checkable.hh index 60205ca6487..0932e5d2b80 100644 --- a/engine/inc/com/centreon/engine/checkable.hh +++ b/engine/inc/com/centreon/engine/checkable.hh @@ -42,6 +42,95 @@ class checkable { enum state_type { soft, hard }; + private: + /** + * @brief we store in this struct the last result of whitelist + * check in order to not check command line each time + * + */ + struct command_allowed { + std::string process_cmd; + bool allowed; + }; + + struct whitelist_last_result { + unsigned whitelist_instance_id; + /* We need a command for each type of command */ + std::array command; + }; + + std::string _name; + std::string _display_name; + std::string _check_command; + uint32_t _check_interval; + uint32_t _retry_interval; + int _max_attempts; + std::string _check_period; + std::string _event_handler; + bool _event_handler_enabled; + std::string _action_url; + std::string _icon_image; + std::string _icon_image_alt; + std::string _notes; + std::string _notes_url; + std::string _plugin_output; + std::string _long_plugin_output; + std::string _perf_data; + bool _flap_detection_enabled; + double _low_flap_threshold; + double _high_flap_threshold; + bool _obsess_over; + std::string _timezone; + bool _checks_enabled; + bool _accept_passive_checks; + bool _check_freshness; + int _freshness_threshold; + check_type _check_type; + int _current_attempt; + bool _has_been_checked; + int _scheduled_downtime_depth; + double _execution_time; + bool _is_flapping; + int _last_check; + double _latency; + std::time_t _next_check; + bool _should_be_scheduled; + uint32_t _state_history_index; + std::time_t _last_state_change; + std::time_t _last_hard_state_change; + enum state_type _state_type; + double _percent_state_change; + commands::command* _event_handler_ptr; + std::shared_ptr _check_command_ptr; + bool _is_executing; + std::shared_ptr _severity; + uint64_t _icon_id; + std::forward_list> _tags; + + // whitelist cache + whitelist_last_result _whitelist_last_result; + + public: + /** + * This structure is used by the static command_is_allowed_by_whitelist() + * method. You have to maintain your own following structure and use it with + * the static method. */ + struct static_whitelist_last_result { + unsigned whitelist_instance_id; + /* We need a command for each type of command */ + command_allowed command; + }; + + /* This enum is used to store the whitelist cache. A checkable can execute + * all the following types of command, so for each one, we store if the + * whitelist allows it or not. */ + enum command_type { + CHECK_TYPE = 0, + NOTIF_TYPE = 1, + EVH_TYPE = 2, + OBSESS_TYPE = 3, + }; + checkable(const std::string& name, std::string const& display_name, std::string const& check_command, @@ -172,73 +261,13 @@ class checkable { std::forward_list>& mut_tags(); const std::forward_list>& tags() const; - bool is_whitelist_allowed(const std::string& process_cmd); + bool command_is_allowed_by_whitelist(const std::string& process_cmd, + command_type typ); + static bool command_is_allowed_by_whitelist( + const std::string& process_cmd, + static_whitelist_last_result& cached_cmd); timeperiod* check_period_ptr; - - private: - /** - * @brief we store in this struct the last result of whitelist - * check in order to not check command line each time - * - */ - struct whitelist_last_result { - whitelist_last_result() : whitelist_instance_id(0), allowed(false) {} - unsigned whitelist_instance_id; - std::string process_cmd; - bool allowed; - }; - - std::string _name; - std::string _display_name; - std::string _check_command; - uint32_t _check_interval; - uint32_t _retry_interval; - int _max_attempts; - std::string _check_period; - std::string _event_handler; - bool _event_handler_enabled; - std::string _action_url; - std::string _icon_image; - std::string _icon_image_alt; - std::string _notes; - std::string _notes_url; - std::string _plugin_output; - std::string _long_plugin_output; - std::string _perf_data; - bool _flap_detection_enabled; - double _low_flap_threshold; - double _high_flap_threshold; - bool _obsess_over; - std::string _timezone; - bool _checks_enabled; - bool _accept_passive_checks; - bool _check_freshness; - int _freshness_threshold; - check_type _check_type; - int _current_attempt; - bool _has_been_checked; - int _scheduled_downtime_depth; - double _execution_time; - bool _is_flapping; - int _last_check; - double _latency; - std::time_t _next_check; - bool _should_be_scheduled; - uint32_t _state_history_index; - std::time_t _last_state_change; - std::time_t _last_hard_state_change; - enum state_type _state_type; - double _percent_state_change; - commands::command* _event_handler_ptr; - std::shared_ptr _check_command_ptr; - bool _is_executing; - std::shared_ptr _severity; - uint64_t _icon_id; - std::forward_list> _tags; - - // whitelist cache - whitelist_last_result _whitelist_last_result; }; } // namespace com::centreon::engine diff --git a/engine/inc/com/centreon/engine/configuration/whitelist.hh b/engine/inc/com/centreon/engine/configuration/whitelist.hh index 37f3fbed5c7..134d46fbe57 100644 --- a/engine/inc/com/centreon/engine/configuration/whitelist.hh +++ b/engine/inc/com/centreon/engine/configuration/whitelist.hh @@ -1,5 +1,5 @@ /** - * Copyright 2023 Centreon (https://www.centreon.com/) + * Copyright 2023-2024 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/engine/inc/com/centreon/engine/utils.hh b/engine/inc/com/centreon/engine/utils.hh index 4ef43e8fe0e..7560738d8b0 100644 --- a/engine/inc/com/centreon/engine/utils.hh +++ b/engine/inc/com/centreon/engine/utils.hh @@ -35,7 +35,7 @@ extern "C" { int my_system_r(nagios_macros* mac, std::string const& cmd, int timeout, - int* early_timeout, + bool* early_timeout, double* exectime, std::string& output, unsigned int max_output_length); diff --git a/engine/src/checkable.cc b/engine/src/checkable.cc index d6ebaf973b7..332cb6368f9 100644 --- a/engine/src/checkable.cc +++ b/engine/src/checkable.cc @@ -541,21 +541,52 @@ void checkable::set_name(const std::string& name) { * it tries to use last whitelist check result * * @param process_cmd final command line (macros replaced) + * @param cached_cmd the static cached command (in case of a cache stored + * in another place than in this). The cached command is writable to be updated + * if needed. This method should be used with care, usually the other method + * with the same name should be preferred. + * @return A boolean true if allowed, false otherwise. + */ +bool checkable::command_is_allowed_by_whitelist( + const std::string& process_cmd, + static_whitelist_last_result& cached_cmd) { + if (process_cmd == cached_cmd.command.process_cmd && + configuration::whitelist::instance().instance_id() == + cached_cmd.whitelist_instance_id) { + return cached_cmd.command.allowed; + } + + // something has changed => call whitelist + cached_cmd.command.process_cmd = process_cmd; + cached_cmd.command.allowed = + configuration::whitelist::instance().is_allowed(process_cmd); + cached_cmd.whitelist_instance_id = + configuration::whitelist::instance().instance_id(); + return cached_cmd.command.allowed; +} + +/** + * @brief check if a command is allowed by whitelist + * it tries to use last whitelist check result + * + * @param process_cmd final command line (macros replaced) + * @param typ a value among CHECK_TYPE, NOTIF_TYPE, EVH_TYPE or OBSESS_TYPE. * @return true allowed * @return false */ -bool checkable::is_whitelist_allowed(const std::string& process_cmd) { - if (process_cmd == _whitelist_last_result.process_cmd && +bool checkable::command_is_allowed_by_whitelist(const std::string& process_cmd, + command_type typ) { + auto& cmd = _whitelist_last_result.command[typ]; + if (process_cmd == cmd.process_cmd && configuration::whitelist::instance().instance_id() == _whitelist_last_result.whitelist_instance_id) { - return _whitelist_last_result.allowed; + return cmd.allowed; } // something has changed => call whitelist - _whitelist_last_result.process_cmd = process_cmd; - _whitelist_last_result.allowed = - configuration::whitelist::instance().is_allowed(process_cmd); + cmd.process_cmd = process_cmd; + cmd.allowed = configuration::whitelist::instance().is_allowed(process_cmd); _whitelist_last_result.whitelist_instance_id = configuration::whitelist::instance().instance_id(); - return _whitelist_last_result.allowed; + return cmd.allowed; } diff --git a/engine/src/checks/checker.cc b/engine/src/checks/checker.cc index 381df663ed1..56c412ef5cf 100644 --- a/engine/src/checks/checker.cc +++ b/engine/src/checks/checker.cc @@ -21,6 +21,7 @@ #include "com/centreon/engine/checks/checker.hh" #include "com/centreon/engine/broker.hh" +#include "com/centreon/engine/checkable.hh" #include "com/centreon/engine/configuration/whitelist.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" @@ -535,7 +536,8 @@ com::centreon::engine::host::host_state checker::_execute_sync(host* hst) { res.start_time = res.end_time; }; - if (!hst->is_whitelist_allowed(processed_cmd)) { + if (!hst->command_is_allowed_by_whitelist(processed_cmd, + checkable::CHECK_TYPE)) { SPDLOG_LOGGER_ERROR(commands_logger, "host {}: this command cannot be executed because of " "security restrictions on the poller. A whitelist has " diff --git a/engine/src/host.cc b/engine/src/host.cc index 6a055cbb067..5f7a67444aa 100644 --- a/engine/src/host.cc +++ b/engine/src/host.cc @@ -23,6 +23,7 @@ #include #include "com/centreon/engine/broker.hh" +#include "com/centreon/engine/checkable.hh" #include "com/centreon/engine/checks/checker.hh" #include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/configuration/whitelist.hh" @@ -1817,7 +1818,7 @@ int host::run_async_check(int check_options, }; // allowed by whitelist? - if (!is_whitelist_allowed(processed_cmd)) { + if (!command_is_allowed_by_whitelist(processed_cmd, CHECK_TYPE)) { SPDLOG_LOGGER_ERROR(commands_logger, "host {}: this command cannot be executed because of " "security restrictions on the poller. A whitelist has " @@ -2530,7 +2531,7 @@ int host::notify_contact(nagios_macros* mac, int escalated) { std::string raw_command; std::string processed_command; - int early_timeout = false; + bool early_timeout = false; double exectime; struct timeval start_time, end_time; struct timeval method_start_time, method_end_time; @@ -2636,16 +2637,24 @@ int host::notify_contact(nagios_macros* mac, } /* run the notification command */ - try { - std::string out; - my_system_r(mac, processed_command, config->notification_timeout(), - &early_timeout, &exectime, out, 0); - } catch (std::exception const& e) { - engine_logger(log_runtime_error, basic) - << "Error: can't execute host notification '" << cntct->get_name() - << "' : " << e.what(); - runtime_logger->error("Error: can't execute host notification '{}' : {}", - cntct->get_name(), e.what()); + if (command_is_allowed_by_whitelist(processed_command, NOTIF_TYPE)) { + try { + std::string out; + my_system_r(mac, processed_command, config->notification_timeout(), + &early_timeout, &exectime, out, 0); + } catch (std::exception const& e) { + engine_logger(log_runtime_error, basic) + << "Error: can't execute host notification for contact '" + << cntct->get_name() << "' : " << e.what(); + runtime_logger->error( + "Error: can't execute host notification for contact '{}' : {}", + cntct->get_name(), e.what()); + } + } else { + runtime_logger->error( + "Error: can't execute host notification for contact '{}' : it is not " + "allowed by the whitelist", + cntct->get_name()); } /* check to see if the notification timed out */ diff --git a/engine/src/notification.cc b/engine/src/notification.cc index 2e32df5fe25..5e2b750ef87 100644 --- a/engine/src/notification.cc +++ b/engine/src/notification.cc @@ -206,7 +206,7 @@ int notification::execute(std::unordered_set const& to_notify) { engine_logger(dbg_notifications, basic) << contacts_notified << " contacts were notified."; - notifications_logger->trace(" contacts were notified."); + notifications_logger->trace("{} contacts were notified.", contacts_notified); return OK; } diff --git a/engine/src/sehandlers.cc b/engine/src/sehandlers.cc index 4ae3cb69a10..18872b09f17 100644 --- a/engine/src/sehandlers.cc +++ b/engine/src/sehandlers.cc @@ -21,6 +21,7 @@ #include "com/centreon/engine/sehandlers.hh" #include "com/centreon/engine/broker.hh" +#include "com/centreon/engine/checkable.hh" #include "com/centreon/engine/comment.hh" #include "com/centreon/engine/downtimes/downtime.hh" #include "com/centreon/engine/downtimes/downtime_manager.hh" @@ -44,7 +45,7 @@ int obsessive_compulsive_host_check_processor( com::centreon::engine::host* hst) { std::string raw_command; std::string processed_command; - int early_timeout = false; + bool early_timeout = false; double exectime = 0.0; int macro_options = STRIP_ILLEGAL_MACRO_CHARS | ESCAPE_MACRO_CHARS; nagios_macros* mac(get_global_macros()); @@ -99,23 +100,32 @@ int obsessive_compulsive_host_check_processor( "command line: {}", processed_command); - /* run the command */ - try { - std::string tmp; - my_system_r(mac, processed_command, config->ochp_timeout(), &early_timeout, - &exectime, tmp, 0); - } catch (std::exception const& e) { - engine_logger(log_runtime_error, basic) - << "Error: can't execute compulsive host processor command line '" - << processed_command << "' : " << e.what(); + if (hst->command_is_allowed_by_whitelist(processed_command, + checkable::OBSESS_TYPE)) { + /* run the command */ + try { + std::string tmp; + my_system_r(mac, processed_command, config->ochp_timeout(), + &early_timeout, &exectime, tmp, 0); + } catch (std::exception const& e) { + engine_logger(log_runtime_error, basic) + << "Error: can't execute compulsive host processor command line '" + << processed_command << "' : " << e.what(); + runtime_logger->error( + "Error: can't execute compulsive host processor command line '{}' : " + "{}", + processed_command, e.what()); + } + } else { runtime_logger->error( - "Error: can't execute compulsive host processor command line '{}' : {}", - processed_command, e.what()); + "Error: can't execute compulsive host processor command line '{}' : it " + "is not allowed by the whitelist", + processed_command); } clear_volatile_macros_r(mac); /* check to see if the command timed out */ - if (early_timeout == true) + if (early_timeout) engine_logger(log_runtime_warning, basic) << "Warning: OCHP command '" << processed_command << "' for host '" << hst->name() << "' timed out after " << config->ochp_timeout() @@ -138,7 +148,7 @@ int run_global_service_event_handler(nagios_macros* mac, std::string processed_command; std::string processed_logentry; std::string command_output; - int early_timeout = false; + bool early_timeout = false; double exectime = 0.0; struct timeval start_time; int macro_options = STRIP_ILLEGAL_MACRO_CHARS | ESCAPE_MACRO_CHARS; @@ -204,23 +214,33 @@ int run_global_service_event_handler(nagios_macros* mac, events_logger->debug(processed_logentry); } - /* run the command */ - try { - my_system_r(mac, processed_command, config->event_handler_timeout(), - &early_timeout, &exectime, command_output, 0); - } catch (std::exception const& e) { - engine_logger(log_runtime_error, basic) - << "Error: can't execute global service event handler " - "command line '" - << processed_command << "' : " << e.what(); + static checkable::static_whitelist_last_result cached_cmd; + + if (checkable::command_is_allowed_by_whitelist(processed_command, + cached_cmd)) { + /* run the command */ + try { + my_system_r(mac, processed_command, config->event_handler_timeout(), + &early_timeout, &exectime, command_output, 0); + } catch (std::exception const& e) { + engine_logger(log_runtime_error, basic) + << "Error: can't execute global service event handler " + "command line '" + << processed_command << "' : " << e.what(); + runtime_logger->error( + "Error: can't execute global service event handler " + "command line '{}' : {}", + processed_command, e.what()); + } + } else { runtime_logger->error( "Error: can't execute global service event handler " - "command line '{}' : {}", - processed_command, e.what()); + "command line '{}' : it is not allowed by the whitelist", + processed_command); } /* check to see if the event handler timed out */ - if (early_timeout == true) { + if (early_timeout) { engine_logger(log_event_handler | log_runtime_warning, basic) << "Warning: Global service event handler command '" << processed_command << "' timed out after " @@ -240,7 +260,7 @@ int run_service_event_handler(nagios_macros* mac, std::string processed_command; std::string processed_logentry; std::string command_output; - int early_timeout = false; + bool early_timeout = false; double exectime = 0.0; struct timeval start_time; int macro_options = STRIP_ILLEGAL_MACRO_CHARS | ESCAPE_MACRO_CHARS; @@ -286,7 +306,7 @@ int run_service_event_handler(nagios_macros* mac, events_logger->debug("Processed service event handler command line: {}", processed_command); - if (config->log_event_handlers() == true) { + if (config->log_event_handlers()) { std::ostringstream oss; oss << "SERVICE EVENT HANDLER: " << svc->get_hostname() << ';' << svc->description() @@ -297,21 +317,29 @@ int run_service_event_handler(nagios_macros* mac, events_logger->info(processed_logentry); } - /* run the command */ - try { - my_system_r(mac, processed_command, config->event_handler_timeout(), - &early_timeout, &exectime, command_output, 0); - } catch (std::exception const& e) { - engine_logger(log_runtime_error, basic) - << "Error: can't execute service event handler command line '" - << processed_command << "' : " << e.what(); + if (svc->command_is_allowed_by_whitelist(processed_command, + checkable::EVH_TYPE)) { + /* run the command */ + try { + my_system_r(mac, processed_command, config->event_handler_timeout(), + &early_timeout, &exectime, command_output, 0); + } catch (std::exception const& e) { + engine_logger(log_runtime_error, basic) + << "Error: can't execute service event handler command line '" + << processed_command << "' : " << e.what(); + runtime_logger->error( + "Error: can't execute service event handler command line '{}' : {}", + processed_command, e.what()); + } + } else { runtime_logger->error( - "Error: can't execute service event handler command line '{}' : {}", - processed_command, e.what()); + "Error: can't execute service event handler command line '{}' : it is " + "not allowed by the whitelist", + processed_command); } /* check to see if the event handler timed out */ - if (early_timeout == true) { + if (early_timeout) { engine_logger(log_event_handler | log_runtime_warning, basic) << "Warning: Service event handler command '" << processed_command << "' timed out after " << config->event_handler_timeout() @@ -374,7 +402,7 @@ int run_global_host_event_handler(nagios_macros* mac, std::string processed_command; std::string processed_logentry; std::string command_output; - int early_timeout = false; + bool early_timeout = false; double exectime = 0.0; struct timeval start_time; int macro_options = STRIP_ILLEGAL_MACRO_CHARS | ESCAPE_MACRO_CHARS; @@ -435,21 +463,31 @@ int run_global_host_event_handler(nagios_macros* mac, events_logger->info(processed_logentry); } - /* run the command */ - try { - my_system_r(mac, processed_command, config->event_handler_timeout(), - &early_timeout, &exectime, command_output, 0); - } catch (std::exception const& e) { - engine_logger(log_runtime_error, basic) - << "Error: can't execute global host event handler command line '" - << processed_command << "' : " << e.what(); + static checkable::static_whitelist_last_result cached_cmd; + + if (host::command_is_allowed_by_whitelist(processed_command, cached_cmd)) { + /* run the command */ + try { + my_system_r(mac, processed_command, config->event_handler_timeout(), + &early_timeout, &exectime, command_output, 0); + } catch (std::exception const& e) { + engine_logger(log_runtime_error, basic) + << "Error: can't execute global host event handler command line '" + << processed_command << "' : " << e.what(); + runtime_logger->error( + "Error: can't execute global host event handler command line '{}' : " + "{}", + processed_command, e.what()); + } + } else { runtime_logger->error( - "Error: can't execute global host event handler command line '{}' : {}", - processed_command, e.what()); + "Error: can't execute global host event handler command line '{}' : it " + "is not allowed by the whitelist", + processed_command); } /* check for a timeout in the execution of the event handler command */ - if (early_timeout == true) { + if (early_timeout) { engine_logger(log_event_handler | log_runtime_warning, basic) << "Warning: Global host event handler command '" << processed_command << "' timed out after " << config->event_handler_timeout() @@ -470,7 +508,7 @@ int run_host_event_handler(nagios_macros* mac, std::string processed_command; std::string processed_logentry; std::string command_output; - int early_timeout = false; + bool early_timeout = false; double exectime = 0.0; struct timeval start_time; int macro_options = STRIP_ILLEGAL_MACRO_CHARS | ESCAPE_MACRO_CHARS; @@ -523,21 +561,29 @@ int run_host_event_handler(nagios_macros* mac, events_logger->info(processed_logentry); } - /* run the command */ - try { - my_system_r(mac, processed_command, config->event_handler_timeout(), - &early_timeout, &exectime, command_output, 0); - } catch (std::exception const& e) { - engine_logger(log_runtime_error, basic) - << "Error: can't execute host event handler command line '" - << processed_command << "' : " << e.what(); + if (hst->command_is_allowed_by_whitelist(processed_command, + checkable::EVH_TYPE)) { + /* run the command */ + try { + my_system_r(mac, processed_command, config->event_handler_timeout(), + &early_timeout, &exectime, command_output, 0); + } catch (std::exception const& e) { + engine_logger(log_runtime_error, basic) + << "Error: can't execute host event handler command line '" + << processed_command << "' : " << e.what(); + runtime_logger->error( + "Error: can't execute host event handler command line '{}' : {}", + processed_command, e.what()); + } + } else { runtime_logger->error( - "Error: can't execute host event handler command line '{}' : {}", - processed_command, e.what()); + "Error: can't execute host event handler command line '{}' : it is not " + "allowed by the whitelist", + processed_command); } /* check to see if the event handler timed out */ - if (early_timeout == true) { + if (early_timeout) { engine_logger(log_event_handler | log_runtime_warning, basic) << "Warning: Host event handler command '" << processed_command << "' timed out after " << config->event_handler_timeout() diff --git a/engine/src/service.cc b/engine/src/service.cc index 58845c20d65..4280f603652 100644 --- a/engine/src/service.cc +++ b/engine/src/service.cc @@ -22,6 +22,7 @@ #include #include "com/centreon/engine/broker.hh" +#include "com/centreon/engine/checkable.hh" #include "com/centreon/engine/checks/checker.hh" #include "com/centreon/engine/configuration/whitelist.hh" #include "com/centreon/engine/deleter/listmember.hh" @@ -2268,7 +2269,7 @@ int service::obsessive_compulsive_service_check_processor() { std::string raw_command; std::string processed_command; host* temp_host{get_host_ptr()}; - int early_timeout = false; + bool early_timeout = false; double exectime = 0.0; int macro_options = STRIP_ILLEGAL_MACRO_CHARS | ESCAPE_MACRO_CHARS; nagios_macros* mac(get_global_macros()); @@ -2328,26 +2329,33 @@ int service::obsessive_compulsive_service_check_processor() { "processor command line: {}", processed_command); - /* run the command */ - try { - std::string tmp; - my_system_r(mac, processed_command, config->ocsp_timeout(), &early_timeout, - &exectime, tmp, 0); - } catch (std::exception const& e) { - engine_logger(log_runtime_error, basic) - << "Error: can't execute compulsive service processor command line '" - << processed_command << "' : " << e.what(); - SPDLOG_LOGGER_ERROR( - runtime_logger, + if (command_is_allowed_by_whitelist(processed_command, OBSESS_TYPE)) { + /* run the command */ + try { + std::string tmp; + my_system_r(mac, processed_command, config->ocsp_timeout(), + &early_timeout, &exectime, tmp, 0); + } catch (std::exception const& e) { + engine_logger(log_runtime_error, basic) + << "Error: can't execute compulsive service processor command line '" + << processed_command << "' : " << e.what(); + SPDLOG_LOGGER_ERROR(runtime_logger, + "Error: can't execute compulsive service processor " + "command line '{}' : " + "{}", + processed_command, e.what()); + } + } else { + runtime_logger->error( "Error: can't execute compulsive service processor command line '{}' : " - "{}", - processed_command, e.what()); + "it is not allowed by the whitelist", + processed_command); } clear_volatile_macros_r(mac); /* check to see if the command timed out */ - if (early_timeout == true) + if (early_timeout) engine_logger(log_runtime_warning, basic) << "Warning: OCSP command '" << processed_command << "' for service '" << name() << "' on host '" << _hostname << "' timed out after " @@ -2669,7 +2677,7 @@ int service::run_async_check_local(int check_options, }; // allowed by whitelist? - if (!is_whitelist_allowed(processed_cmd)) { + if (!command_is_allowed_by_whitelist(processed_cmd, CHECK_TYPE)) { SPDLOG_LOGGER_ERROR( commands_logger, "service {}: this command cannot be executed because of " @@ -3153,7 +3161,7 @@ int service::notify_contact(nagios_macros* mac, int escalated) { std::string raw_command; std::string processed_command; - int early_timeout = false; + bool early_timeout = false; double exectime; struct timeval start_time, end_time; struct timeval method_start_time, method_end_time; @@ -3259,17 +3267,25 @@ int service::notify_contact(nagios_macros* mac, } /* run the notification command */ - try { - std::string tmp; - my_system_r(mac, processed_command, config->notification_timeout(), - &early_timeout, &exectime, tmp, 0); - } catch (std::exception const& e) { - engine_logger(log_runtime_error, basic) - << "Error: can't execute service notification '" << cntct->get_name() - << "' : " << e.what(); + if (command_is_allowed_by_whitelist(processed_command, NOTIF_TYPE)) { + try { + std::string tmp; + my_system_r(mac, processed_command, config->notification_timeout(), + &early_timeout, &exectime, tmp, 0); + } catch (std::exception const& e) { + engine_logger(log_runtime_error, basic) + << "Error: can't execute service notification for contact '" + << cntct->get_name() << "' : " << e.what(); + SPDLOG_LOGGER_ERROR( + runtime_logger, + "Error: can't execute service notification for contact '{}': {}", + cntct->get_name(), e.what()); + } + } else { SPDLOG_LOGGER_ERROR(runtime_logger, - "Error: can't execute service notification '{}' : {}", - cntct->get_name(), e.what()); + "Error: can't execute service notification for " + "contact '{}' : it is not allowed by the whitelist", + cntct->get_name()); } /* check to see if the notification command timed out */ diff --git a/engine/src/utils.cc b/engine/src/utils.cc index 888248b91eb..e6a25db2d7a 100644 --- a/engine/src/utils.cc +++ b/engine/src/utils.cc @@ -57,7 +57,7 @@ using namespace com::centreon::engine::logging; int my_system_r(nagios_macros* mac, std::string const& cmd, int timeout, - int* early_timeout, + bool* early_timeout, double* exectime, std::string& output, unsigned int max_output_length) { diff --git a/engine/src/xpddefault.cc b/engine/src/xpddefault.cc index 00cf6912ac6..3aeaa79adc7 100644 --- a/engine/src/xpddefault.cc +++ b/engine/src/xpddefault.cc @@ -291,7 +291,7 @@ int xpddefault_run_service_performance_data_command( com::centreon::engine::service* svc) { std::string raw_command_line; std::string processed_command_line; - int early_timeout(false); + bool early_timeout = false; double exectime; int result(OK); int macro_options(STRIP_ILLEGAL_MACRO_CHARS | ESCAPE_MACRO_CHARS); @@ -346,7 +346,7 @@ int xpddefault_run_service_performance_data_command( } // check to see if the command timed out. - if (early_timeout == true) + if (early_timeout) engine_logger(log_runtime_warning, basic) << "Warning: Service performance data command '" << processed_command_line << "' for service '" << svc->description() @@ -366,7 +366,7 @@ int xpddefault_run_host_performance_data_command(nagios_macros* mac, host* hst) { std::string raw_command_line; std::string processed_command_line; - int early_timeout(false); + bool early_timeout = false; double exectime; int result(OK); int macro_options(STRIP_ILLEGAL_MACRO_CHARS | ESCAPE_MACRO_CHARS); @@ -421,7 +421,7 @@ int xpddefault_run_host_performance_data_command(nagios_macros* mac, return ERROR; // check to see if the command timed out. - if (early_timeout == true) + if (early_timeout) engine_logger(log_runtime_warning, basic) << "Warning: Host performance data command '" << processed_command_line << "' for host '" << hst->name() << "' timed out after " @@ -659,7 +659,7 @@ int xpddefault_update_host_performance_data_file(nagios_macros* mac, int xpddefault_process_host_perfdata_file() { std::string raw_command_line; std::string processed_command_line; - int early_timeout(false); + bool early_timeout = false; double exectime(0.0); int result(OK); int macro_options(STRIP_ILLEGAL_MACRO_CHARS | ESCAPE_MACRO_CHARS); @@ -731,7 +731,7 @@ int xpddefault_process_host_perfdata_file() { pthread_mutex_unlock(&xpddefault_host_perfdata_fp_lock); // check to see if the command timed out. - if (early_timeout == true) + if (early_timeout) engine_logger(log_runtime_warning, basic) << "Warning: Host performance data file processing command '" << processed_command_line << "' timed out after " @@ -747,7 +747,7 @@ int xpddefault_process_host_perfdata_file() { int xpddefault_process_service_perfdata_file() { std::string raw_command_line; std::string processed_command_line; - int early_timeout(false); + bool early_timeout = false; double exectime(0.0); int result(OK); int macro_options(STRIP_ILLEGAL_MACRO_CHARS | ESCAPE_MACRO_CHARS); @@ -821,7 +821,7 @@ int xpddefault_process_service_perfdata_file() { clear_volatile_macros_r(mac); // check to see if the command timed out. - if (early_timeout == true) + if (early_timeout) engine_logger(log_runtime_warning, basic) << "Warning: Service performance data file processing command '" << processed_command_line << "' timed out after " diff --git a/tests/README.md b/tests/README.md index 148fe569fcc..3a7620c20a4 100644 --- a/tests/README.md +++ b/tests/README.md @@ -40,7 +40,7 @@ git clone https://github.com/open-telemetry/opentelemetry-proto.git opentelemetr On other rpm based distributions, you can try the following commands to initialize your robot tests: ``` -pip3 install -U robotframework robotframework-databaselibrary robotframework-httpctrl pymysql +pip3 install -U robotframework robotframework-databaselibrary robotframework-httpctrl robotframework-examples pymysql yum install python3-devel -y @@ -75,32 +75,38 @@ Here is the list of the currently implemented tests: 2. [x] **BABOO**: With bbdo version 3.0.1, a BA of type 'worst' with 2 child services and another BA of type impact with a boolean rule returning if one of its two services are critical are created. These two BA are built from the same services and should have a similar behavior 3. [x] **BABOOAND**: With bbdo version 3.0.1, a BA of type impact with a boolean rule returning if both of its two services are ok is created. When one condition is false, the and operator returns false as a result even if the other child is unknown. 4. [x] **BABOOCOMPL**: With bbdo version 3.0.1, a BA of type impact with a complex boolean rule is configured. We check its correct behaviour following service updates. -5. [x] **BABOOOR**: With bbdo version 3.0.1, a BA of type 'worst' with 2 child services and another BA of type impact with a boolean rule returning if one of its two services are critical are created. These two BA are built from the same services and should have a similar behavior -6. [x] **BABOOORREL**: With bbdo version 3.0.1, a BA of type impact with a boolean rule returning if one of its two services is ok is created. One of the two underlying services must change of state to change the ba state. For this purpose, we change the service state and reload cbd. So the rule is something like "False OR True" which is equal to True. And to pass from True to False, we change the second service. -7. [x] **BAWORST**: With bbdo version 3.0.1, a BA of type 'worst' with two services is configured. -8. [x] **BA_BOOL_KPI**: With bbdo version 3.0.1, a BA of type 'worst' with 1 boolean kpi -9. [x] **BA_IMPACT_2KPI_SERVICES**: With bbdo version 3.0.1, a BA of type 'impact' with 2 serv, ba is critical only if the 2 services are critical -10. [x] **BA_RATIO_NUMBER_BA_4_SERVICE**: With bbdo version 3.0.1, a BA of type 'ratio number' with 4 serv -11. [x] **BA_RATIO_NUMBER_BA_SERVICE**: With bbdo version 3.0.1, a BA of type 'ratio number' with 2 services and one ba with 1 service -12. [x] **BA_RATIO_PERCENT_BA_4_SERVICE**: With bbdo version 3.0.1, a BA of type 'ratio number' with 4 serv -13. [x] **BA_RATIO_PERCENT_BA_SERVICE**: With bbdo version 3.0.1, a BA of type 'ratio percent' with 2 serv an 1 ba with one service -14. [x] **BEBAMIDT1**: A BA of type 'worst' with one service is configured. The BA is in critical state, because of its service. Then we set a downtime on this last one. An inherited downtime is set to the BA. The downtime is removed from the service, the inherited downtime is then deleted. -15. [x] **BEBAMIDT2**: A BA of type 'worst' with one service is configured. The BA is in critical state, because of its service. Then we set a downtime on this last one. An inherited downtime is set to the BA. Engine is restarted. Broker is restarted. The two downtimes are still there with no duplicates. The downtime is removed from the service, the inherited downtime is then deleted. -16. [x] **BEBAMIDTU1**: With bbdo version 3.0.1, a BA of type 'worst' with one service is configured. The BA is in critical state, because of its service. Then we set a downtime on this last one. An inherited downtime is set to the BA. The downtime is removed from the service, the inherited downtime is then deleted. -17. [x] **BEBAMIDTU2**: With bbdo version 3.0.1, a BA of type 'worst' with one service is configured. The BA is in critical state, because of its service. Then we set a downtime on this last one. An inherited downtime is set to the BA. Engine is restarted. Broker is restarted. The two downtimes are still there with no duplicates. The downtime is removed from the service, the inherited downtime is then deleted. -18. [x] **BEBAMIGNDT1**: A BA of type 'worst' with two services is configured. The downtime policy on this ba is "Ignore the indicator in the calculation". The BA is in critical state, because of the second critical service. Then we apply two downtimes on this last one. The BA state is ok because of the policy on indicators. A first downtime is cancelled, the BA is still OK, but when the second downtime is cancelled, the BA should be CRITICAL. -19. [x] **BEBAMIGNDT2**: A BA of type 'worst' with two services is configured. The downtime policy on this ba is "Ignore the indicator in the calculation". The BA is in critical state, because of the second critical service. Then we apply two downtimes on this last one. The BA state is ok because of the policy on indicators. The first downtime reaches its end, the BA is still OK, but when the second downtime reaches its end, the BA should be CRITICAL. -20. [x] **BEBAMIGNDTU1**: With bbdo version 3.0.1, a BA of type 'worst' with two services is configured. The downtime policy on this ba is "Ignore the indicator in the calculation". The BA is in critical state, because of the second critical service. Then we apply two downtimes on this last one. The BA state is ok because of the policy on indicators. A first downtime is cancelled, the BA is still OK, but when the second downtime is cancelled, the BA should be CRITICAL. -21. [x] **BEBAMIGNDTU2**: With bbdo version 3.0.1, a BA of type 'worst' with two services is configured. The downtime policy on this ba is "Ignore the indicator in the calculation". The BA is in critical state, because of the second critical service. Then we apply two downtimes on this last one. The BA state is ok because of the policy on indicators. The first downtime reaches its end, the BA is still OK, but when the second downtime reaches its end, the BA should be CRITICAL. -22. [x] **BEPB_BA_DURATION_EVENT**: use of pb_ba_duration_event message. -23. [x] **BEPB_DIMENSION_BA_BV_RELATION_EVENT**: bbdo_version 3 use pb_dimension_ba_bv_relation_event message. -24. [x] **BEPB_DIMENSION_BA_EVENT**: bbdo_version 3 use pb_dimension_ba_event message. -25. [x] **BEPB_DIMENSION_BA_TIMEPERIOD_RELATION**: use of pb_dimension_ba_timeperiod_relation message. -26. [x] **BEPB_DIMENSION_BV_EVENT**: bbdo_version 3 use pb_dimension_bv_event message. -27. [x] **BEPB_DIMENSION_KPI_EVENT**: bbdo_version 3 use pb_dimension_kpi_event message. -28. [x] **BEPB_DIMENSION_TIMEPERIOD**: use of pb_dimension_timeperiod message. -29. [x] **BEPB_DIMENSION_TRUNCATE_TABLE**: use of pb_dimension_timeperiod message. -30. [x] **BEPB_KPI_STATUS**: bbdo_version 3 use kpi_status message. +5. [x] **BABOOCOMPL_RELOAD**: With bbdo version 3.0.1, a BA of type impact with a complex boolean rule is configured. We check its correct behaviour following service updates. +6. [x] **BABOOCOMPL_RESTART**: With bbdo version 3.0.1, a BA of type impact with a complex boolean rule is configured. We check its correct behaviour following service updates. +7. [x] **BABOOOR**: With bbdo version 3.0.1, a BA of type 'worst' with 2 child services and another BA of type impact with a boolean rule returning if one of its two services are critical are created. These two BA are built from the same services and should have a similar behavior +8. [x] **BABOOORREL**: With bbdo version 3.0.1, a BA of type impact with a boolean rule returning if one of its two services is ok is created. One of the two underlying services must change of state to change the ba state. For this purpose, we change the service state and reload cbd. So the rule is something like "False OR True" which is equal to True. And to pass from True to False, we change the second service. +9. [x] **BAWORST**: With bbdo version 3.0.1, a BA of type 'worst' with two services is configured. We also check stats output +10. [x] **BAWORST2**: a worst ba with a boolean kpi and a ba kpi +11. [x] **BA_BOOL_KPI**: With bbdo version 3.0.1, a BA of type 'worst' with 1 boolean kpi +12. [x] **BA_CHANGED**: A BA of type worst is configured with one service kpi. Then it is modified so that the service kpi is replaced by a boolean rule kpi. When cbd is reloaded, the BA is well updated. +13. [x] **BA_DISABLED**: create a disabled BA with timeperiods and reporting filter don't create error message +14. [x] **BA_IMPACT_2KPI_SERVICES**: With bbdo version 3.0.1, a BA of type 'impact' with 2 serv, ba is critical only if the 2 services are critical +15. [x] **BA_IMPACT_IMPACT**: A BA of type impact is defined with two BAs of type impact as children. The first child has an impact of 90 and the second one of 10. When they are impacting both, the parent should be critical. When they are not impacting, the parent should be ok. +16. [x] **BA_RATIO_NUMBER_BA_4_SERVICE**: With bbdo version 3.0.1, a BA of type 'ratio number' with 4 serv +17. [x] **BA_RATIO_NUMBER_BA_SERVICE**: With bbdo version 3.0.1, a BA of type 'ratio number' with 2 services and one ba with 1 service +18. [x] **BA_RATIO_PERCENT_BA_4_SERVICE**: With bbdo version 3.0.1, a BA of type 'ratio number' with 4 serv +19. [x] **BA_RATIO_PERCENT_BA_SERVICE**: With bbdo version 3.0.1, a BA of type 'ratio percent' with 2 serv an 1 ba with one service +20. [x] **BEBAMIDT1**: A BA of type 'worst' with one service is configured. The BA is in critical state, because of its service. Then we set a downtime on this last one. An inherited downtime is set to the BA. The downtime is removed from the service, the inherited downtime is then deleted. +21. [x] **BEBAMIDT2**: A BA of type 'worst' with one service is configured. The BA is in critical state, because of its service. Then we set a downtime on this last one. An inherited downtime is set to the BA. Engine is restarted. Broker is restarted. The two downtimes are still there with no duplicates. The downtime is removed from the service, the inherited downtime is then deleted. +22. [x] **BEBAMIDTU1**: With bbdo version 3.0.1, a BA of type 'worst' with one service is configured. The BA is in critical state, because of its service. Then we set a downtime on this last one. An inherited downtime is set to the BA. The downtime is removed from the service, the inherited downtime is then deleted. +23. [x] **BEBAMIDTU2**: With bbdo version 3.0.1, a BA of type 'worst' with one service is configured. The BA is in critical state, because of its service. Then we set a downtime on this last one. An inherited downtime is set to the BA. Engine is restarted. Broker is restarted. The two downtimes are still there with no duplicates. The downtime is removed from the service, the inherited downtime is then deleted. +24. [x] **BEBAMIGNDT1**: A BA of type 'worst' with two services is configured. The downtime policy on this ba is "Ignore the indicator in the calculation". The BA is in critical state, because of the second critical service. Then we apply two downtimes on this last one. The BA state is ok because of the policy on indicators. A first downtime is cancelled, the BA is still OK, but when the second downtime is cancelled, the BA should be CRITICAL. +25. [x] **BEBAMIGNDT2**: A BA of type 'worst' with two services is configured. The downtime policy on this ba is "Ignore the indicator in the calculation". The BA is in critical state, because of the second critical service. Then we apply two downtimes on this last one. The BA state is ok because of the policy on indicators. The first downtime reaches its end, the BA is still OK, but when the second downtime reaches its end, the BA should be CRITICAL. +26. [x] **BEBAMIGNDTU1**: With bbdo version 3.0.1, a BA of type 'worst' with two services is configured. The downtime policy on this ba is "Ignore the indicator in the calculation". The BA is in critical state, because of the second critical service. Then we apply two downtimes on this last one. The BA state is ok because of the policy on indicators. A first downtime is cancelled, the BA is still OK, but when the second downtime is cancelled, the BA should be CRITICAL. +27. [x] **BEBAMIGNDTU2**: With bbdo version 3.0.1, a BA of type 'worst' with two services is configured. The downtime policy on this ba is "Ignore the indicator in the calculation". The BA is in critical state, because of the second critical service. Then we apply two downtimes on this last one. The BA state is ok because of the policy on indicators. The first downtime reaches its end, the BA is still OK, but when the second downtime reaches its end, the BA should be CRITICAL. +28. [x] **BEPB_BA_DURATION_EVENT**: use of pb_ba_duration_event message. +29. [x] **BEPB_DIMENSION_BA_BV_RELATION_EVENT**: bbdo_version 3 use pb_dimension_ba_bv_relation_event message. +30. [x] **BEPB_DIMENSION_BA_EVENT**: bbdo_version 3 use pb_dimension_ba_event message. +31. [x] **BEPB_DIMENSION_BA_TIMEPERIOD_RELATION**: use of pb_dimension_ba_timeperiod_relation message. +32. [x] **BEPB_DIMENSION_BV_EVENT**: bbdo_version 3 use pb_dimension_bv_event message. +33. [x] **BEPB_DIMENSION_KPI_EVENT**: bbdo_version 3 use pb_dimension_kpi_event message. +34. [x] **BEPB_DIMENSION_TIMEPERIOD**: use of pb_dimension_timeperiod message. +35. [x] **BEPB_DIMENSION_TRUNCATE_TABLE**: use of pb_dimension_timeperiod message. +36. [x] **BEPB_KPI_STATUS**: bbdo_version 3 use kpi_status message. ### Broker 1. [x] **BCL1**: Starting broker with option '-s foobar' should return an error @@ -164,10 +170,10 @@ Here is the list of the currently implemented tests: 59. [x] **BSCSSK1**: Start-Stop two instances of broker, server configured with grpc and client with tcp. No connectrion established and error raised on client side. 60. [x] **BSCSSK2**: Start-Stop two instances of broker, server configured with tcp and client with grpc. No connection established and error raised on client side. 61. [x] **BSCSSP1**: Start-Stop two instances of broker and no coredump. The server contains a listen address -62. [x] **BSCSSPRR1**: Start-Stop two instances of broker and no coredump. The server contains a listen address, reversed and retention. central-broker-master-output is then a failover. +62. [x] **BSCSSPRR1**: Start-Stop two instances of broker and no coredump. The server contains a listen address, reversed and retention. centreon-broker-master-rrd is then a failover. 63. [x] **BSCSSR1**: Start-Stop two instances of broker and no coredump. Connection with bbdo_server/bbdo_client and reversed. -64. [x] **BSCSSRR1**: Start-Stop two instances of broker and no coredump. Connection with bbdo_server/bbdo_client, reversed and retention. central-broker-master-output is then a failover. -65. [x] **BSCSSRR2**: Start/Stop 10 times broker with 300ms interval and no coredump, reversed and retention. central-broker-master-output is then a failover. +64. [x] **BSCSSRR1**: Start-Stop two instances of broker and no coredump. Connection with bbdo_server/bbdo_client, reversed and retention. centreon-broker-master-rrd is then a failover. +65. [x] **BSCSSRR2**: Start/Stop 10 times broker with 300ms interval and no coredump, reversed and retention. centreon-broker-master-rrd is then a failover. 66. [x] **BSCSST1**: Start-Stop two instances of broker and no coredump. Encryption is enabled on client side. 67. [x] **BSCSST2**: Start-Stop two instances of broker and no coredump. Encryption is enabled on client side. 68. [x] **BSCSSTG1**: Start-Stop two instances of broker. The connection is made by bbdo_client/bbdo_server with encryption enabled. This is not sufficient, then an error is raised. @@ -194,11 +200,12 @@ Here is the list of the currently implemented tests: 3. [x] **NetworkDBFail7**: network failure test between broker and database: we wait for the connection to be established and then we shut down the connection for 60s 4. [x] **NetworkDBFailU6**: network failure test between broker and database: we wait for the connection to be established and then we shut down the connection for 60s (with unified_sql) 5. [x] **NetworkDBFailU7**: network failure test between broker and database: we wait for the connection to be established and then we shut down the connection for 60s (with unified_sql) -6. [x] **NetworkDbFail1**: network failure test between broker and database (shutting down connection for 100ms) -7. [x] **NetworkDbFail2**: network failure test between broker and database (shutting down connection for 1s) -8. [x] **NetworkDbFail3**: network failure test between broker and database (shutting down connection for 10s) -9. [x] **NetworkDbFail4**: network failure test between broker and database (shutting down connection for 30s) -10. [x] **NetworkDbFail5**: network failure test between broker and database (shutting down connection for 60s) +6. [x] **NetworkDBFailU8**: network failure test between broker and database: we wait for the connection to be established and then we shutdown the connection until _check_queues failure +7. [x] **NetworkDbFail1**: network failure test between broker and database (shutting down connection for 100ms) +8. [x] **NetworkDbFail2**: network failure test between broker and database (shutting down connection for 1s) +9. [x] **NetworkDbFail3**: network failure test between broker and database (shutting down connection for 10s) +10. [x] **NetworkDbFail4**: network failure test between broker and database (shutting down connection for 30s) +11. [x] **NetworkDbFail5**: network failure test between broker and database (shutting down connection for 60s) ### Broker/engine 1. [x] **ANO_CFG_SENSITIVITY_SAVED**: cfg sensitivity saved in retention @@ -209,248 +216,288 @@ Here is the list of the currently implemented tests: 6. [x] **ANO_EXTCMD_SENSITIVITY_SAVED**: extcmd sensitivity saved in retention 7. [x] **ANO_JSON_SENSITIVITY_NOT_SAVED**: json sensitivity not saved in retention 8. [x] **ANO_NOFILE**: an anomaly detection without threshold file must be in unknown state -9. [x] **ANO_OUT_LOWER_THAN_LIMIT**: an anomaly detection with a perfdata lower than lower limit make a critical state -10. [x] **ANO_OUT_UPPER_THAN_LIMIT**: an anomaly detection with a perfdata upper than upper limit make a critical state -11. [x] **ANO_TOO_OLD_FILE**: an anomaly detection with an oldest threshold file must be in unknown state -12. [x] **AOUTLU1**: an anomaly detection with a perfdata upper than upper limit make a critical state with bbdo 3 -13. [x] **BAM_STREAM_FILTER**: With bbdo version 3.0.1, a BA of type 'worst' with one service is configured. The BA is in critical state, because of its service. we watch its events -14. [x] **BEACK1**: Engine has a critical service. An external command is sent to acknowledge it. The centreon_storage.acknowledgements table is then updated with this acknowledgement. The service is newly set to OK. And the acknowledgement in database is deleted from engine but still open on the database. -15. [x] **BEACK2**: Configuration is made with BBDO3. Engine has a critical service. An external command is sent to acknowledge it. The centreon_storage.acknowledgements table is then updated with this acknowledgement. The service is newly set to OK. And the acknowledgement in database is deleted. -16. [x] **BEACK3**: Engine has a critical service. An external command is sent to acknowledge it. The centreon_storage.acknowledgements table is then updated with this acknowledgement. The acknowledgement is removed and the comment in the comments table has its deletion_time column updated. -17. [x] **BEACK4**: Configuration is made with BBDO3. Engine has a critical service. An external command is sent to acknowledge it. The centreon_storage.acknowledgements table is then updated with this acknowledgement. The acknowledgement is removed and the comment in the comments table has its deletion_time column updated. -18. [x] **BEACK5**: Engine has a critical service. An external command is sent to acknowledge it ; the acknowledgement is sticky. The centreon_storage.acknowledgements table is then updated with this acknowledgement. The service is newly set to WARNING. And the acknowledgement in database is still there. -19. [x] **BEACK6**: Configuration is made with BBDO3. Engine has a critical service. An external command is sent to acknowledge it ; the acknowledgement is sticky. The centreon_storage.acknowledgements table is then updated with this acknowledgement. The service is newly set to WARNING. And the acknowledgement in database is still there. -20. [x] **BEATOI11**: external command SEND_CUSTOM_HOST_NOTIFICATION with option_number=1 should work -21. [x] **BEATOI12**: external command SEND_CUSTOM_HOST_NOTIFICATION with option_number>7 should fail -22. [x] **BEATOI13**: external command SCHEDULE SERVICE DOWNTIME with duration<0 should fail -23. [x] **BEATOI21**: external command ADD_HOST_COMMENT and DEL_HOST_COMMENT should work -24. [x] **BEATOI22**: external command DEL_HOST_COMMENT with comment_id<0 should fail -25. [x] **BEATOI23**: external command ADD_SVC_COMMENT with persistent=0 should work -26. [x] **BECC1**: Broker/Engine communication with compression between central and poller -27. [x] **BECT1**: Broker/Engine communication with anonymous TLS between central and poller -28. [x] **BECT2**: Broker/Engine communication with TLS between central and poller with key/cert -29. [x] **BECT3**: Broker/Engine communication with anonymous TLS and ca certificate -30. [x] **BECT4**: Broker/Engine communication with TLS between central and poller with key/cert and hostname forced -31. [x] **BECT_GRPC1**: Broker/Engine communication with GRPC and with anonymous TLS between central and poller -32. [x] **BECT_GRPC2**: Broker/Engine communication with TLS between central and poller with key/cert -33. [x] **BECT_GRPC3**: Broker/Engine communication with anonymous TLS and ca certificate -34. [x] **BECT_GRPC4**: Broker/Engine communication with TLS between central and poller with key/cert and hostname forced -35. [x] **BECUSTOMHOSTVAR**: external command CHANGE_CUSTOM_HOST_VAR on SNMPVERSION -36. [x] **BECUSTOMSVCVAR**: external command CHANGE_CUSTOM_SVC_VAR on CRITICAL -37. [x] **BEDTHOSTFIXED**: A downtime is set on a host, the total number of downtimes is really 21 (1 for the host and 20 for its 20 services) then we delete this downtime and the number is 0. -38. [x] **BEDTMASS1**: New services with several pollers are created. Then downtimes are set on all configured hosts. This action results on 1050 downtimes if we also count impacted services. Then all these downtimes are removed. This test is done with BBDO 3.0.0 -39. [x] **BEDTMASS2**: New services with several pollers are created. Then downtimes are set on all configured hosts. This action results on 1050 downtimes if we also count impacted services. Then all these downtimes are removed. This test is done with BBDO 2.0 -40. [x] **BEDTSVCFIXED**: A downtime is set on a service, the total number of downtimes is really 1 then we delete this downtime and the number of downtime is 0. -41. [x] **BEDTSVCREN1**: A downtime is set on a service then the service is renamed. The downtime is still active on the renamed service. The downtime is removed from the renamed service and it is well removed. -42. [x] **BEEXTCMD1**: external command CHANGE_NORMAL_SVC_CHECK_INTERVAL on bbdo3.0 -43. [x] **BEEXTCMD10**: external command CHANGE_MAX_SVC_CHECK_ATTEMPTS on bbdo2.0 -44. [x] **BEEXTCMD11**: external command CHANGE_MAX_HOST_CHECK_ATTEMPTS on bbdo3.0 -45. [x] **BEEXTCMD12**: external command CHANGE_MAX_HOST_CHECK_ATTEMPTS on bbdo2.0 -46. [x] **BEEXTCMD13**: external command CHANGE_HOST_CHECK_TIMEPERIOD on bbdo3.0 -47. [x] **BEEXTCMD14**: external command CHANGE_HOST_CHECK_TIMEPERIOD on bbdo2.0 -48. [x] **BEEXTCMD15**: external command CHANGE_HOST_NOTIFICATION_TIMEPERIOD on bbdo3.0 -49. [x] **BEEXTCMD16**: external command CHANGE_HOST_NOTIFICATION_TIMEPERIOD on bbdo2.0 -50. [x] **BEEXTCMD17**: external command CHANGE_SVC_CHECK_TIMEPERIOD on bbdo3.0 -51. [x] **BEEXTCMD18**: external command CHANGE_SVC_CHECK_TIMEPERIOD on bbdo2.0 -52. [x] **BEEXTCMD19**: external command CHANGE_SVC_NOTIFICATION_TIMEPERIOD on bbdo3.0 -53. [x] **BEEXTCMD2**: external command CHANGE_NORMAL_SVC_CHECK_INTERVAL on bbdo2.0 -54. [x] **BEEXTCMD20**: external command CHANGE_SVC_NOTIFICATION_TIMEPERIOD on bbdo2.0 -55. [x] **BEEXTCMD21**: external command DISABLE_HOST_AND_CHILD_NOTIFICATIONS and ENABLE_HOST_AND_CHILD_NOTIFICATIONS on bbdo3.0 -56. [x] **BEEXTCMD22**: external command DISABLE_HOST_AND_CHILD_NOTIFICATIONS and ENABLE_HOST_AND_CHILD_NOTIFICATIONS on bbdo2.0 -57. [x] **BEEXTCMD23**: external command DISABLE_HOST_CHECK and ENABLE_HOST_CHECK on bbdo3.0 -58. [x] **BEEXTCMD24**: external command DISABLE_HOST_CHECK and ENABLE_HOST_CHECK on bbdo2.0 -59. [x] **BEEXTCMD25**: external command DISABLE_HOST_EVENT_HANDLER and ENABLE_HOST_EVENT_HANDLER on bbdo3.0 -60. [x] **BEEXTCMD26**: external command DISABLE_HOST_EVENT_HANDLER and ENABLE_HOST_EVENT_HANDLER on bbdo2.0 -61. [x] **BEEXTCMD27**: external command DISABLE_HOST_FLAP_DETECTION and ENABLE_HOST_FLAP_DETECTION on bbdo3.0 -62. [x] **BEEXTCMD28**: external command DISABLE_HOST_FLAP_DETECTION and ENABLE_HOST_FLAP_DETECTION on bbdo2.0 -63. [x] **BEEXTCMD29**: external command DISABLE_HOST_NOTIFICATIONS and ENABLE_HOST_NOTIFICATIONS on bbdo3.0 -64. [x] **BEEXTCMD3**: external command CHANGE_NORMAL_HOST_CHECK_INTERVAL on bbdo3.0 -65. [x] **BEEXTCMD30**: external command DISABLE_HOST_NOTIFICATIONS and ENABLE_HOST_NOTIFICATIONS on bbdo2.0 -66. [x] **BEEXTCMD31**: external command DISABLE_HOST_SVC_CHECKS and ENABLE_HOST_SVC_CHECKS on bbdo3.0 -67. [x] **BEEXTCMD32**: external command DISABLE_HOST_SVC_CHECKS and ENABLE_HOST_SVC_CHECKS on bbdo2.0 -68. [x] **BEEXTCMD33**: external command DISABLE_HOST_SVC_NOTIFICATIONS and ENABLE_HOST_SVC_NOTIFICATIONS on bbdo3.0 -69. [x] **BEEXTCMD34**: external command DISABLE_HOST_SVC_NOTIFICATIONS and ENABLE_HOST_SVC_NOTIFICATIONS on bbdo2.0 -70. [x] **BEEXTCMD35**: external command DISABLE_PASSIVE_HOST_CHECKS and ENABLE_PASSIVE_HOST_CHECKS on bbdo3.0 -71. [x] **BEEXTCMD36**: external command DISABLE_PASSIVE_HOST_CHECKS and ENABLE_PASSIVE_HOST_CHECKS on bbdo2.0 -72. [x] **BEEXTCMD37**: external command DISABLE_PASSIVE_SVC_CHECKS and ENABLE_PASSIVE_SVC_CHECKS on bbdo3.0 -73. [x] **BEEXTCMD38**: external command DISABLE_PASSIVE_SVC_CHECKS and ENABLE_PASSIVE_SVC_CHECKS on bbdo2.0 -74. [x] **BEEXTCMD39**: external command START_OBSESSING_OVER_HOST and STOP_OBSESSING_OVER_HOST on bbdo3.0 -75. [x] **BEEXTCMD4**: external command CHANGE_NORMAL_HOST_CHECK_INTERVAL on bbdo2.0 -76. [x] **BEEXTCMD40**: external command START_OBSESSING_OVER_HOST and STOP_OBSESSING_OVER_HOST on bbdo2.0 -77. [x] **BEEXTCMD41**: external command START_OBSESSING_OVER_SVC and STOP_OBSESSING_OVER_SVC on bbdo3.0 -78. [x] **BEEXTCMD42**: external command START_OBSESSING_OVER_SVC and STOP_OBSESSING_OVER_SVC on bbdo2.0 -79. [x] **BEEXTCMD5**: external command CHANGE_RETRY_SVC_CHECK_INTERVAL on bbdo3.0 -80. [x] **BEEXTCMD6**: external command CHANGE_RETRY_SVC_CHECK_INTERVAL on bbdo2.0 -81. [x] **BEEXTCMD7**: external command CHANGE_RETRY_HOST_CHECK_INTERVAL on bbdo3.0 -82. [x] **BEEXTCMD8**: external command CHANGE_RETRY_HOST_CHECK_INTERVAL on bbdo2.0 -83. [x] **BEEXTCMD9**: external command CHANGE_MAX_SVC_CHECK_ATTEMPTS on bbdo3.0 -84. [x] **BEEXTCMD_COMPRESS_GRPC1**: external command CHANGE_NORMAL_SVC_CHECK_INTERVAL on bbdo3.0 and compressed grpc -85. [x] **BEEXTCMD_GRPC1**: external command CHANGE_NORMAL_SVC_CHECK_INTERVAL on bbdo3.0 and grpc -86. [x] **BEEXTCMD_GRPC2**: external command CHANGE_NORMAL_SVC_CHECK_INTERVAL on bbdo2.0 and grpc -87. [x] **BEEXTCMD_GRPC3**: external command CHANGE_NORMAL_HOST_CHECK_INTERVAL on bbdo3.0 and grpc -88. [x] **BEEXTCMD_GRPC4**: external command CHANGE_NORMAL_HOST_CHECK_INTERVAL on bbdo2.0 and grpc -89. [x] **BEEXTCMD_REVERSE_GRPC1**: external command CHANGE_NORMAL_SVC_CHECK_INTERVAL on bbdo3.0 and reversed gRPC -90. [x] **BEEXTCMD_REVERSE_GRPC2**: external command CHANGE_NORMAL_SVC_CHECK_INTERVAL on bbdo2.0 and grpc reversed -91. [x] **BEEXTCMD_REVERSE_GRPC3**: external command CHANGE_NORMAL_HOST_CHECK_INTERVAL on bbdo3.0 and grpc reversed -92. [x] **BEEXTCMD_REVERSE_GRPC4**: external command CHANGE_NORMAL_HOST_CHECK_INTERVAL on bbdo2.0 and grpc reversed -93. [x] **BEHOSTCHECK**: external command CHECK_SERVICE_RESULT -94. [x] **BEHS1**: store_in_resources is enabled and store_in_hosts_services is not. Only writes into resources should be done (except hosts/services events that continue to be written in hosts/services tables) -95. [x] **BEINSTANCE**: Instance to bdd -96. [x] **BEINSTANCESTATUS**: Instance status to bdd -97. [x] **BENCH_${nb_check}STATUS**: external command CHECK_SERVICE_RESULT 1000 times -98. [x] **BENCH_1000STATUS_100${suffixe}**: external command CHECK_SERVICE_RESULT 100 times with 100 pollers with 20 services -99. [x] **BEPBBEE1**: central-module configured with bbdo_version 3.0 but not others. Unable to establish connection. -100. [x] **BEPBBEE2**: bbdo_version 3 not compatible with sql/storage -101. [x] **BEPBBEE3**: bbdo_version 3 generates new bbdo protobuf service status messages. -102. [x] **BEPBBEE4**: bbdo_version 3 generates new bbdo protobuf host status messages. -103. [x] **BEPBBEE5**: bbdo_version 3 generates new bbdo protobuf service messages. -104. [x] **BEPBCVS**: bbdo_version 3 communication of custom variables. -105. [x] **BEPBRI1**: bbdo_version 3 use pb_resource new bbdo protobuf ResponsiveInstance message. -106. [x] **BERD1**: Starting/stopping Broker does not create duplicated events. -107. [x] **BERD2**: Starting/stopping Engine does not create duplicated events. -108. [x] **BERDUC1**: Starting/stopping Broker does not create duplicated events in usual cases -109. [x] **BERDUC2**: Starting/stopping Engine does not create duplicated events in usual cases -110. [x] **BERDUC3U1**: Starting/stopping Broker does not create duplicated events in usual cases with unified_sql and BBDO 3.0 -111. [x] **BERDUC3U2**: Starting/stopping Engine does not create duplicated events in usual cases with unified_sql and BBDO 3.0 -112. [x] **BERDUCA300**: Starting/stopping Engine is stopped ; it should emit a stop event and receive an ack event with events to clean from broker. -113. [x] **BERDUCA301**: Starting/stopping Engine is stopped ; it should emit a stop event and receive an ack event with events to clean from broker with bbdo 3.0.1. -114. [x] **BERDUCU1**: Starting/stopping Broker does not create duplicated events in usual cases with unified_sql -115. [x] **BERDUCU2**: Starting/stopping Engine does not create duplicated events in usual cases with unified_sql -116. [x] **BERES1**: store_in_resources is enabled and store_in_hosts_services is not. Only writes into resources should be done (except hosts/services events that continue to be written in hosts/services tables) -117. [x] **BESERVCHECK**: external command CHECK_SERVICE_RESULT -118. [x] **BESS1**: Start-Stop Broker/Engine - Broker started first - Broker stopped first -119. [x] **BESS2**: Start-Stop Broker/Engine - Broker started first - Engine stopped first -120. [x] **BESS3**: Start-Stop Broker/Engine - Engine started first - Engine stopped first -121. [x] **BESS4**: Start-Stop Broker/Engine - Engine started first - Broker stopped first -122. [x] **BESS5**: Start-Stop Broker/engine - Engine debug level is set to all, it should not hang -123. [x] **BESSBQ1**: A very bad queue file is written for broker. Broker and Engine are then started, Broker must read the file raising an error because of that file and then get data sent by Engine. -124. [x] **BESS_CRYPTED_GRPC1**: Start-Stop grpc version Broker/Engine - well configured -125. [x] **BESS_CRYPTED_GRPC2**: Start-Stop grpc version Broker/Engine only server crypted -126. [x] **BESS_CRYPTED_GRPC3**: Start-Stop grpc version Broker/Engine only engine crypted -127. [x] **BESS_CRYPTED_REVERSED_GRPC1**: Start-Stop grpc version Broker/Engine - well configured -128. [x] **BESS_CRYPTED_REVERSED_GRPC2**: Start-Stop grpc version Broker/Engine only engine server crypted -129. [x] **BESS_CRYPTED_REVERSED_GRPC3**: Start-Stop grpc version Broker/Engine only engine crypted -130. [x] **BESS_ENGINE_DELETE_HOST**: once engine and cbd started, stop and restart cbd, delete an host and reload engine, cbd mustn't core -131. [x] **BESS_GRPC1**: Start-Stop grpc version Broker/Engine - Broker started first - Broker stopped first -132. [x] **BESS_GRPC2**: Start-Stop grpc version Broker/Engine - Broker started first - Engine stopped first -133. [x] **BESS_GRPC3**: Start-Stop grpc version Broker/Engine - Engine started first - Engine stopped first -134. [x] **BESS_GRPC4**: Start-Stop grpc version Broker/Engine - Engine started first - Broker stopped first -135. [x] **BESS_GRPC5**: Start-Stop grpc version Broker/engine - Engine debug level is set to all, it should not hang -136. [x] **BESS_GRPC_COMPRESS1**: Start-Stop grpc version Broker/Engine - Broker started first - Broker stopped last compression activated -137. [x] **BETAG1**: Engine is configured with some tags. When broker receives them, it stores them in the centreon_storage.tags table. Broker is started before. -138. [x] **BETAG2**: Engine is configured with some tags. When broker receives them, it stores them in the centreon_storage.tags table. Engine is started before. -139. [x] **BEUTAG1**: Engine is configured with some tags. When broker receives them through unified_sql stream, it stores them in the centreon_storage.tags table. Broker is started before. -140. [x] **BEUTAG10**: some services are configured with tags on two pollers. Then tags are removed from some of them and in centreon_storage, we can observe resources_tags table updated. -141. [x] **BEUTAG11**: some services are configured with tags on two pollers. Then several tags are removed, and we can observe resources_tags table updated. -142. [x] **BEUTAG12**: Engine is configured with some tags. Group tags tag2, tag6 are set to hosts 1 and 2. Category tags tag4 and tag8 are added to hosts 2, 3, 4. The resources and resources_tags tables are well filled. The tag6 and tag8 are removed and resources_tags is also well updated. -143. [x] **BEUTAG2**: Engine is configured with some tags. A new service is added with a tag. Broker should make the relations. -144. [x] **BEUTAG3**: Engine is configured with some tags. When broker receives them, it stores them in the centreon_storage.tags table. Engine is started before. -145. [x] **BEUTAG4**: Engine is configured with some tags. Group tags tag9, tag13 are set to services 1 and 3. Category tags tag3 and tag11 are added to services 1, 3, 5 and 6. The centreon_storage.resources and resources_tags tables are well filled. -146. [x] **BEUTAG5**: Engine is configured with some tags. Group tags tag2, tag6 are set to hosts 1 and 2. Category tags tag4 and tag8 are added to hosts 2, 3, 4. The resources and resources_tags tables are well filled. -147. [x] **BEUTAG6**: Engine is configured with some tags. When broker receives them, it stores them in the centreon_storage.resources_tags table. Engine is started before. -148. [x] **BEUTAG7**: some services are configured and deleted with tags on two pollers. -149. [x] **BEUTAG8**: Services have tags provided by templates. -150. [x] **BEUTAG9**: hosts have tags provided by templates. -151. [x] **BE_DEFAULT_NOTIFCATION_INTERVAL_IS_ZERO_SERVICE_RESOURCE**: default notification_interval must be set to NULL in services, hosts and resources tables. -152. [x] **BE_NOTIF_OVERFLOW**: bbdo 2.0 notification number =40000. make an overflow => notification_number null in db -153. [x] **BE_TIME_NULL_SERVICE_RESOURCE**: With BBDO 3, notification_interval time must be set to NULL on 0 in services, hosts and resources tables. -154. [x] **BRCS1**: Broker reverse connection stopped -155. [x] **BRCTS1**: Broker reverse connection too slow -156. [x] **BRCTSMN**: Broker connected to map with neb filter -157. [x] **BRCTSMNS**: Broker connected to map with neb and storage filters -158. [x] **BRGC1**: Broker good reverse connection -159. [x] **BRRDCDDID1**: RRD metrics deletion from index ids with rrdcached. -160. [x] **BRRDCDDIDDB1**: RRD metrics deletion from index ids with a query in centreon_storage with rrdcached. -161. [x] **BRRDCDDIDU1**: RRD metrics deletion from index ids with unified sql output with rrdcached. -162. [x] **BRRDCDDM1**: RRD metrics deletion from metric ids with rrdcached. -163. [x] **BRRDCDDMDB1**: RRD metrics deletion from metric ids with a query in centreon_storage and rrdcached. -164. [x] **BRRDCDDMID1**: RRD deletion of non existing metrics and indexes with rrdcached -165. [x] **BRRDCDDMIDU1**: RRD deletion of non existing metrics and indexes with rrdcached -166. [x] **BRRDCDDMU1**: RRD metric deletion on table metric with unified sql output with rrdcached -167. [x] **BRRDCDRB1**: RRD metric rebuild with gRPC API. 3 indexes are selected then a message to rebuild them is sent. This is done with storage/sql sql output and rrdcached. -168. [x] **BRRDCDRBDB1**: RRD metric rebuild with a query in centreon_storage and unified sql with rrdcached -169. [x] **BRRDCDRBU1**: RRD metric rebuild with gRPC API. 3 indexes are selected then a message to rebuild them is sent. This is done with unified_sql output and rrdcached. -170. [x] **BRRDCDRBUDB1**: RRD metric rebuild with a query in centreon_storage and unified sql with rrdcached -171. [x] **BRRDDID1**: RRD metrics deletion from index ids. -172. [x] **BRRDDIDDB1**: RRD metrics deletion from index ids with a query in centreon_storage. -173. [x] **BRRDDIDU1**: RRD metrics deletion from index ids with unified sql output. -174. [x] **BRRDDM1**: RRD metrics deletion from metric ids. -175. [x] **BRRDDMDB1**: RRD metrics deletion from metric ids with a query in centreon_storage. -176. [x] **BRRDDMID1**: RRD deletion of non existing metrics and indexes -177. [x] **BRRDDMIDU1**: RRD deletion of non existing metrics and indexes -178. [x] **BRRDDMU1**: RRD metric deletion on table metric with unified sql output -179. [x] **BRRDRBDB1**: RRD metric rebuild with a query in centreon_storage and unified sql -180. [x] **BRRDRBUDB1**: RRD metric rebuild with a query in centreon_storage and unified sql -181. [x] **BRRDRM1**: RRD metric rebuild with gRPC API. 3 indexes are selected then a message to rebuild them is sent. This is done with storage/sql sql output. -182. [x] **BRRDRMU1**: RRD metric rebuild with gRPC API. 3 indexes are selected then a message to rebuild them is sent. This is done with unified_sql output. -183. [x] **BRRDUPLICATE**: RRD metric rebuild with a query in centreon_storage and unified sql with duplicate rows in database -184. [x] **BRRDWM1**: We are working with BBDO3. This test checks protobuf metrics and status are sent to cbd RRD. -185. [x] **CBD_RELOAD_AND_FILTERS**: We start engine/broker with a classical configuration. All is up and running. Some filters are added to the rrd output and cbd is reloaded. All is still up and running but some events are rejected. Then all is newly set as filter and all events are sent to rrd broker. -186. [x] **CBD_RELOAD_AND_FILTERS_WITH_OPR**: We start engine/broker with an almost classical configuration, just the connection between cbd central and cbd rrd is reversed with one peer retention. All is up and running. Some filters are added to the rrd output and cbd is reloaded. All is still up and running but some events are rejected. Then all is newly set as filter and all events are sent to rrd broker. -187. [x] **EBBPS1**: 1000 service check results are sent to the poller. The test is done with the unified_sql stream, no service status is lost, we find the 1000 results in the database: table resources. -188. [x] **EBBPS2**: 1000 service check results are sent to the poller. The test is done with the unified_sql stream, no service status is lost, we find the 1000 results in the database: table services. -189. [x] **EBDP1**: Four new pollers are started and then we remove Poller3. -190. [x] **EBDP2**: Three new pollers are started, then they are killed. After a simple restart of broker, it is still possible to remove Poller2 if removed from the configuration. -191. [x] **EBDP3**: Three new pollers are started, then they are killed. It is still possible to remove Poller2 if removed from the configuration. -192. [x] **EBDP4**: Four new pollers are started and then we remove Poller3 with its hosts and services. All service status/host status are then refused by broker. -193. [x] **EBDP5**: Four new pollers are started and then we remove Poller3. -194. [x] **EBDP6**: Three new pollers are started, then they are killed. After a simple restart of broker, it is still possible to remove Poller2 if removed from the configuration. -195. [x] **EBDP7**: Three new pollers are started, then they are killed. It is still possible to remove Poller2 if removed from the configuration. -196. [x] **EBDP8**: Four new pollers are started and then we remove Poller3 with its hosts and services. All service status/host status are then refused by broker. -197. [x] **EBDP_GRPC2**: Three new pollers are started, then they are killed. After a simple restart of broker, it is still possible to remove Poller2 if removed from the configuration. -198. [x] **EBMSSM**: 1000 services are configured with 100 metrics each. The rrd output is removed from the broker configuration. GetSqlManagerStats is called to measure writes into data_bin. -199. [x] **EBNHG1**: New host group with several pollers and connections to DB -200. [x] **EBNHG4**: New host group with several pollers and connections to DB with broker and rename this hostgroup -201. [x] **EBNHGU1**: New host group with several pollers and connections to DB with broker configured with unified_sql -202. [x] **EBNHGU2**: New host group with several pollers and connections to DB with broker configured with unified_sql -203. [x] **EBNHGU3**: New host group with several pollers and connections to DB with broker configured with unified_sql -204. [x] **EBNHGU4**: New host group with several pollers and connections to DB with broker and rename this hostgroup -205. [x] **EBNSG1**: New service group with several pollers and connections to DB -206. [x] **EBNSGU1**: New service group with several pollers and connections to DB with broker configured with unified_sql -207. [x] **EBNSGU2**: New service group with several pollers and connections to DB with broker configured with unified_sql -208. [x] **EBNSVC1**: New services with several pollers -209. [x] **EBPS2**: 1000 services are configured with 20 metrics each. The rrd output is removed from the broker configuration to avoid to write too many rrd files. While metrics are written in bulk, the database is stopped. This must not crash broker. -210. [x] **EBSAU2**: New services with action_url with more than 2000 characters -211. [x] **EBSN3**: New services with notes with more than 500 characters -212. [x] **EBSNU1**: New services with notes_url with more than 2000 characters -213. [x] **ENRSCHE1**: Verify that next check of a rescheduled host is made at last_check + interval_check -214. [x] **FILTER_ON_LUA_EVENT**: stream connector with a bad configured filter generate a log error message -215. [x] **LOGV2DB1**: log-v2 disabled old log enabled check broker sink -216. [x] **LOGV2DB2**: log-v2 disabled old log disabled check broker sink -217. [x] **LOGV2DF1**: log-v2 disabled old log enabled check logfile sink -218. [x] **LOGV2DF2**: log-v2 disabled old log disabled check logfile sink -219. [x] **LOGV2EB1**: Checking broker sink when log-v2 is enabled and legacy logs are disabled. -220. [x] **LOGV2EB2**: log-v2 enabled old log enabled check broker sink -221. [x] **LOGV2EBU1**: Checking broker sink when log-v2 is enabled and legacy logs are disabled with bbdo3. -222. [x] **LOGV2EBU2**: Check Broker sink with log-v2 enabled and legacy log enabled with BBDO3. -223. [x] **LOGV2EF1**: log-v2 enabled old log disabled check logfile sink -224. [x] **LOGV2EF2**: log-v2 enabled old log enabled check logfile sink -225. [x] **LOGV2FE2**: log-v2 enabled old log enabled check logfile sink -226. [x] **RLCode**: Test if reloading LUA code in a stream connector applies the changes -227. [x] **SDER**: The check attempts and the max check attempts of (host_1,service_1) are changed to 280 thanks to the retention.dat file. Then engine and broker are started and broker should write these values in the services and resources tables. We only test the services table because we need a resources table that allows bigger numbers for these two attributes. But we see that broker doesn't crash anymore. -228. [x] **SEVERAL_FILTERS_ON_LUA_EVENT**: Two stream connectors with different filters are configured. -229. [x] **STORAGE_ON_LUA**: The category 'storage' is applied on the stream connector. Only events of this category should be sent to this stream. -230. [x] **STUPID_FILTER**: Unified SQL is configured with only the bbdo category as filter. An error is raised by broker and broker should run correctly. -231. [x] **Service_increased_huge_check_interval**: New services with high check interval at creation time. -232. [x] **Start_Stop_Broker_Engine_${id}**: Start-Stop Broker/Engine - Broker started first - Engine stopped first -233. [x] **Start_Stop_Engine_Broker_${id}**: Start-Stop Broker/Engine - Broker started first - Broker stopped first -234. [x] **UNIFIED_SQL_FILTER**: With bbdo version 3.0.1, we watch events written or rejected in unified_sql -235. [x] **VICT_ONE_CHECK_METRIC**: victoria metrics metric output -236. [x] **VICT_ONE_CHECK_METRIC_AFTER_FAILURE**: victoria metrics metric output after victoria shutdown -237. [x] **VICT_ONE_CHECK_STATUS**: victoria metrics status output -238. [x] **not1**: This test case configures a single service and verifies that a notification is sent when the service is in a non-OK state. -239. [x] **not10**: This test case involves scheduling downtime on a down host. After the downtime is finished and the host is still critical, we should receive a critical notification. -240. [x] **not11**: This test case involves scheduling downtime on a down host that already had a critical notification. After putting it in the UP state when the downtime is finished and the host is UP, we should receive a recovery notification. -241. [x] **not12**: This test case involves configuring one service and checking that three alerts are sent for it. -242. [x] **not13**: Escalations -243. [x] **not2**: This test case configures a single service and verifies that a recovery notification is sent after a service recovers from a non-OK state. -244. [x] **not3**: This test case configures a single service and verifies that a non-OK notification is sent after the service exits downtime. -245. [x] **not4**: This test case configures a single service and verifies that a non-OK notification is sent when the acknowledgement is completed. -246. [x] **not5**: This test case configures two services with two different users being notified when the services transition to a critical state. -247. [x] **not6**: This test case validates the behavior when the notification time period is set to null. -248. [x] **not7**: This test case simulates a host alert scenario. -249. [x] **not8**: This test validates the critical host notification. -250. [x] **not9**: This test case configures a single host and verifies that a recovery notification is sent after the host recovers from a non-OK state. +9. [x] **ANO_NOFILE_VERIF_CONFIG_NO_ERROR**: an anomaly detection without threshold file doesn't display error on config check +10. [x] **ANO_OUT_LOWER_THAN_LIMIT**: an anomaly detection with a perfdata lower than lower limit make a critical state +11. [x] **ANO_OUT_UPPER_THAN_LIMIT**: an anomaly detection with a perfdata upper than upper limit make a critical state +12. [x] **ANO_TOO_OLD_FILE**: An anomaly detection with an oldest threshold file must be in unknown state +13. [x] **AOUTLU1**: an anomaly detection with a perfdata upper than upper limit make a critical state with bbdo 3 +14. [x] **BAM_STREAM_FILTER**: With bbdo version 3.0.1, a BA of type 'worst' with one service is configured. The BA is in critical state, because of its service. we watch its events +15. [x] **BEACK1**: Engine has a critical service. An external command is sent to acknowledge it. The centreon_storage.acknowledgements table is then updated with this acknowledgement. The service is newly set to OK. And the acknowledgement in database is deleted from engine but still open on the database. +16. [x] **BEACK2**: Configuration is made with BBDO3. Engine has a critical service. An external command is sent to acknowledge it. The centreon_storage.acknowledgements table is then updated with this acknowledgement. The service is newly set to OK. And the acknowledgement in database is deleted. +17. [x] **BEACK3**: Engine has a critical service. An external command is sent to acknowledge it. The centreon_storage.acknowledgements table is then updated with this acknowledgement. The acknowledgement is removed and the comment in the comments table has its deletion_time column updated. +18. [x] **BEACK4**: Configuration is made with BBDO3. Engine has a critical service. An external command is sent to acknowledge it. The centreon_storage.acknowledgements table is then updated with this acknowledgement. The acknowledgement is removed and the comment in the comments table has its deletion_time column updated. +19. [x] **BEACK5**: Engine has a critical service. An external command is sent to acknowledge it ; the acknowledgement is sticky. The centreon_storage.acknowledgements table is then updated with this acknowledgement. The service is newly set to WARNING. And the acknowledgement in database is still there. +20. [x] **BEACK6**: Configuration is made with BBDO3. Engine has a critical service. An external command is sent to acknowledge it ; the acknowledgement is sticky. The centreon_storage.acknowledgements table is then updated with this acknowledgement. The service is newly set to WARNING. And the acknowledgement in database is still there. +21. [x] **BEACK8**: Engine has a critical service. It is configured with BBDO 3. An external command is sent to acknowledge it ; the acknowledgement is normal. The centreon_storage.acknowledgements table is then updated with this acknowledgement. The service is newly set to WARNING. And the acknowledgement in database is removed (not sticky). +22. [x] **BEATOI11**: external command SEND_CUSTOM_HOST_NOTIFICATION with option_number=1 should work +23. [x] **BEATOI12**: external command SEND_CUSTOM_HOST_NOTIFICATION with option_number>7 should fail +24. [x] **BEATOI13**: external command Schedule Service Downtime with duration<0 should fail +25. [x] **BEATOI21**: external command ADD_HOST_COMMENT and DEL_HOST_COMMENT should work +26. [x] **BEATOI22**: external command DEL_HOST_COMMENT with comment_id<0 should fail +27. [x] **BEATOI23**: external command ADD_SVC_COMMENT with persistent=0 should work +28. [x] **BECC1**: Broker/Engine communication with compression between central and poller +29. [x] **BECT1**: Broker/Engine communication with anonymous TLS between central and poller +30. [x] **BECT2**: Broker/Engine communication with TLS between central and poller with key/cert +31. [x] **BECT3**: Broker/Engine communication with anonymous TLS and ca certificate +32. [x] **BECT4**: Broker/Engine communication with TLS between central and poller with key/cert and hostname forced +33. [x] **BECT_GRPC1**: Broker/Engine communication with GRPC and with anonymous TLS between central and poller +34. [x] **BECT_GRPC2**: Broker/Engine communication with TLS between central and poller with key/cert +35. [x] **BECT_GRPC3**: Broker/Engine communication with anonymous TLS and ca certificate +36. [x] **BECT_GRPC4**: Broker/Engine communication with TLS between central and poller with key/cert and hostname forced +37. [x] **BECUSTOMHOSTVAR**: external command CHANGE_CUSTOM_HOST_VAR on SNMPVERSION +38. [x] **BECUSTOMSVCVAR**: external command CHANGE_CUSTOM_SVC_VAR on CRITICAL +39. [x] **BEDTHOSTFIXED**: A downtime is set on a host, the total number of downtimes is really 21 (1 for the host and 20 for its 20 services) then we delete this downtime and the number is 0. +40. [x] **BEDTMASS1**: New services with several pollers are created. Then downtimes are set on all configured hosts. This action results on 1050 downtimes if we also count impacted services. Then all these downtimes are removed. This test is done with BBDO 3.0.0 +41. [x] **BEDTMASS2**: New services with several pollers are created. Then downtimes are set on all configured hosts. This action results on 1050 downtimes if we also count impacted services. Then all these downtimes are removed. This test is done with BBDO 2.0 +42. [x] **BEDTSVCFIXED**: A downtime is set on a service, the total number of downtimes is really 1 then we delete this downtime and the number of downtime is 0. +43. [x] **BEDTSVCREN1**: A downtime is set on a service then the service is renamed. The downtime is still active on the renamed service. The downtime is removed from the renamed service and it is well removed. +44. [x] **BEEXTCMD1**: external command CHANGE_NORMAL_SVC_CHECK_INTERVAL on bbdo3.0 +45. [x] **BEEXTCMD10**: external command CHANGE_MAX_SVC_CHECK_ATTEMPTS on bbdo2.0 +46. [x] **BEEXTCMD11**: external command CHANGE_MAX_HOST_CHECK_ATTEMPTS on bbdo3.0 +47. [x] **BEEXTCMD12**: external command CHANGE_MAX_HOST_CHECK_ATTEMPTS on bbdo2.0 +48. [x] **BEEXTCMD13**: external command CHANGE_HOST_CHECK_TIMEPERIOD on bbdo3.0 +49. [x] **BEEXTCMD14**: external command CHANGE_HOST_CHECK_TIMEPERIOD on bbdo2.0 +50. [x] **BEEXTCMD15**: external command CHANGE_HOST_NOTIFICATION_TIMEPERIOD on bbdo3.0 +51. [x] **BEEXTCMD16**: external command CHANGE_HOST_NOTIFICATION_TIMEPERIOD on bbdo2.0 +52. [x] **BEEXTCMD17**: external command CHANGE_SVC_CHECK_TIMEPERIOD on bbdo3.0 +53. [x] **BEEXTCMD18**: external command CHANGE_SVC_CHECK_TIMEPERIOD on bbdo2.0 +54. [x] **BEEXTCMD19**: external command CHANGE_SVC_NOTIFICATION_TIMEPERIOD on bbdo3.0 +55. [x] **BEEXTCMD2**: external command CHANGE_NORMAL_SVC_CHECK_INTERVAL on bbdo2.0 +56. [x] **BEEXTCMD20**: external command CHANGE_SVC_NOTIFICATION_TIMEPERIOD on bbdo2.0 +57. [x] **BEEXTCMD21**: external command DISABLE_HOST_AND_CHILD_NOTIFICATIONS and ENABLE_HOST_AND_CHILD_NOTIFICATIONS on bbdo3.0 +58. [x] **BEEXTCMD22**: external command DISABLE_HOST_AND_CHILD_NOTIFICATIONS and ENABLE_HOST_AND_CHILD_NOTIFICATIONS on bbdo2.0 +59. [x] **BEEXTCMD23**: external command DISABLE_HOST_CHECK and ENABLE_HOST_CHECK on bbdo3.0 +60. [x] **BEEXTCMD24**: external command DISABLE_HOST_CHECK and ENABLE_HOST_CHECK on bbdo2.0 +61. [x] **BEEXTCMD25**: external command DISABLE_HOST_EVENT_HANDLER and ENABLE_HOST_EVENT_HANDLER on bbdo3.0 +62. [x] **BEEXTCMD26**: external command DISABLE_HOST_EVENT_HANDLER and ENABLE_HOST_EVENT_HANDLER on bbdo2.0 +63. [x] **BEEXTCMD27**: external command DISABLE_HOST_FLAP_DETECTION and ENABLE_HOST_FLAP_DETECTION on bbdo3.0 +64. [x] **BEEXTCMD28**: external command DISABLE_HOST_FLAP_DETECTION and ENABLE_HOST_FLAP_DETECTION on bbdo2.0 +65. [x] **BEEXTCMD29**: external command DISABLE_HOST_NOTIFICATIONS and ENABLE_HOST_NOTIFICATIONS on bbdo3.0 +66. [x] **BEEXTCMD3**: external command CHANGE_NORMAL_HOST_CHECK_INTERVAL on bbdo3.0 +67. [x] **BEEXTCMD30**: external command DISABLE_HOST_NOTIFICATIONS and ENABLE_HOST_NOTIFICATIONS on bbdo2.0 +68. [x] **BEEXTCMD31**: external command DISABLE_HOST_SVC_CHECKS and ENABLE_HOST_SVC_CHECKS on bbdo3.0 +69. [x] **BEEXTCMD32**: external command DISABLE_HOST_SVC_CHECKS and ENABLE_HOST_SVC_CHECKS on bbdo2.0 +70. [x] **BEEXTCMD33**: external command DISABLE_HOST_SVC_NOTIFICATIONS and ENABLE_HOST_SVC_NOTIFICATIONS on bbdo3.0 +71. [x] **BEEXTCMD34**: external command DISABLE_HOST_SVC_NOTIFICATIONS and ENABLE_HOST_SVC_NOTIFICATIONS on bbdo2.0 +72. [x] **BEEXTCMD35**: external command DISABLE_PASSIVE_HOST_CHECKS and ENABLE_PASSIVE_HOST_CHECKS on bbdo3.0 +73. [x] **BEEXTCMD36**: external command DISABLE_PASSIVE_HOST_CHECKS and ENABLE_PASSIVE_HOST_CHECKS on bbdo2.0 +74. [x] **BEEXTCMD37**: external command DISABLE_PASSIVE_SVC_CHECKS and ENABLE_PASSIVE_SVC_CHECKS on bbdo3.0 +75. [x] **BEEXTCMD38**: external command DISABLE_PASSIVE_SVC_CHECKS and ENABLE_PASSIVE_SVC_CHECKS on bbdo2.0 +76. [x] **BEEXTCMD39**: external command START_OBSESSING_OVER_HOST and STOP_OBSESSING_OVER_HOST on bbdo3.0 +77. [x] **BEEXTCMD4**: external command CHANGE_NORMAL_HOST_CHECK_INTERVAL on bbdo2.0 +78. [x] **BEEXTCMD40**: external command START_OBSESSING_OVER_HOST and STOP_OBSESSING_OVER_HOST on bbdo2.0 +79. [x] **BEEXTCMD41**: external command START_OBSESSING_OVER_SVC and STOP_OBSESSING_OVER_SVC on bbdo3.0 +80. [x] **BEEXTCMD42**: external command START_OBSESSING_OVER_SVC and STOP_OBSESSING_OVER_SVC on bbdo2.0 +81. [x] **BEEXTCMD5**: external command CHANGE_RETRY_SVC_CHECK_INTERVAL on bbdo3.0 +82. [x] **BEEXTCMD6**: external command CHANGE_RETRY_SVC_CHECK_INTERVAL on bbdo2.0 +83. [x] **BEEXTCMD7**: external command CHANGE_RETRY_HOST_CHECK_INTERVAL on bbdo3.0 +84. [x] **BEEXTCMD8**: external command CHANGE_RETRY_HOST_CHECK_INTERVAL on bbdo2.0 +85. [x] **BEEXTCMD9**: external command CHANGE_MAX_SVC_CHECK_ATTEMPTS on bbdo3.0 +86. [x] **BEEXTCMD_COMPRESS_GRPC1**: external command CHANGE_NORMAL_SVC_CHECK_INTERVAL on bbdo3.0 and compressed grpc +87. [x] **BEEXTCMD_GRPC1**: external command CHANGE_NORMAL_SVC_CHECK_INTERVAL on bbdo3.0 and grpc +88. [x] **BEEXTCMD_GRPC2**: external command CHANGE_NORMAL_SVC_CHECK_INTERVAL on bbdo2.0 and grpc +89. [x] **BEEXTCMD_GRPC3**: external command CHANGE_NORMAL_HOST_CHECK_INTERVAL on bbdo3.0 and grpc +90. [x] **BEEXTCMD_GRPC4**: external command CHANGE_NORMAL_HOST_CHECK_INTERVAL on bbdo2.0 and grpc +91. [x] **BEEXTCMD_REVERSE_GRPC1**: external command CHANGE_NORMAL_SVC_CHECK_INTERVAL on bbdo3.0 and reversed gRPC +92. [x] **BEEXTCMD_REVERSE_GRPC2**: external command CHANGE_NORMAL_SVC_CHECK_INTERVAL on bbdo2.0 and grpc reversed +93. [x] **BEEXTCMD_REVERSE_GRPC3**: external command CHANGE_NORMAL_HOST_CHECK_INTERVAL on bbdo3.0 and grpc reversed +94. [x] **BEEXTCMD_REVERSE_GRPC4**: external command CHANGE_NORMAL_HOST_CHECK_INTERVAL on bbdo2.0 and grpc reversed +95. [x] **BEHOSTCHECK**: external command CHECK_HOST_RESULT +96. [x] **BEHS1**: store_in_resources is enabled and store_in_hosts_services is not. Only writes into resources should be done (except hosts/services events that continue to be written in hosts/services tables) +97. [x] **BEINSTANCE**: Instance to bdd +98. [x] **BEINSTANCESTATUS**: Instance status to bdd +99. [x] **BENCH_${nb_checks}STATUS**: external command CHECK_SERVICE_RESULT 1000 times +100. [x] **BENCH_${nb_checks}STATUS_TRACES**: external command CHECK_SERVICE_RESULT ${nb_checks} times +101. [x] **BENCH_${nb_checks}_REVERSE_SERVICE_STATUS_TRACES_WITHOUT_SQL**: Broker is configured without SQL output. The connection between Engine and Broker is reversed. External command CHECK_SERVICE_RESULT is sent ${nb_checks} times. Logs are in trace level. +102. [x] **BENCH_${nb_checks}_REVERSE_SERVICE_STATUS_WITHOUT_SQL**: Broker is configured without SQL output. The connection between Engine and Broker is reversed. External command CHECK_SERVICE_RESULT is sent ${nb_checks} times. +103. [x] **BENCH_${nb_checks}_SERVICE_STATUS_TRACES_WITHOUT_SQL**: Broker is configured without SQL output. External command CHECK_SERVICE_RESULT is sent ${nb_checks} times. Logs are in trace level. +104. [x] **BENCH_${nb_checks}_SERVICE_STATUS_WITHOUT_SQL**: Broker is configured without SQL output. External command CHECK_SERVICE_RESULT is sent ${nb_checks} times. +105. [x] **BENCH_1000STATUS_100${suffixe}**: external command CHECK_SERVICE_RESULT 100 times with 100 pollers with 20 services +106. [x] **BEPBBEE1**: central-module configured with bbdo_version 3.0 but not others. Unable to establish connection. +107. [x] **BEPBBEE2**: bbdo_version 3 not compatible with sql/storage +108. [x] **BEPBBEE3**: bbdo_version 3 generates new bbdo protobuf service status messages. +109. [x] **BEPBBEE4**: bbdo_version 3 generates new bbdo protobuf host status messages. +110. [x] **BEPBBEE5**: bbdo_version 3 generates new bbdo protobuf service messages. +111. [x] **BEPBCVS**: bbdo_version 3 communication of custom variables. +112. [x] **BEPBHostParent**: bbdo_version 3 communication of host parent relations +113. [x] **BEPBINST_CONF**: bbdo_version 3 communication of instance configuration. +114. [x] **BEPBRI1**: bbdo_version 3 use pb_resource new bbdo protobuf ResponsiveInstance message. +115. [x] **BEPB_HOST_DEPENDENCY**: BBDO 3 communication of host dependencies. +116. [x] **BEPB_SERVICE_DEPENDENCY**: bbdo_version 3 communication of host dependencies. +117. [x] **BERD1**: Starting/stopping Broker does not create duplicated events. +118. [x] **BERD2**: Starting/stopping Engine does not create duplicated events. +119. [x] **BERDUC1**: Starting/stopping Broker does not create duplicated events in usual cases +120. [x] **BERDUC2**: Starting/stopping Engine does not create duplicated events in usual cases +121. [x] **BERDUC3U1**: Starting/stopping Broker does not create duplicated events in usual cases with unified_sql and BBDO 3.0 +122. [x] **BERDUC3U2**: Starting/stopping Engine does not create duplicated events in usual cases with unified_sql and BBDO 3.0 +123. [x] **BERDUCA300**: Starting/stopping Engine is stopped ; it should emit a stop event and receive an ack event with events to clean from broker. +124. [x] **BERDUCA301**: Starting/stopping Engine is stopped ; it should emit a stop event and receive an ack event with events to clean from broker with bbdo 3.0.1. +125. [x] **BERDUCU1**: Starting/stopping Broker does not create duplicated events in usual cases with unified_sql +126. [x] **BERDUCU2**: Starting/stopping Engine does not create duplicated events in usual cases with unified_sql +127. [x] **BERES1**: store_in_resources is enabled and store_in_hosts_services is not. Only writes into resources should be done (except hosts/services events that continue to be written in hosts/services tables) +128. [x] **BESERVCHECK**: external command CHECK_SERVICE_RESULT +129. [x] **BESS1**: Start-Stop Broker/Engine - Broker started first - Broker stopped first +130. [x] **BESS2**: Start-Stop Broker/Engine - Broker started first - Engine stopped first +131. [x] **BESS2U**: Start-Stop Broker/Engine - Broker started first - Engine stopped first. Unified_sql is used. +132. [x] **BESS3**: Start-Stop Broker/Engine - Engine started first - Engine stopped first +133. [x] **BESS4**: Start-Stop Broker/Engine - Engine started first - Broker stopped first +134. [x] **BESS5**: Start-Stop Broker/engine - Engine debug level is set to all, it should not hang +135. [x] **BESSBQ1**: A very bad queue file is written for broker. Broker and Engine are then started, Broker must read the file raising an error because of that file and then get data sent by Engine. +136. [x] **BESS_CRYPTED_GRPC1**: Start-Stop grpc version Broker/Engine - well configured +137. [x] **BESS_CRYPTED_GRPC2**: Start-Stop grpc version Broker/Engine only server crypted +138. [x] **BESS_CRYPTED_GRPC3**: Start-Stop grpc version Broker/Engine only engine crypted +139. [x] **BESS_CRYPTED_REVERSED_GRPC1**: Start-Stop grpc version Broker/Engine - well configured +140. [x] **BESS_CRYPTED_REVERSED_GRPC2**: Start-Stop grpc version Broker/Engine only engine server crypted +141. [x] **BESS_CRYPTED_REVERSED_GRPC3**: Start-Stop grpc version Broker/Engine only engine crypted +142. [x] **BESS_ENGINE_DELETE_HOST**: once engine and cbd started, stop and restart cbd, delete an host and reload engine, cbd mustn't core +143. [x] **BESS_GRPC1**: Start-Stop grpc version Broker/Engine - Broker started first - Broker stopped first +144. [x] **BESS_GRPC2**: Start-Stop grpc version Broker/Engine - Broker started first - Engine stopped first +145. [x] **BESS_GRPC3**: Start-Stop grpc version Broker/Engine - Engine started first - Engine stopped first +146. [x] **BESS_GRPC4**: Start-Stop grpc version Broker/Engine - Engine started first - Broker stopped first +147. [x] **BESS_GRPC5**: Start-Stop grpc version Broker/engine - Engine debug level is set to all, it should not hang +148. [x] **BESS_GRPC_COMPRESS1**: Start-Stop grpc version Broker/Engine - Broker started first - Broker stopped last compression activated +149. [x] **BETAG1**: Engine is configured with some tags. When broker receives them, it stores them in the centreon_storage.tags table. Broker is started before. +150. [x] **BETAG2**: Engine is configured with some tags. When broker receives them, it stores them in the centreon_storage.tags table. Engine is started before. +151. [x] **BEUTAG1**: Engine is configured with some tags. When broker receives them through unified_sql stream, it stores them in the centreon_storage.tags table. Broker is started before. +152. [x] **BEUTAG10**: some services are configured with tags on two pollers. Then tags are removed from some of them and in centreon_storage, we can observe resources_tags table updated. +153. [x] **BEUTAG11**: some services are configured with tags on two pollers. Then several tags are removed, and we can observe resources_tags table updated. +154. [x] **BEUTAG12**: Engine is configured with some tags. Group tags tag2, tag6 are set to hosts 1 and 2. Category tags tag4 and tag8 are added to hosts 2, 3, 4. The resources and resources_tags tables are well filled. The tag6 and tag8 are removed and resources_tags is also well updated. +155. [x] **BEUTAG2**: Engine is configured with some tags. A new service is added with a tag. Broker should make the relations. +156. [x] **BEUTAG3**: Engine is configured with some tags. When broker receives them, it stores them in the centreon_storage.tags table. Engine is started before. +157. [x] **BEUTAG4**: Engine is configured with some tags. Group tags tag9, tag13 are set to services 1 and 3. Category tags tag3 and tag11 are added to services 1, 3, 5 and 6. The centreon_storage.resources and resources_tags tables are well filled. +158. [x] **BEUTAG5**: Engine is configured with some tags. Group tags tag2, tag6 are set to hosts 1 and 2. Category tags tag4 and tag8 are added to hosts 2, 3, 4. The resources and resources_tags tables are well filled. +159. [x] **BEUTAG6**: Engine is configured with some tags. When broker receives them, it stores them in the centreon_storage.resources_tags table. Engine is started before. +160. [x] **BEUTAG7**: Some services are configured with tags on two pollers. Then tags configuration is modified. +161. [x] **BEUTAG8**: Services have tags provided by templates. +162. [x] **BEUTAG9**: hosts have tags provided by templates. +163. [x] **BEUTAG_REMOVE_HOST_FROM_HOSTGROUP**: remove a host from hostgroup, reload, insert 2 host in the hostgroup must not make sql error +164. [x] **BE_DEFAULT_NOTIFCATION_INTERVAL_IS_ZERO_SERVICE_RESOURCE**: default notification_interval must be set to NULL in services, hosts and resources tables. +165. [x] **BE_NOTIF_OVERFLOW**: bbdo 2.0 notification number =40000. make an overflow => notification_number null in db +166. [x] **BE_TIME_NULL_SERVICE_RESOURCE**: With BBDO 3, notification_interval time must be set to NULL on 0 in services, hosts and resources tables. +167. [x] **BRCS1**: Broker reverse connection stopped +168. [x] **BRCTS1**: Broker reverse connection too slow +169. [x] **BRCTSMN**: Broker connected to map with neb filter +170. [x] **BRCTSMNS**: Broker connected to map with neb and storage filters +171. [x] **BRGC1**: Broker good reverse connection +172. [x] **BRRDCDDID1**: RRD metrics deletion from index ids with rrdcached. +173. [x] **BRRDCDDIDDB1**: RRD metrics deletion from index ids with a query in centreon_storage with rrdcached. +174. [x] **BRRDCDDIDU1**: RRD metrics deletion from index ids with unified sql output with rrdcached. +175. [x] **BRRDCDDM1**: RRD metrics deletion from metric ids with rrdcached. +176. [x] **BRRDCDDMDB1**: RRD metrics deletion from metric ids with a query in centreon_storage and rrdcached. +177. [x] **BRRDCDDMID1**: RRD deletion of non existing metrics and indexes with rrdcached +178. [x] **BRRDCDDMIDU1**: RRD deletion of non existing metrics and indexes with rrdcached +179. [x] **BRRDCDDMU1**: RRD metric deletion on table metric with unified sql output with rrdcached +180. [x] **BRRDCDRB1**: RRD metric rebuild with gRPC API. 3 indexes are selected then a message to rebuild them is sent. This is done with storage/sql sql output and rrdcached. +181. [x] **BRRDCDRBDB1**: RRD metric rebuild with a query in centreon_storage and unified sql with rrdcached +182. [x] **BRRDCDRBU1**: RRD metric rebuild with gRPC API. 3 indexes are selected then a message to rebuild them is sent. This is done with unified_sql output and rrdcached. +183. [x] **BRRDCDRBUDB1**: RRD metric rebuild with a query in centreon_storage and unified sql with rrdcached +184. [x] **BRRDDID1**: RRD metrics deletion from index ids. +185. [x] **BRRDDIDDB1**: RRD metrics deletion from index ids with a query in centreon_storage. +186. [x] **BRRDDIDU1**: RRD metrics deletion from index ids with unified sql output. +187. [x] **BRRDDM1**: RRD metrics deletion from metric ids. +188. [x] **BRRDDMDB1**: RRD metrics deletion from metric ids with a query in centreon_storage. +189. [x] **BRRDDMID1**: RRD deletion of non existing metrics and indexes +190. [x] **BRRDDMIDU1**: RRD deletion of non existing metrics and indexes +191. [x] **BRRDDMU1**: RRD metric deletion on table metric with unified sql output +192. [x] **BRRDRBDB1**: RRD metric rebuild with a query in centreon_storage and unified sql +193. [x] **BRRDRBUDB1**: RRD metric rebuild with a query in centreon_storage and unified sql +194. [x] **BRRDRM1**: RRD metric rebuild with gRPC API. 3 indexes are selected then a message to rebuild them is sent. This is done with storage/sql sql output. +195. [x] **BRRDRMU1**: RRD metric rebuild with gRPC API. 3 indexes are selected then a message to rebuild them is sent. This is done with unified_sql output. +196. [x] **BRRDUPLICATE**: RRD metric rebuild with a query in centreon_storage and unified sql with duplicate rows in database +197. [x] **BRRDWM1**: We are working with BBDO3. This test checks protobuf metrics and status are sent to cbd RRD. +198. [x] **CBD_RELOAD_AND_FILTERS**: We start engine/broker with a classical configuration. All is up and running. Some filters are added to the rrd output and cbd is reloaded. All is still up and running but some events are rejected. Then all is newly set as filter and all events are sent to rrd broker. +199. [x] **CBD_RELOAD_AND_FILTERS_WITH_OPR**: We start engine/broker with an almost classical configuration, just the connection between cbd central and cbd rrd is reversed with one peer retention. All is up and running. Some filters are added to the rrd output and cbd is reloaded. All is still up and running but some events are rejected. Then all is newly set as filter and all events are sent to rrd broker. +200. [x] **DTIM**: New services with several pollers are created. Then downtimes are set on all configured hosts. This action results on 5250 downtimes if we also count impacted services. Then all these downtimes are removed. This test is done with BBDO 3.0.1 +201. [x] **EBBPS1**: 1000 service check results are sent to the poller. The test is done with the unified_sql stream, no service status is lost, we find the 1000 results in the database: table resources. +202. [x] **EBBPS2**: 1000 service check results are sent to the poller. The test is done with the unified_sql stream, no service status is lost, we find the 1000 results in the database: table services. +203. [x] **EBDP1**: Four new pollers are started and then we remove Poller3. +204. [x] **EBDP2**: Three new pollers are started, then they are killed. After a simple restart of broker, it is still possible to remove Poller2 if removed from the configuration. +205. [x] **EBDP3**: Three new pollers are started, then they are killed. It is still possible to remove Poller2 if removed from the configuration. +206. [x] **EBDP4**: Four new pollers are started and then we remove Poller3 with its hosts and services. All service status/host status are then refused by Broker. +207. [x] **EBDP5**: Four new pollers are started and then we remove Poller3. +208. [x] **EBDP6**: Three new pollers are started, then they are killed. After a simple restart of broker, it is still possible to remove Poller2 if removed from the configuration. +209. [x] **EBDP7**: Three new pollers are started, then they are killed. It is still possible to remove Poller2 if removed from the configuration. +210. [x] **EBDP8**: Four new pollers are started and then we remove Poller3 with its hosts and services. All service status/host status are then refused by broker. +211. [x] **EBDP_GRPC2**: Three new pollers are started, then they are killed. After a simple restart of broker, it is still possible to remove Poller2 if removed from the configuration. +212. [x] **EBMSSM**: 1000 services are configured with 100 metrics each. The rrd output is removed from the broker configuration. GetSqlManagerStats is called to measure writes into data_bin. +213. [x] **EBNHG1**: New host group with several pollers and connections to DB +214. [x] **EBNHG4**: New host group with several pollers and connections to DB with broker and rename this hostgroup +215. [x] **EBNHGU1**: New host group with several pollers and connections to DB with broker configured with unified_sql +216. [x] **EBNHGU2**: New host group with several pollers and connections to DB with broker configured with unified_sql +217. [x] **EBNHGU3**: New host group with several pollers and connections to DB with broker configured with unified_sql +218. [x] **EBNHGU4_${test_label}**: New host group with several pollers and connections to DB with broker and rename this hostgroup +219. [x] **EBNSG1**: New service group with several pollers and connections to DB +220. [x] **EBNSGU1**: New service group with several pollers and connections to DB with broker configured with unified_sql +221. [x] **EBNSGU2**: New service group with several pollers and connections to DB with broker configured with unified_sql +222. [x] **EBNSGU3_${test_label}**: New service group with several pollers and connections to DB with broker and rename this servicegroup +223. [x] **EBNSVC1**: New services with several pollers +224. [x] **EBPS2**: 1000 services are configured with 20 metrics each. The rrd output is removed from the broker configuration to avoid to write too many rrd files. While metrics are written in bulk, the database is stopped. This must not crash broker. +225. [x] **EBSAU2**: New services with action_url with more than 2000 characters +226. [x] **EBSN3**: New services with notes with more than 500 characters +227. [x] **EBSNU1**: New services with notes_url with more than 2000 characters +228. [x] **ENRSCHE1**: Verify that next check of a rescheduled host is made at last_check + interval_check +229. [x] **FILTER_ON_LUA_EVENT**: stream connector with a bad configured filter generate a log error message +230. [x] **GRPC_CLOUD_FAILURE**: simulate a broker failure in cloud environment, we provide a muted grpc server and there must remain only one grpc connection. Then we start broker and connection must be ok +231. [x] **GRPC_RECONNECT**: We restart broker and engine must reconnect to it and send data +232. [x] **LCDNU**: the lua cache updates correctly service cache. +233. [x] **LCDNUH**: the lua cache updates correctly host cache +234. [x] **LOGV2DB1**: log-v2 disabled old log enabled check broker sink +235. [x] **LOGV2DB2**: log-v2 disabled old log disabled check broker sink +236. [x] **LOGV2DF1**: log-v2 disabled old log enabled check logfile sink +237. [x] **LOGV2DF2**: log-v2 disabled old log disabled check logfile sink +238. [x] **LOGV2EB1**: Checking broker sink when log-v2 is enabled and legacy logs are disabled. +239. [x] **LOGV2EB2**: log-v2 enabled old log enabled check broker sink +240. [x] **LOGV2EBU1**: Checking broker sink when log-v2 is enabled and legacy logs are disabled with bbdo3. +241. [x] **LOGV2EBU2**: Check Broker sink with log-v2 enabled and legacy log enabled with BBDO3. +242. [x] **LOGV2EF1**: log-v2 enabled old log disabled check logfile sink +243. [x] **LOGV2EF2**: log-v2 enabled old log enabled check logfile sink +244. [x] **LOGV2FE2**: log-v2 enabled old log enabled check logfile sink +245. [x] **RLCode**: Test if reloading LUA code in a stream connector applies the changes +246. [x] **RRD1**: RRD metric rebuild asked with gRPC API. Three non existing indexes IDs are selected then an error message is sent. This is done with unified_sql output. +247. [x] **SDER**: The check attempts and the max check attempts of (host_1,service_1) are changed to 280 thanks to the retention.dat file. Then Engine and Broker are started and Broker should write these values in the services and resources tables. We only test the services table because we need a resources table that allows bigger numbers for these two attributes. But we see that Broker doesn't crash anymore. +248. [x] **SEVERAL_FILTERS_ON_LUA_EVENT**: Two stream connectors with different filters are configured. +249. [x] **STORAGE_ON_LUA**: The category 'storage' is applied on the stream connector. Only events of this category should be sent to this stream. +250. [x] **STUPID_FILTER**: Unified SQL is configured with only the bbdo category as filter. An error is raised by broker and broker should run correctly. +251. [x] **Service_increased_huge_check_interval**: New services with high check interval at creation time. +252. [x] **Services_and_bulks_${id}**: One service is configured with one metric with a name of 150 to 1021 characters. +253. [x] **Start_Stop_Broker_Engine_${id}**: Start-Stop Broker/Engine - Broker started first - Engine stopped first +254. [x] **Start_Stop_Engine_Broker_${id}**: Start-Stop Broker/Engine - Broker started first - Broker stopped first +255. [x] **UNIFIED_SQL_FILTER**: With bbdo version 3.0.1, we watch events written or rejected in unified_sql +256. [x] **VICT_ONE_CHECK_METRIC**: victoria metrics metric output +257. [x] **VICT_ONE_CHECK_METRIC_AFTER_FAILURE**: victoria metrics metric output after victoria shutdown +258. [x] **VICT_ONE_CHECK_STATUS**: victoria metrics status output +259. [x] **Whitelist_Directory_Rights**: log if /etc/centreon-engine-whitelist has not mandatory rights or owner +260. [x] **Whitelist_Empty_Directory**: log if /etc/centreon-engine-whitelist is empty +261. [x] **Whitelist_Host**: test allowed and forbidden commands for hosts +262. [x] **Whitelist_No_Whitelist_Directory**: log if /etc/centreon-engine-whitelist doesn't exist +263. [x] **Whitelist_Perl_Connector**: test allowed and forbidden commands for services +264. [x] **Whitelist_Service**: test allowed and forbidden commands for services +265. [x] **Whitelist_Service_EH**: test allowed and forbidden event handler for services +266. [x] **metric_mapping**: Check if metric name exists using a stream connector +267. [x] **not1**: This test case configures a single service and verifies that a notification is sent when the service is in a non-OK HARD state. +268. [x] **not10**: This test case involves scheduling downtime on a down host that already had a critical notification. When The Host return to UP state we should receive a recovery notification. +269. [x] **not11**: This test case involves configuring one service and checking that three alerts are sent for it. +270. [x] **not12**: Escalations +271. [x] **not13**: notification for a dependensies host +272. [x] **not14**: notification for a Service dependency +273. [x] **not15**: several notification commands for the same user. +274. [x] **not16**: notification for a dependensies services group +275. [x] **not17**: notification for a dependensies host group +276. [x] **not18**: notification delay where first notification delay equal retry check +277. [x] **not19**: notification delay where first notification delay greater than retry check +278. [x] **not1_WL_KO**: This test case configures a single service. When it is in non-OK HARD state a notification should be sent but it is not allowed by the whitelist +279. [x] **not1_WL_OK**: This test case configures a single service. When it is in non-OK HARD state a notification is sent because it is allowed by the whitelist +280. [x] **not2**: This test case configures a single service and verifies that a recovery notification is sent +281. [x] **not20**: notification delay where first notification delay samller than retry check +282. [x] **not3**: This test case configures a single service and verifies the notification system's behavior during and after downtime +283. [x] **not4**: This test case configures a single service and verifies the notification system's behavior during and after acknowledgement +284. [x] **not5**: This test case configures two services with two different users being notified when the services transition to a critical state. +285. [x] **not6**: This test case validate the behavior when the notification time period is set to null. +286. [x] **not7**: This test case simulates a host alert scenario. +287. [x] **not8**: This test validates the critical host notification. +288. [x] **not9**: This test case configures a single host and verifies that a recovery notification is sent after the host recovers from a non-OK state. +289. [x] **not_in_timeperiod_with_send_recovery_notifications_anyways**: This test case configures a single service and verifies that a notification is sent when the service is in a non-OK state and OK is sent outside timeperiod when _send_recovery_notifications_anyways is set +290. [x] **not_in_timeperiod_without_send_recovery_notifications_anyways**: This test case configures a single service and verifies that a notification is sent when the service is in a non-OK state and OK is not sent outside timeperiod when _send_recovery_notifications_anyways is not set ### Ccc 1. [x] **BECCC1**: ccc without port fails with an error message @@ -471,22 +518,26 @@ Here is the list of the currently implemented tests: 1. [x] **Test6Hosts**: as 127.0.0.x point to the localhost address we will simulate check on 6 hosts 2. [x] **TestBadPwd**: test bad password 3. [x] **TestBadUser**: test unknown user +4. [x] **TestWhiteList**: as 127.0.0.x point to the localhost address we will simulate check on 6 hosts ### Engine 1. [x] **EFHC1**: Engine is configured with hosts and we force checks on one 5 times on bbdo2 -2. [x] **EFHC2**: Engine is configured with hosts and we force checks on one 5 times on bbdo2 +2. [x] **EFHC2**: Engine is configured with hosts and we force check on one 5 times on bbdo2 3. [x] **EFHCU1**: Engine is configured with hosts and we force checks on one 5 times on bbdo3. Bbdo3 has no impact on this behavior. resources table is cleared before starting broker. 4. [x] **EFHCU2**: Engine is configured with hosts and we force checks on one 5 times on bbdo3. Bbdo3 has no impact on this behavior. 5. [x] **EMACROS**: macros ADMINEMAIL and ADMINPAGER are replaced in check outputs 6. [x] **EMACROS_NOTIF**: macros ADMINEMAIL and ADMINPAGER are replaced in notification commands -7. [x] **EPC1**: Check with perl connector -8. [x] **ESS1**: Start-Stop (0s between start/stop) 5 times one instance of engine and no coredump -9. [x] **ESS2**: Start-Stop (300ms between start/stop) 5 times one instance of engine and no coredump -10. [x] **ESS3**: Start-Stop (0s between start/stop) 5 times three instances of engine and no coredump -11. [x] **ESS4**: Start-Stop (300ms between start/stop) 5 times three instances of engine and no coredump +7. [x] **EMACROS_SEMICOLON**: Macros with a semicolon are used even if they contain a semicolon. +8. [x] **EPC1**: Check with perl connector +9. [x] **ESS1**: Start-Stop (0s between start/stop) 5 times one instance of engine and no coredump +10. [x] **ESS2**: Start-Stop (300ms between start/stop) 5 times one instance of engine and no coredump +11. [x] **ESS3**: Start-Stop (0s between start/stop) 5 times three instances of engine and no coredump +12. [x] **ESS4**: Start-Stop (300ms between start/stop) 5 times three instances of engine and no coredump +13. [x] **EXT_CONF1**: Engine configuration is overided by json conf +14. [x] **EXT_CONF2**: Engine configuration is overided by json conf after reload ### Migration -1. [x] **MIGRATION**: Migration bbdo2 => sql/storage => unified_sql => bbdo3 +1. [x] **MIGRATION**: Migration bbdo2 with sql/storage to bbdo2 with unified_sql and then to bbdo3 with unified_sql and then to bbdo2 with unified_sql and then to bbdo2 with sql/storage ### Severities 1. [x] **BESEV1**: Engine is configured with some severities. When broker receives them, it stores them in the centreon_storage.severities table. Broker is started before. diff --git a/tests/broker-engine/notifications.robot b/tests/broker-engine/notifications.robot index bf67ece87ed..9cde528b806 100644 --- a/tests/broker-engine/notifications.robot +++ b/tests/broker-engine/notifications.robot @@ -13,6 +13,7 @@ Test Teardown Ctn Save Logs If Failed not1 [Documentation] This test case configures a single service and verifies that a notification is sent when the service is in a non-OK HARD state. [Tags] broker engine services hosts notification + Ctn Clear Commands Status Ctn Config Engine ${1} ${1} ${1} Ctn Config Notifications Ctn Engine Config Set Value In Hosts 0 host_1 notifications_enabled 1 @@ -34,6 +35,51 @@ not1 # Let's wait for the external command check start Ctn Wait For Engine To Be Ready ${1} + ${cmd_service_1} Ctn Get Service Command Id ${1} + Ctn Set Command Status ${cmd_service_1} ${2} + ## Time to set the service to CRITICAL HARD. + Ctn Process Service Result Hard host_1 service_1 ${2} The service_1 is CRITICAL + + ${result} Ctn Check Service Resource Status With Timeout host_1 service_1 ${2} 60 HARD + Should Be True ${result} Service (host_1,service_1) should be CRITICAL HARD + + ${content} Create List SERVICE NOTIFICATION: John_Doe;host_1;service_1;CRITICAL;command_notif; + ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 60 + Should Be True ${result} No notification has been sent concerning a critical service + + Ctn Stop Engine + Ctn Kindly Stop Broker + +not1_WL_OK + [Documentation] This test case configures a single service. When it is in non-OK HARD state + ... a notification is sent because it is allowed by the whitelist + [Tags] broker engine services hosts notification whitelist MON-75741 + Ctn Config Engine ${1} ${1} ${1} + Ctn Config Notifications + Ctn Engine Config Set Value In Hosts 0 host_1 notifications_enabled 1 + Ctn Engine Config Set Value In Hosts 0 host_1 notification_options d,r + Ctn Engine Config Set Value In Hosts 0 host_1 contacts John_Doe + Ctn Engine Config Set Value In Services 0 service_1 contacts John_Doe + Ctn Engine Config Set Value In Services 0 service_1 notification_options w,c,r + Ctn Engine Config Set Value In Services 0 service_1 notifications_enabled 1 + Ctn Engine Config Set Value In Services 0 service_1 notification_period 24x7 + Ctn Engine Config Replace Value In Services 0 service_1 check_interval 1 + Ctn Engine Config Replace Value In Services 0 service_1 retry_interval 1 + Ctn Engine Config Set Value In Contacts 0 John_Doe host_notification_commands command_notif + Ctn Engine Config Set Value In Contacts 0 John_Doe service_notification_commands command_notif + + # create non matching file with /tmp/var/lib/centreon-engine/check.pl 0 1.0.0.0 + ${whitelist_content} Catenate + ... {"whitelist":{"wildcard":["/tmp/var/lib/centreon-engine/toto* * *"], "regex":["/usr/bin/true", "/tmp/var/lib/centreon-engine/check.pl .*"]}} + Create File /etc/centreon-engine-whitelist/test ${whitelist_content} + + ${start} Get Current Date + Ctn Start Broker + Ctn Start Engine + + # Let's wait for the external command check start + Ctn Wait For Engine To Be Ready ${1} + ${cmd_id} Ctn Get Service Command Id ${1} Ctn Set Command Status ${cmd_id} ${2} ## Time to set the service to CRITICAL HARD. @@ -42,16 +88,17 @@ not1 ${result} Ctn Check Service Status With Timeout host_1 service_1 ${2} 60 HARD Should Be True ${result} Service (host_1,service_1) should be CRITICAL HARD - ${content} Create List SERVICE NOTIFICATION: John_Doe;host_1;service_1;CRITICAL;command_notif; + ${content} Create List SERVICE NOTIFICATION: John_Doe;host_1;service_1;CRITICAL;command_notif; my_system_r ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 60 Should Be True ${result} No notification has been sent concerning a critical service Ctn Stop Engine Ctn Kindly Stop Broker -not2 - [Documentation] This test case configures a single service and verifies that a recovery notification is sent - [Tags] broker engine services hosts notification +not1_WL_KO + [Documentation] This test case configures a single service. When it is in non-OK HARD state + ... a notification should be sent but it is not allowed by the whitelist + [Tags] broker engine services hosts notification whitelist MON-75741 Ctn Config Engine ${1} ${1} ${1} Ctn Config Notifications Ctn Engine Config Set Value In Hosts 0 host_1 notifications_enabled 1 @@ -66,6 +113,11 @@ not2 Ctn Engine Config Set Value In Contacts 0 John_Doe host_notification_commands command_notif Ctn Engine Config Set Value In Contacts 0 John_Doe service_notification_commands command_notif + # create non matching file with /tmp/var/lib/centreon-engine/check.pl 0 1.0.0.0 + ${whitelist_content} Catenate + ... {"whitelist":{"wildcard":["/tmp/var/lib/centreon-engine/toto* * *"], "regex":["/usr/bin/good", "/tmp/var/lib/centreon-engine/check.pl .*"]}} + Create File /etc/centreon-engine-whitelist/test ${whitelist_content} + ${start} Get Current Date Ctn Start Broker Ctn Start Engine @@ -81,16 +133,57 @@ not2 ${result} Ctn Check Service Status With Timeout host_1 service_1 ${2} 60 HARD Should Be True ${result} Service (host_1,service_1) should be CRITICAL HARD + ${content} Create List SERVICE NOTIFICATION: John_Doe;host_1;service_1;CRITICAL;command_notif; Error: can't execute service notification for contact 'John_Doe' : it is not allowed by the whitelist + ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 60 + Should Be True ${result} No notification has been sent concerning a critical service + + Ctn Stop Engine + Ctn Kindly Stop Broker + +not2 + [Documentation] This test case configures a single service and verifies that a recovery notification is sent + [Tags] broker engine services hosts notification + Ctn Clear Commands Status + Ctn Config Engine ${1} ${1} ${1} + Ctn Config Notifications + Ctn Engine Config Set Value In Hosts 0 host_1 notifications_enabled 1 + Ctn Engine Config Set Value In Hosts 0 host_1 notification_options d,r + Ctn Engine Config Set Value In Hosts 0 host_1 contacts John_Doe + Ctn Engine Config Set Value In Services 0 service_1 contacts John_Doe + Ctn Engine Config Set Value In Services 0 service_1 notification_options w,c,r + Ctn Engine Config Set Value In Services 0 service_1 notifications_enabled 1 + Ctn Engine Config Set Value In Services 0 service_1 notification_period 24x7 + Ctn Engine Config Replace Value In Services 0 service_1 check_interval 1 + Ctn Engine Config Replace Value In Services 0 service_1 retry_interval 1 + Ctn Engine Config Set Value In Contacts 0 John_Doe host_notification_commands command_notif + Ctn Engine Config Set Value In Contacts 0 John_Doe service_notification_commands command_notif + + ${start} Get Current Date + Ctn Start Broker + Ctn Start Engine + + # Let's wait for the external command check start + Ctn Wait For Engine To Be Ready ${1} + + ${cmd_service_1} Ctn Get Service Command Id ${1} + Ctn Set Command Status ${cmd_service_1} ${2} + ## Time to set the service to CRITICAL HARD. + Ctn Process Service Result Hard host_1 service_1 ${2} The service_1 is CRITICAL + + ${result} Ctn Check Service Resource Status With Timeout host_1 service_1 ${2} 60 HARD + Should Be True ${result} Service (host_1,service_1) should be CRITICAL HARD + ${content} Create List SERVICE NOTIFICATION: John_Doe;host_1;service_1;CRITICAL;command_notif; ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 60 Should Be True ${result} No notification has been sent concerning a critical service ## Time to set the service to UP hard + ${start} Ctn Get Round Current Date - Ctn Set Command Status ${cmd_id} ${0} + Ctn Set Command Status ${cmd_service_1} ${0} Ctn Process Service Result Hard host_1 service_1 ${0} The service_1 is OK - ${result} Ctn Check Service Status With Timeout host_1 service_1 ${0} 60 HARD + ${result} Ctn Check Service Resource Status With Timeout host_1 service_1 ${0} 60 HARD Should Be True ${result} Service (host_1,service_1) should be OK HARD ${content} Create List SERVICE NOTIFICATION: John_Doe;host_1;service_1;RECOVERY (OK);command_notif; @@ -103,6 +196,7 @@ not2 not3 [Documentation] This test case configures a single service and verifies the notification system's behavior during and after downtime [Tags] broker engine services hosts notification + Ctn Clear Commands Status Ctn Config Engine ${1} ${1} ${1} Ctn Config Notifications Ctn Engine Config Set Value In Hosts 0 host_1 notifications_enabled 1 @@ -124,8 +218,8 @@ not3 # Let's wait for the external command check start Ctn Wait For Engine To Be Ready ${1} - ${cmd_id} Ctn Get Service Command Id ${1} - Ctn Set Command Status ${cmd_id} ${2} + ${cmd_service_1} Ctn Get Service Command Id ${1} + Ctn Set Command Status ${cmd_service_1} ${2} # It's time to schedule a downtime Ctn Schedule Service Fixed Downtime host_1 service_1 60 @@ -139,19 +233,19 @@ not3 ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 90 Should Be True ${result} The critical notification is sent while downtime + ${start} Ctn Get Round Current Date Ctn Delete Service Downtime host_1 service_1 - Sleep 10s - ${content} Create List SERVICE NOTIFICATION: John_Doe;host_1;service_1;CRITICAL;command_notif; ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 90 Should Be True ${result} The critical notification is not sent - Ctn Set Command Status ${cmd_id} ${0} + ${start} Ctn Get Round Current Date + Ctn Set Command Status ${cmd_service_1} ${0} Ctn Process Service Result Hard host_1 service_1 ${0} The service_1 is OK - ${result} Ctn Check Service Status With Timeout host_1 service_1 ${0} 60 HARD + ${result} Ctn Check Service Resource Status With Timeout host_1 service_1 ${0} 60 HARD Should Be True ${result} Service (host_1,service_1) should be OK HARD ${content} Create List SERVICE NOTIFICATION: John_Doe;host_1;service_1;RECOVERY (OK);command_notif; @@ -164,6 +258,7 @@ not3 not4 [Documentation] This test case configures a single service and verifies the notification system's behavior during and after acknowledgement [Tags] broker engine services acknowledgement notification + Ctn Clear Commands Status Ctn Config Engine ${1} ${1} ${1} Ctn Config Notifications Ctn Engine Config Set Value In Hosts 0 host_1 notifications_enabled 1 @@ -185,13 +280,13 @@ not4 # Let's wait for the external command check start Ctn Wait For Engine To Be Ready ${1} - ${cmd_id} Ctn Get Service Command Id ${1} - Ctn Set Command Status ${cmd_id} ${2} + ${cmd_service_1} Ctn Get Service Command Id ${1} + Ctn Set Command Status ${cmd_service_1} ${2} # Time to set the service to CRITICAL HARD. Ctn Process Service Result Hard host_1 service_1 ${2} The service_1 is CRITICAL - ${result} Ctn Check Service Status With Timeout host_1 service_1 ${2} 60 HARD + ${result} Ctn Check Service Resource Status With Timeout host_1 service_1 ${2} 60 HARD Should Be True ${result} Service (host_1,service_1) should be CRITICAL HARD # Acknowledge the service with critical status @@ -203,11 +298,12 @@ not4 Should Be True ${result} check_for_external_commands() should be available. # Time to set the service to OK HARD. - Ctn Set Command Status ${cmd_id} ${0} + ${start} Ctn Get Round Current Date + Ctn Set Command Status ${cmd_service_1} ${0} Ctn Process Service Result Hard host_1 service_1 ${0} The service_1 is OK - ${result} Ctn Check Service Status With Timeout host_1 service_1 ${0} 60 HARD + ${result} Ctn Check Service Resource Status With Timeout host_1 service_1 ${0} 60 HARD Should Be True ${result} Service (host_1,service_1) should be OK HARD ${content} Create List SERVICE NOTIFICATION: John_Doe;host_1;service_1;RECOVERY (OK);command_notif; @@ -220,6 +316,7 @@ not4 not5 [Documentation] This test case configures two services with two different users being notified when the services transition to a critical state. [Tags] broker engine services hosts notification + Ctn Clear Commands Status Ctn Config Engine ${1} ${2} ${1} Ctn Config Notifications Ctn Engine Config Set Value In Hosts 0 host_1 notifications_enabled 1 @@ -252,28 +349,28 @@ not5 # Let's wait for the external command check start Ctn Wait For Engine To Be Ready ${1} - ${cmd_id} Ctn Get Service Command Id ${1} - Ctn Set Command Status ${cmd_id} ${2} + ${cmd_service_1} Ctn Get Service Command Id ${1} + ${cmd_service_2} Ctn Get Service Command Id ${2} - ${cmd_id} Ctn Get Service Command Id ${2} - Ctn Set Command Status ${cmd_id} ${2} + Ctn Set Command Status ${cmd_service_1} ${2} + Ctn Set Command Status ${cmd_service_2} ${2} ## Time to set the services to CRITICAL HARD. Ctn Process Service Result Hard host_1 service_1 ${2} The service_1 is CRITICAL Ctn Process Service Result Hard host_2 service_2 ${2} The service_2 is CRITICAL - - ${result} Ctn Check Service Status With Timeout host_1 service_1 ${2} 70 HARD + + ${result} Ctn Check Service Resource Status With Timeout host_1 service_1 ${2} 70 HARD Should Be True ${result} Service (host_1,service_1) should be CRITICAL HARD - ${result} Ctn Check Service Status With Timeout host_2 service_2 ${2} 70 HARD + ${result} Ctn Check Service Resource Status With Timeout host_2 service_2 ${2} 70 HARD Should Be True ${result} Service (host_2,service_2) should be CRITICAL HARD - + # Notification for the first user john ${content} Create List SERVICE NOTIFICATION: John_Doe;host_1;service_1;CRITICAL;command_notif; ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 60 Should Be True ${result} The critical notification of service_1 is not sent - + # Notification for the second user U2 ${content} Create List SERVICE NOTIFICATION: U2;host_2;service_2;CRITICAL;command_notif; ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 60 @@ -285,6 +382,7 @@ not5 not6 [Documentation] This test case validate the behavior when the notification time period is set to null. [Tags] broker engine services hosts notification + Ctn Clear Commands Status Ctn Config Engine ${1} ${1} ${1} Ctn Config Notifications Ctn Engine Config Set Value In Hosts 0 host_1 notifications_enabled 1 @@ -306,13 +404,13 @@ not6 # Let's wait for the external command check start Ctn Wait For Engine To Be Ready ${1} - ${cmd_id} Ctn Get Service Command Id ${1} - Ctn Set Command Status ${cmd_id} ${2} + ${cmd_service_1} Ctn Get Service Command Id ${1} + Ctn Set Command Status ${cmd_service_1} ${2} ## Time to set the service to CRITICAL HARD. Ctn Process Service Result Hard host_1 service_1 ${2} The service_1 is CRITICAL - ${result} Ctn Check Service Status With Timeout host_1 service_1 ${2} 60 HARD + ${result} Ctn Check Service Resource Status With Timeout host_1 service_1 ${2} 60 HARD Should Be True ${result} Service (host_2,service_2) should be CRITICAL HARD ${content} Create List SERVICE NOTIFICATION: John_Doe;host_1;service_1;CRITICAL;command_notif; @@ -322,16 +420,16 @@ not6 Ctn Engine Config Replace Value In Services 0 service_1 notification_period none Sleep 5s - ${start} Get Current Date + ${start} Ctn Get Round Current Date Ctn Reload Broker Ctn Reload Engine ## Time to set the service to OK hard - Ctn Set Command Status ${cmd_id} ${0} + Ctn Set Command Status ${cmd_service_1} ${0} Ctn Process Service Result Hard host_1 service_1 ${0} The service_1 is OK - ${result} Ctn Check Service Status With Timeout host_1 service_1 ${0} 60 HARD + ${result} Ctn Check Service Resource Status With Timeout host_1 service_1 ${0} 60 HARD Should Be True ${result} Service (host_1,service_1) should be OK HARD ${content} Create List This notifier shouldn't have notifications sent out at this time @@ -344,6 +442,7 @@ not6 not7 [Documentation] This test case simulates a host alert scenario. [Tags] broker engine host notification + Ctn Clear Commands Status Ctn Config Engine ${1} ${1} Ctn Config Notifications Ctn Config Host Command Status ${0} checkh1 2 @@ -376,6 +475,7 @@ not7 not8 [Documentation] This test validates the critical host notification. [Tags] broker engine host notification + Ctn Clear Commands Status Ctn Config Engine ${1} ${1} Ctn Config Notifications Ctn Config Host Command Status ${0} checkh1 2 @@ -408,6 +508,7 @@ not8 not9 [Documentation] This test case configures a single host and verifies that a recovery notification is sent after the host recovers from a non-OK state. [Tags] broker engine host notification + Ctn Clear Commands Status Ctn Config Engine ${1} ${1} Ctn Config Notifications Ctn Config Host Command Status ${0} checkh1 2 @@ -423,7 +524,7 @@ not9 Ctn Start Engine Ctn Wait For Engine To Be Ready ${1} - + ## Time to set the host to CRITICAL HARD. FOR ${i} IN RANGE ${4} Ctn Schedule Forced Host Check host_1 ${VarRoot}/lib/centreon-engine/config0/rw/centengine.cmd @@ -435,6 +536,7 @@ not9 Should Be True ${result} The down notification of host_1 is not sent ## Time to set the host to UP HARD. + ${start} Ctn Get Round Current Date Ctn Process Host Check Result host_1 0 host_1 UP FOR ${i} IN RANGE ${4} @@ -450,8 +552,11 @@ not9 Ctn Kindly Stop Broker not10 - [Documentation] This test case involves scheduling downtime on a down host that already had a critical notification.When The Host return to UP state we should receive a recovery notification. + [Documentation] This test case involves scheduling downtime on a down host that already had + ... a critical notification. When The Host return to UP state we should receive a recovery + ... notification. [Tags] broker engine host notification + Ctn Clear Commands Status Ctn Config Engine ${1} ${1} ${1} Ctn Config Notifications Ctn Config Host Command Status ${0} checkh1 2 @@ -475,6 +580,9 @@ not10 END Ctn Schedule Host Downtime ${0} host_1 ${60} + ${content} Create List Notifications for the service will not be sent out during that time period. + ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 20 + Should Be True ${result} The downtime has not be sent. Ctn Process Host Check Result host_1 2 host_1 DOWN @@ -483,15 +591,18 @@ not10 Should Be True ${result} The down notification of host_1 is sent Ctn Delete Host Downtimes ${0} host_1 + ${content} Create List cmd_delete_downtime_full() args = host_1 + ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 20 + Should Be True ${result} Downtimes not removed in host_1 ## Time to set the host to UP HARD. - ${content} Create List HOST NOTIFICATION: John_Doe;host_1;DOWN;command_notif; ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 90 Should Be True ${result} The down notification of host_1 is not sent ## Time to set the host to UP HARD. - + ${start} Ctn Get Round Current Date + Ctn Process Host Check Result host_1 0 host_1 UP FOR ${i} IN RANGE ${4} @@ -508,10 +619,10 @@ not10 Ctn Stop Engine Ctn Kindly Stop Broker - not11 [Documentation] This test case involves configuring one service and checking that three alerts are sent for it. [Tags] broker engine services hosts notification + Ctn Clear Commands Status Ctn Config Engine ${1} ${1} ${1} Ctn Config Notifications Ctn Engine Config Set Value In Hosts 0 host_1 notifications_enabled 1 @@ -531,8 +642,8 @@ not11 # Let's wait for the external command check start Ctn Wait For Engine To Be Ready ${1} - ${cmd_id} Ctn Get Service Command Id ${1} - Ctn Set Command Status ${cmd_id} ${2} + ${cmd_service_1} Ctn Get Service Command Id ${1} + Ctn Set Command Status ${cmd_service_1} ${2} ## Time to set the service to CRITICAL HARD. @@ -540,7 +651,7 @@ not11 ${content} Create List SERVICE ALERT: host_1;service_1;CRITICAL;SOFT;1; ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 60 - Should Be True ${result} The first service alert SOFT1 is not sent + Should Be True ${result} The first service alert SOFT1 is not sent ${content} Create List SERVICE ALERT: host_1;service_1;CRITICAL;SOFT;2; ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 60 @@ -557,6 +668,7 @@ not11 not12 [Documentation] Escalations [Tags] broker engine services hosts notification + Ctn Clear Commands Status Ctn Config Engine ${1} ${2} ${1} Ctn Engine Config Set Value 0 interval_length 1 True Ctn Config Engine Add Cfg File ${0} servicegroups.cfg @@ -585,19 +697,18 @@ not12 # Let's wait for the external command check start Ctn Wait For Engine To Be Ready ${1} - ${cmd_id} Ctn Get Service Command Id ${1} - Ctn Set Command Status ${cmd_id} ${2} - - ${cmd_id} Ctn Get Service Command Id ${2} - Ctn Set Command Status ${cmd_id} ${2} + ${cmd_service_1} Ctn Get Service Command Id ${1} + ${cmd_service_2} Ctn Get Service Command Id ${2} + Ctn Set Command Status ${cmd_service_1} ${2} + Ctn Set Command Status ${cmd_service_2} ${2} Ctn Process Service Result Hard host_1 service_1 ${2} The service_1 is CRITICAL Ctn Process Service Result Hard host_2 service_2 ${2} The service_2 is CRITICAL - ${result} Ctn Check Service Status With Timeout host_1 service_1 ${2} 60 HARD + ${result} Ctn Check Service Resource Status With Timeout host_1 service_1 ${2} 60 HARD Should Be True ${result} Service (host_1,service_1) should be CRITICAL HARD - ${result} Ctn Check Service Status With Timeout host_2 service_2 ${2} 60 HARD + ${result} Ctn Check Service Resource Status With Timeout host_2 service_2 ${2} 60 HARD Should Be True ${result} Service (host_2,service_2) should be CRITICAL HARD # Let's wait for the first notification of the user U1 @@ -608,16 +719,15 @@ not12 ${content} Create List SERVICE NOTIFICATION: U1;host_2;service_2;CRITICAL;command_notif; ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 60 Should Be True ${result} The first notification of contact group 1 is not sent - - Ctn Set Command Status ${cmd_id} ${2} + ${start} Ctn Get Round Current Date Ctn Process Service Result Hard host_1 service_1 ${2} The service_1 is CRITICAL Ctn Process Service Result Hard host_2 service_2 ${2} The service_2 is CRITICAL - ${result} Ctn Check Service Status With Timeout host_1 service_1 ${2} 60 HARD + ${result} Ctn Check Service Resource Status With Timeout host_1 service_1 ${2} 60 HARD Should Be True ${result} Service (host_1,service_1) should be CRITICAL HARD - ${result} Ctn Check Service Status With Timeout host_2 service_2 ${2} 60 HARD + ${result} Ctn Check Service Resource Status With Timeout host_2 service_2 ${2} 60 HARD Should Be True ${result} Service (host_2,service_2) should be CRITICAL HARD # Let's wait for the first notification of the contact group 2 U3 ET U2 @@ -628,16 +738,14 @@ not12 ${content} Create List SERVICE NOTIFICATION: U3;host_1;service_1;CRITICAL;command_notif; ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 60 Should Be True ${result} The first notification of U3 is not sent - - Ctn Set Command Status ${cmd_id} ${2} Ctn Process Service Result Hard host_1 service_1 ${2} The service_1 is CRITICAL Ctn Process Service Result Hard host_2 service_2 ${2} The service_2 is CRITICAL - ${result} Ctn Check Service Status With Timeout host_1 service_1 ${2} 60 HARD + ${result} Ctn Check Service Resource Status With Timeout host_1 service_1 ${2} 60 HARD Should Be True ${result} Service (host_1,service_1) should be CRITICAL HARD - ${result} Ctn Check Service Status With Timeout host_2 service_2 ${2} 60 HARD + ${result} Ctn Check Service Resource Status With Timeout host_2 service_2 ${2} 60 HARD Should Be True ${result} Service (host_2,service_2) should be CRITICAL HARD # Let's wait for the second notification of the contact group 2 U3 ET U2 @@ -648,16 +756,15 @@ not12 ${content} Create List SERVICE NOTIFICATION: U3;host_2;service_2;CRITICAL;command_notif; ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 60 Should Be True ${result} The second notification of U3 is not sent - - Ctn Set Command Status ${cmd_id} ${2} + ${start} Ctn Get Round Current Date Ctn Process Service Result Hard host_1 service_1 ${2} The service_1 is CRITICAL Ctn Process Service Result Hard host_2 service_2 ${2} The service_1 is CRITICAL - ${result} Ctn Check Service Status With Timeout host_1 service_1 ${2} 60 HARD + ${result} Ctn Check Service Resource Status With Timeout host_1 service_1 ${2} 60 HARD Should Be True ${result} Service (host_1,service_1) should be CRITICAL HARD - ${result} Ctn Check Service Status With Timeout host_2 service_2 ${2} 60 HARD + ${result} Ctn Check Service Resource Status With Timeout host_2 service_2 ${2} 60 HARD Should Be True ${result} Service (host_2,service_2) should be CRITICAL HARD # Let's wait for the first notification of the contact group 3 U4 @@ -672,6 +779,7 @@ not12 not13 [Documentation] notification for a dependensies host [Tags] broker engine host unified_sql + Ctn Clear Commands Status Ctn Config Engine ${1} ${2} ${1} Ctn Config Notifications Ctn Config Engine Add Cfg File ${0} dependencies.cfg @@ -722,8 +830,8 @@ not13 ${content} Create List HOST NOTIFICATION: John_Doe;host_2;DOWN;command_notif; ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 60 Should Be True ${result} The down notification of host_2 is not sent - + ${start} Ctn Get Round Current Date Ctn Process Host Check Result host_2 0 host_2 UP FOR ${i} IN RANGE ${3} @@ -752,7 +860,7 @@ not13 Ctn Schedule Forced Host Check host_2 ${VarRoot}/lib/centreon-engine/config0/rw/centengine.cmd Sleep 5s END - + ${content} Create List This notifier won't send any notification since it depends on another notifier that has already sent one ${result} Ctn Find In Log With Timeout ${engineLog0} ${new_date} ${content} 60 Should Be True ${result} The down notification of host_2 is sent dependency not working @@ -774,6 +882,7 @@ not13 not14 [Documentation] notification for a Service dependency [Tags] broker engine services unified_sql + Ctn Clear Commands Status Ctn Config Engine ${1} ${2} ${1} Ctn Config Notifications Ctn Config Engine Add Cfg File ${0} dependencies.cfg @@ -808,14 +917,15 @@ not14 # Let's wait for the external command check start Ctn Wait For Engine To Be Ready ${1} - - ${cmd_id} Ctn Get Service Command Id ${2} - Ctn Set Command Status ${cmd_id} ${2} + + ${cmd_service_1} Ctn Get Service Command Id ${1} + ${cmd_service_2} Ctn Get Service Command Id ${2} + Ctn Set Command Status ${cmd_service_2} ${2} ## Time to set the service2 to CRITICAL HARD. Ctn Process Service Result Hard host_2 service_2 ${2} The service_2 is CRITICAL - ${result} Ctn Check Service Status With Timeout host_2 service_2 ${2} 60 HARD + ${result} Ctn Check Service Resource Status With Timeout host_2 service_2 ${2} 60 HARD Should Be True ${result} Service (host_2,service_2) should be CRITICAL HARD ${content} Create List SERVICE NOTIFICATION: John_Doe;host_2;service_2;CRITICAL;command_notif; @@ -823,12 +933,12 @@ not14 Should Be True ${result} The notification is not sent ## Time to set the service2 to OK hard - ${cmd_id} Ctn Get Service Command Id ${2} - Ctn Set Command Status ${cmd_id} ${0} + ${start} Ctn Get Round Current Date + Ctn Set Command Status ${cmd_service_2} ${0} Ctn Process Service Result Hard host_2 service_2 ${0} The service_2 is OK - ${result} Ctn Check Service Status With Timeout host_2 service_2 ${0} 60 HARD + ${result} Ctn Check Service Resource Status With Timeout host_2 service_2 ${0} 60 HARD Should Be True ${result} Service (host_2,service_2) should be OK HARD ${content} Create List SERVICE NOTIFICATION: John_Doe;host_2;service_2;RECOVERY (OK);command_notif; @@ -836,12 +946,12 @@ not14 Should Be True ${result} The notification is not sent ## Time to set the service1 to CRITICAL HARD. - ${cmd_id} Ctn Get Service Command Id ${1} - Ctn Set Command Status ${cmd_id} ${2} + ${start} Ctn Get Round Current Date + Ctn Set Command Status ${cmd_service_1} ${2} Ctn Process Service Result Hard host_1 service_1 ${2} The service_1 is CRITICAL - ${result} Ctn Check Service Status With Timeout host_1 service_1 ${2} 60 HARD + ${result} Ctn Check Service Resource Status With Timeout host_1 service_1 ${2} 60 HARD Should Be True ${result} Service (host_1,service_1) should be CRITICAL HARD ${content} Create List SERVICE NOTIFICATION: John_Doe;host_1;service_1;CRITICAL;command_notif; @@ -850,12 +960,11 @@ not14 ${new_date} Get Current Date ## Time to set the service2 to CRITICAL HARD. - ${cmd_id} Ctn Get Service Command Id ${2} - Ctn Set Command Status ${cmd_id} ${2} + Ctn Set Command Status ${cmd_service_2} ${2} Ctn Process Service Result Hard host_2 service_2 ${2} The service_2 is CRITICAL - ${result} Ctn Check Service Status With Timeout host_2 service_2 ${2} 60 HARD + ${result} Ctn Check Service Resource Status With Timeout host_2 service_2 ${2} 60 HARD Should Be True ${result} Service (host_2,service_2) should be CRITICAL HARD ${content} Create List This notifier won't send any notification since it depends on another notifier that has already sent one @@ -863,12 +972,11 @@ not14 Should Be True ${result} the dependency not working and the service_é has recieved a notification ## Time to set the service1 to OK hard - ${cmd_id} Ctn Get Service Command Id ${1} - Ctn Set Command Status ${cmd_id} ${0} + Ctn Set Command Status ${cmd_service_1} ${0} Ctn Process Service Result Hard host_1 service_1 ${0} The service_1 is OK - ${result} Ctn Check Service Status With Timeout host_1 service_1 ${0} 60 HARD + ${result} Ctn Check Service Resource Status With Timeout host_1 service_1 ${0} 60 HARD Should Be True ${result} Service (host_1,service_1) should be OK HARD ${content} Create List SERVICE NOTIFICATION: John_Doe;host_1;service_1;RECOVERY (OK);command_notif; @@ -882,6 +990,7 @@ not14 not15 [Documentation] several notification commands for the same user. [Tags] broker engine services unified_sql + Ctn Clear Commands Status Ctn Config Engine ${1} ${1} ${1} Ctn Config Notifications Ctn Engine Config Add Command @@ -905,15 +1014,15 @@ not15 # Let's wait for the external command check start Ctn Wait For Engine To Be Ready ${1} - - ${cmd_id} Ctn Get Service Command Id ${1} - Ctn Set Command Status ${cmd_id} ${2} + + ${cmd_service_1} Ctn Get Service Command Id ${1} + Ctn Set Command Status ${cmd_service_1} ${2} ## Time to set the service to CRITICAL HARD. Ctn Process Service Result Hard host_1 service_1 ${2} The service_1 is CRITICAL - ${result} Ctn Check Service Status With Timeout host_1 service_1 ${2} 60 HARD + ${result} Ctn Check Service Resource Status With Timeout host_1 service_1 ${2} 60 HARD Should Be True ${result} Service (host_1,service_1) should be CRITICAL HARD ${content} Create List SERVICE NOTIFICATION: John_Doe;host_1;service_1;CRITICAL;command_notif; @@ -930,6 +1039,7 @@ not15 not16 [Documentation] notification for a dependensies services group [Tags] broker engine services unified_sql + Ctn Clear Commands Status Ctn Config Engine ${1} ${4} ${1} Ctn Engine Config Set Value 0 interval_length 1 True Ctn Config Engine Add Cfg File ${0} servicegroups.cfg @@ -991,21 +1101,23 @@ not16 ## Time to set the service3 to CRITICAL HARD. - ${cmd_id} Ctn Get Service Command Id ${3} - Ctn Set Command Status ${cmd_id} ${0} + ${cmd_service_1} Ctn Get Service Command Id ${1} + ${cmd_service_3} Ctn Get Service Command Id ${3} + ${cmd_service_4} Ctn Get Service Command Id ${4} + + Ctn Set Command Status ${cmd_service_3} ${0} Ctn Process Service Result Hard host_3 service_3 ${0} The service_3 is OK - ${result} Ctn Check Service Status With Timeout host_3 service_3 ${0} 60 HARD + ${result} Ctn Check Service Resource Status With Timeout host_3 service_3 ${0} 60 HARD Should Be True ${result} Service (host_3,service_3) should be OK HARD - + ##Time to set the service3 to CRITICAL HARD. - ${cmd_id} Ctn Get Service Command Id ${3} - Ctn Set Command Status ${cmd_id} ${2} + Ctn Set Command Status ${cmd_service_3} ${2} Ctn Process Service Result Hard host_3 service_3 ${2} The service_3 is CRITICAL - ${result} Ctn Check Service Status With Timeout host_3 service_3 ${2} 60 HARD + ${result} Ctn Check Service Resource Status With Timeout host_3 service_3 ${2} 60 HARD Should Be True ${result} Service (host_3,service_3) should be CRITICAL HARD ${content} Create List SERVICE NOTIFICATION: John_Doe;host_3;service_3;CRITICAL;command_notif; @@ -1013,12 +1125,12 @@ not16 Should Be True ${result} The notification is not sent for service3 ## Time to set the service3 to OK hard - ${cmd_id} Ctn Get Service Command Id ${3} - Ctn Set Command Status ${cmd_id} ${0} + ${start} Ctn Get Round Current Date + Ctn Set Command Status ${cmd_service_3} ${0} Ctn Process Service Result Hard host_3 service_3 ${0} The service_3 is OK - ${result} Ctn Check Service Status With Timeout host_3 service_3 ${0} 60 HARD + ${result} Ctn Check Service Resource Status With Timeout host_3 service_3 ${0} 60 HARD Should Be True ${result} Service (host_3,service_3) should be OK HARD ${content} Create List SERVICE NOTIFICATION: John_Doe;host_3;service_3;RECOVERY (OK);command_notif; @@ -1026,11 +1138,11 @@ not16 Should Be True ${result} The notification is not sent for service3 ## Time to set the service1 to CRITICAL HARD. - ${cmd_id} Ctn Get Service Command Id ${1} - Ctn Set Command Status ${cmd_id} ${2} + ${start} Ctn Get Round Current Date + Ctn Set Command Status ${cmd_service_1} ${2} Ctn Process Service Result Hard host_1 service_1 ${2} The service_1 is CRITICAL - ${result} Ctn Check Service Status With Timeout host_1 service_1 ${2} 60 HARD + ${result} Ctn Check Service Resource Status With Timeout host_1 service_1 ${2} 60 HARD Should Be True ${result} Service (host_1,service_1) should be CRITICAL HARD ${content} Create List SERVICE NOTIFICATION: John_Doe;host_1;service_1;CRITICAL;command_notif; @@ -1038,12 +1150,12 @@ not16 Should Be True ${result} The notification is not sent for service1 ## Time to set the service3 to CRITICAL HARD. - ${cmd_id} Ctn Get Service Command Id ${3} - Ctn Set Command Status ${cmd_id} ${2} + ${start} Ctn Get Round Current Date + Ctn Set Command Status ${cmd_service_3} ${2} Ctn Process Service Result Hard host_3 service_3 ${2} The service_3 is CRITICAL - ${result} Ctn Check Service Status With Timeout host_3 service_3 ${2} 90 HARD + ${result} Ctn Check Service Resource Status With Timeout host_3 service_3 ${2} 90 HARD Should Be True ${result} Service (host_3,service_3) should be CRITICAL HARD ${content} Create List This notifier won't send any notification since it depends on another notifier that has already sent one @@ -1051,12 +1163,12 @@ not16 Should Be True ${result} The notification is sent for service3: dependency not working ## Time to set the service4 to CRITICAL HARD. - ${cmd_id} Ctn Get Service Command Id ${4} - Ctn Set Command Status ${cmd_id} ${2} + ${start} Ctn Get Round Current Date + Ctn Set Command Status ${cmd_service_4} ${2} Ctn Process Service Result Hard host_4 service_4 ${2} The service_4 is CRITICAL - ${result} Ctn Check Service Status With Timeout host_4 service_4 ${2} 60 HARD + ${result} Ctn Check Service Resource Status With Timeout host_4 service_4 ${2} 60 HARD Should Be True ${result} Service (host_4,service_4) should be CRITICAL HARD @@ -1065,12 +1177,12 @@ not16 Should Be True ${result} The notification is sent for service4: dependency not working ## Time to set the service1 to OK hard - ${cmd_id} Ctn Get Service Command Id ${1} - Ctn Set Command Status ${cmd_id} ${0} + ${start} Ctn Get Round Current Date + Ctn Set Command Status ${cmd_service_1} ${0} Ctn Process Service Result Hard host_1 service_1 ${0} The service_1 is OK - ${result} Ctn Check Service Status With Timeout host_1 service_1 ${0} 60 HARD + ${result} Ctn Check Service Resource Status With Timeout host_1 service_1 ${0} 60 HARD Should Be True ${result} Service (host_1,service_1) should be OK HARD @@ -1085,6 +1197,7 @@ not16 not17 [Documentation] notification for a dependensies host group [Tags] broker engine host unified_sql + Ctn Clear Commands Status Ctn Config Engine ${1} ${4} ${0} Ctn Engine Config Set Value 0 interval_length 10 True Ctn Add Host Group ${0} ${1} ["host_1", "host_2"] @@ -1138,6 +1251,7 @@ not17 ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 60 Should Be True ${result} The down notification of host_3 is not sent + ${start} Ctn Get Round Current Date FOR ${i} IN RANGE ${3} Ctn Process Host Check Result host_3 0 host_3 UP Sleep 1s @@ -1147,6 +1261,7 @@ not17 ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 60 Should Be True ${result} The recovery notification of host_3 is not sent + ${start} Ctn Get Round Current Date FOR ${i} IN RANGE ${3} Ctn Process Host Check Result host_1 1 host_1 DOWN Sleep 1s @@ -1161,7 +1276,7 @@ not17 Should Be True ${result} The down notification of host_1 is not sent ${new_date} Get Current Date - + ${content} Create List This notifier won't send any notification since it depends on another notifier that has already sent one ${result} Ctn Find In Log With Timeout ${engineLog0} ${new_date} ${content} 90 Should Be True ${result} The down notification of host_3 is sent dependency not working @@ -1190,6 +1305,7 @@ not17 not18 [Documentation] notification delay where first notification delay equal retry check [Tags] broker engine services hosts notification + Ctn Clear Commands Status Ctn Config Engine ${1} ${1} ${1} Ctn Engine Config Set Value 0 interval_length 1 True Ctn Config Notifications @@ -1214,12 +1330,12 @@ not18 # Let's wait for the external command check start Ctn Wait For Engine To Be Ready ${1} - ${cmd_id} Ctn Get Service Command Id ${1} - Ctn Set Command Status ${cmd_id} ${2} + ${cmd_service_1} Ctn Get Service Command Id ${1} + Ctn Set Command Status ${cmd_service_1} ${2} Ctn Process Service Result Hard host_1 service_1 ${2} The service_1 is CRITICAL - ${result} Ctn Check Service Status With Timeout host_1 service_1 ${2} 60 HARD + ${result} Ctn Check Service Resource Status With Timeout host_1 service_1 ${2} 60 HARD Should Be True ${result} Service (host_1,service_1) should be CRITICAL HARD ${content} Create List SERVICE NOTIFICATION: John_Doe;host_1;service_1;CRITICAL;command_notif; @@ -1232,6 +1348,7 @@ not18 not19 [Documentation] notification delay where first notification delay greater than retry check [Tags] broker engine services hosts notification + Ctn Clear Commands Status Ctn Config Engine ${1} ${1} ${1} Ctn Engine Config Set Value 0 interval_length 1 True Ctn Config Notifications @@ -1255,12 +1372,12 @@ not19 # Let's wait for the external command check start Ctn Wait For Engine To Be Ready ${1} - ${cmd_id} Ctn Get Service Command Id ${1} - Ctn Set Command Status ${cmd_id} ${2} + ${cmd_service_1} Ctn Get Service Command Id ${1} + Ctn Set Command Status ${cmd_service_1} ${2} Ctn Process Service Result Hard host_1 service_1 ${2} The service_1 is CRITICAL - ${result} Ctn Check Service Status With Timeout host_1 service_1 ${2} 60 HARD + ${result} Ctn Check Service Resource Status With Timeout host_1 service_1 ${2} 60 HARD Should Be True ${result} Service (host_1,service_1) should be CRITICAL HARD ${content} Create List SERVICE NOTIFICATION: John_Doe;host_1;service_1;CRITICAL;command_notif; @@ -1273,6 +1390,7 @@ not19 not20 [Documentation] notification delay where first notification delay samller than retry check [Tags] broker engine services hosts notification + Ctn Clear Commands Status Ctn Config Engine ${1} ${1} ${1} Ctn Engine Config Set Value 0 interval_length 1 True Ctn Config Notifications @@ -1296,12 +1414,12 @@ not20 # Let's wait for the external command check start Ctn Wait For Engine To Be Ready ${1} - ${cmd_id} Ctn Get Service Command Id ${1} - Ctn Set Command Status ${cmd_id} ${2} + ${cmd_service_1} Ctn Get Service Command Id ${1} + Ctn Set Command Status ${cmd_service_1} ${2} Ctn Process Service Result Hard host_1 service_1 ${2} The service_1 is CRITICAL - ${result} Ctn Check Service Status With Timeout host_1 service_1 ${2} 60 HARD + ${result} Ctn Check Service Resource Status With Timeout host_1 service_1 ${2} 60 HARD Should Be True ${result} Service (host_1,service_1) should be CRITICAL HARD ${content} Create List SERVICE NOTIFICATION: John_Doe;host_1;service_1;CRITICAL;command_notif; @@ -1314,6 +1432,7 @@ not20 not_in_timeperiod_without_send_recovery_notifications_anyways [Documentation] This test case configures a single service and verifies that a notification is sent when the service is in a non-OK state and OK is not sent outside timeperiod when _send_recovery_notifications_anyways is not set [Tags] MON-33121 broker engine services hosts notification + Ctn Clear Commands Status Ctn Config Engine ${1} ${1} ${1} Ctn Config Notifications Ctn Engine Config Set Value In Hosts 0 host_1 notifications_enabled 1 @@ -1341,7 +1460,7 @@ not_in_timeperiod_without_send_recovery_notifications_anyways ## Time to set the service to CRITICAL HARD. Ctn Process Service Result Hard host_1 service_1 2 critical - ${result} Ctn Check Service Status With Timeout host_1 service_1 ${2} 60 HARD + ${result} Ctn Check Service Resource Status With Timeout host_1 service_1 ${2} 60 HARD Should Be True ${result} Service (host_1,service_1) should be CRITICAL HARD ${content} Create List SERVICE NOTIFICATION: John_Doe;host_1;service_1;CRITICAL;command_notif;critical @@ -1359,6 +1478,7 @@ not_in_timeperiod_without_send_recovery_notifications_anyways not_in_timeperiod_with_send_recovery_notifications_anyways [Documentation] This test case configures a single service and verifies that a notification is sent when the service is in a non-OK state and OK is sent outside timeperiod when _send_recovery_notifications_anyways is set [Tags] MON-33121 broker engine services hosts notification mon-33121 + Ctn Clear Commands Status Ctn Config Engine ${1} ${1} ${1} Ctn Config Notifications Ctn Engine Config Set Value In Hosts 0 host_1 notifications_enabled 1 @@ -1388,7 +1508,7 @@ not_in_timeperiod_with_send_recovery_notifications_anyways ## Time to set the service to CRITICAL HARD. Ctn Process Service Result Hard host_1 service_1 2 critical - ${result} Ctn Check Service Status With Timeout host_1 service_1 ${2} 60 HARD + ${result} Ctn Check Service Resource Status With Timeout host_1 service_1 ${2} 60 HARD Should Be True ${result} Service (host_1,service_1) should be CRITICAL HARD ${content} Create List SERVICE NOTIFICATION: John_Doe;host_1;service_1;CRITICAL;command_notif;critical diff --git a/tests/broker-engine/whitelist.robot b/tests/broker-engine/whitelist.robot index 205f343da48..d2549ff8094 100644 --- a/tests/broker-engine/whitelist.robot +++ b/tests/broker-engine/whitelist.robot @@ -24,7 +24,7 @@ Whitelist_No_Whitelist_Directory Should Be True ${result} no whitelist directory found must be found in logs Whitelist_Empty_Directory - [Documentation] log if /etc/centreon-engine-whitelist if empty + [Documentation] log if /etc/centreon-engine-whitelist is empty [Tags] whitelist engine Ctn Config Engine ${1} ${50} ${20} Ctn Config Broker module ${1} @@ -42,7 +42,7 @@ Whitelist_Directory_Rights Ctn Config Engine ${1} ${50} ${20} Ctn Config Broker module ${1} Run chown root:root /etc/centreon-engine-whitelist - ${start} Get Current Date + ${start} Ctn Get Round Current Date Ctn Start engine ${content} Create List ... directory /etc/centreon-engine-whitelist must be owned by root@centreon-engine @@ -121,6 +121,61 @@ Whitelist_Host ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 60 Should Be True ${result} totozea not found +Whitelist_Service_EH + [Documentation] test allowed and forbidden event handler for services + [Tags] whitelist engine MON-75741 + Ctn Config Engine ${1} ${50} ${20} + Empty Directory /etc/centreon-engine-whitelist + Ctn Config Broker central + Ctn Config Broker module ${1} + Ctn Engine Config Set Value 0 log_level_checks trace True + Ctn Engine Config Set Value 0 log_level_commands trace True + # service_1 uses command_1 + Ctn Engine Config Replace Value In Services 0 service_1 check_command command_2 + Ctn Engine Config Change Command 0 1 /tmp/var/lib/centreon-engine/totozea 0 $HOSTADDRESS$ + Ctn Engine Config Set Value In Services 0 service_1 event_handler_enabled 1 + # command_1 poits to the command totozea that is not allowed. + Ctn Engine Config Set Value In Services 0 service_1 event_handler command_1 + + # create non matching file + ${whitelist_content} Catenate + ... {"whitelist":{"wildcard":["/tmp/var/lib/centreon-engine/check.pl * *"], "regex":["/tmp/var/lib/centreon-engine/check.pl [1-9] .*"]}} + Create File /etc/centreon-engine-whitelist/test ${whitelist_content} + ${start} Get Current Date + Ctn Start Broker only_central=${True} + Ctn Start engine + Ctn Wait For Engine To Be Ready ${start} ${1} + ${cmd} Ctn Get Service Command Id 1 + Ctn Set Command Status ${cmd} 0 + Ctn Process Service Result Hard host_1 service_1 0 output OK + #Repeat Keyword 3 times Ctn Schedule Forced Svc Check host_1 service_1 + Ctn Set Command Status ${cmd} 2 + Ctn Process Service Result Hard host_1 service_1 2 output CRITICAL + #Repeat Keyword 3 times Ctn Schedule Forced Svc Check host_1 service_1 + ${content} Create List + ... Error: can't execute service event handler command line '/tmp/var/lib/centreon-engine/totozea 0 1.0.0.0' : it is not allowed by the whitelist + ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 60 + Should Be True ${result} The event handler for service_1 should be forbidden to execute + + # Now, we allow totozea as event handler. + ${whitelist_content} Catenate + ... {"whitelist":{"wildcard":["/tmp/var/lib/centreon-engine/totozea * *"], "regex":["/tmp/var/lib/centreon-engine/check.pl [1-9] .*"]}} + Create File /etc/centreon-engine-whitelist/test ${whitelist_content} + Ctn Engine Config Change Command 0 1 /tmp/var/lib/centreon-engine/check.pl 1 $HOSTADDRESS$ + ${start} Ctn Get Round Current Date + Ctn Reload Engine + Ctn Wait For Engine To Be Ready ${start} ${1} + ${cmd} Ctn Get Service Command Id 1 + Ctn Set Command Status ${cmd} 0 + Ctn Process Service Result Hard host_1 service_1 0 output OK + #Repeat Keyword 3 times Ctn Schedule Forced Svc Check host_1 service_1 + Ctn Set Command Status ${cmd} 2 + Ctn Process Service Result Hard host_1 service_1 2 output CRITICAL + #Repeat Keyword 3 times Ctn Schedule Forced Svc Check host_1 service_1 + ${content} Create List SERVICE EVENT HANDLER: host_1;service_1;.*;command_1 my_system_r + ${result} Ctn Find Regex In Log With Timeout ${engineLog0} ${start} ${content} 60 + Should Be True ${result[0]} The event handler with command totozea should be OK. + Whitelist_Service [Documentation] test allowed and forbidden commands for services [Tags] whitelist engine diff --git a/tests/resources/Broker.py b/tests/resources/Broker.py index 71c439f1d2d..e9e629c335e 100755 --- a/tests/resources/Broker.py +++ b/tests/resources/Broker.py @@ -1,3 +1,24 @@ +#!/usr/bin/python3 +# +# Copyright 2023-2024 Centreon +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# For more information : contact@centreon.com +# +# This script is a little tcp server working on port 5669. It can simulate +# a cbd instance. It is useful to test the validity of BBDO packets sent by +# centengine. import signal from os import setsid from os import makedirs diff --git a/tests/resources/Common.py b/tests/resources/Common.py index 8f8699bbca2..2bce27f9bdc 100644 --- a/tests/resources/Common.py +++ b/tests/resources/Common.py @@ -1,3 +1,24 @@ +#!/usr/bin/python3 +# +# Copyright 2023-2024 Centreon +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# For more information : contact@centreon.com +# +# This script is a little tcp server working on port 5669. It can simulate +# a cbd instance. It is useful to test the validity of BBDO packets sent by +# centengine. from robot.api import logger from subprocess import getoutput, Popen, DEVNULL import re diff --git a/tests/resources/Engine.py b/tests/resources/Engine.py index f43cf9c0f44..39e63e33ead 100755 --- a/tests/resources/Engine.py +++ b/tests/resources/Engine.py @@ -1,3 +1,24 @@ +#!/usr/bin/python3 +# +# Copyright 2023-2024 Centreon +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# For more information : contact@centreon.com +# +# This script is a little tcp server working on port 5669. It can simulate +# a cbd instance. It is useful to test the validity of BBDO packets sent by +# centengine. import Common import grpc import math diff --git a/tests/resources/engine-scripts/check.pl b/tests/resources/engine-scripts/check.pl index 096a4b309ad..a00fd54a9bd 100755 --- a/tests/resources/engine-scripts/check.pl +++ b/tests/resources/engine-scripts/check.pl @@ -1,5 +1,24 @@ #!/usr/bin/perl - +# +# Copyright 2023-2024 Centreon +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# For more information : contact@centreon.com +# +# This script is a little tcp server working on port 5669. It can simulate +# a cbd instance. It is useful to test the validity of BBDO packets sent by +# centengine. use strict; use warnings; use Getopt::Long; @@ -37,9 +56,10 @@ else { if (open(FH, '<', "/tmp/states")) { while () { - if (/$id=>(.*)/) { + if (/^$id=>(.*)/) { $status = $1; chomp $status; + last; } } close FH; diff --git a/tests/robot.sh b/tests/robot.sh index fc011516259..5d57f507a34 100755 --- a/tests/robot.sh +++ b/tests/robot.sh @@ -1,5 +1,7 @@ #!/bin/bash +getent group centreon-engine || groupadd centreon-engine + sed -i -r 's/(\$\{DBUserRoot\}\s*)root_centreon/\1root/g' resources/db_variables.resource ulimit -c unlimited sysctl -w kernel.core_pattern=/tmp/core-%e.%p.%h.%t diff --git a/tests/update-doc.py b/tests/update-doc.py index 1335840e447..0e058e83913 100755 --- a/tests/update-doc.py +++ b/tests/update-doc.py @@ -1,4 +1,24 @@ #!/usr/bin/python3 +# +# Copyright 2023-2024 Centreon +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# For more information : contact@centreon.com +# +# This script is a little tcp server working on port 5669. It can simulate +# a cbd instance. It is useful to test the validity of BBDO packets sent by +# centengine. import os import re @@ -8,21 +28,32 @@ def complete_doc(dico, ff): content = f.readlines() f.close() r = re.compile(r"\s+\[Documentation]\s+(\S.*)$") + rd = re.compile(r"\s+\.\.\. \s*(.*)$") in_test = False + in_documentation = False test_name = "" - for l in content: + for line in content: + if in_documentation: + m = rd.match(line) + if m: + dico[test_name] += " " + m.group(1) + continue + else: + test_name = "" + in_documentation = False + if in_test: - if l.startswith("***"): + if line.startswith("***"): break - if len(test_name) != 0 and "[Documentation]" in l: - m = r.match(l) + if len(test_name) != 0 and "[Documentation]" in line: + m = r.match(line) if m: + in_documentation = True dico[test_name] = m.group(1) - test_name = "" - if not l.startswith('\t') and not l.startswith(" "): - test_name = l.strip() - elif l.startswith("*** Test Cases ***"): + if not line.startswith('\t') and not line.startswith(" "): + test_name = line.strip() + elif line.startswith("*** Test Cases ***"): in_test = True From fab83ebac4ac39a973174de7c80b364d0753b933 Mon Sep 17 00:00:00 2001 From: tuntoja <58987095+tuntoja@users.noreply.github.com> Date: Tue, 4 Jun 2024 12:00:44 +0200 Subject: [PATCH 19/60] enh(nightly): delay nightly to avoid heavy load on runners (#1396) --- .github/workflows/robot-nightly.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/robot-nightly.yml b/.github/workflows/robot-nightly.yml index 2e609cf9e4f..38836730e2e 100644 --- a/.github/workflows/robot-nightly.yml +++ b/.github/workflows/robot-nightly.yml @@ -8,7 +8,7 @@ concurrency: on: workflow_dispatch: schedule: - - cron: '0 0 * * *' + - cron: '30 0 * * *' jobs: dispatch-to-maintained-branches: From 8f4dda8d091b19e0dcae47c14ebbe98c0f104b81 Mon Sep 17 00:00:00 2001 From: David Boucher Date: Tue, 4 Jun 2024 13:43:23 +0200 Subject: [PATCH 20/60] enh(engine): extinfo removed (#1395) * enh(engine): no more hostextinfo/serviceextinfo REFS: MON-86794 --- .../engine/configuration/anomalydetection.hh | 41 +- .../configuration/applier/anomalydetection.hh | 38 +- .../engine/configuration/applier/command.hh | 38 +- .../engine/configuration/applier/connector.hh | 38 +- .../engine/configuration/applier/contact.hh | 38 +- .../configuration/applier/contactgroup.hh | 38 +- .../configuration/applier/difference.hh | 2 +- .../engine/configuration/applier/globals.hh | 39 +- .../engine/configuration/applier/logging.hh | 4 +- .../engine/configuration/applier/scheduler.hh | 2 +- .../applier/servicedependency.hh | 38 +- .../applier/serviceescalation.hh | 4 +- .../centreon/engine/configuration/command.hh | 2 +- .../engine/configuration/connector.hh | 2 +- .../centreon/engine/configuration/contact.hh | 39 +- .../engine/configuration/contactgroup.hh | 42 +- .../com/centreon/engine/configuration/host.hh | 4 +- .../engine/configuration/hostextinfo.hh | 94 ---- .../centreon/engine/configuration/parser.hh | 6 +- .../centreon/engine/configuration/service.hh | 4 +- .../engine/configuration/serviceextinfo.hh | 85 ---- engine/src/configuration/CMakeLists.txt | 2 - engine/src/configuration/anomalydetection.cc | 14 - .../src/configuration/applier/CMakeLists.txt | 37 +- .../configuration/applier/anomalydetection.cc | 25 +- engine/src/configuration/applier/connector.cc | 25 +- engine/src/configuration/applier/globals.cc | 35 +- engine/src/configuration/applier/logging.cc | 36 +- engine/src/configuration/applier/macros.cc | 35 +- .../applier/serviceescalation.cc | 19 - engine/src/configuration/command.cc | 36 +- engine/src/configuration/connector.cc | 36 +- engine/src/configuration/contactgroup.cc | 35 +- engine/src/configuration/group.cc | 35 +- engine/src/configuration/host.cc | 18 - engine/src/configuration/hostescalation.cc | 36 +- engine/src/configuration/hostextinfo.cc | 442 ------------------ engine/src/configuration/object.cc | 30 +- engine/src/configuration/parser.cc | 78 ---- engine/src/configuration/point_2d.cc | 36 +- engine/src/configuration/point_3d.cc | 36 +- engine/src/configuration/service.cc | 14 - engine/src/configuration/serviceextinfo.cc | 332 ------------- engine/src/configuration/servicegroup.cc | 35 +- engine/src/configuration/state.cc | 23 +- engine/src/configuration/timeperiod.cc | 36 +- 46 files changed, 479 insertions(+), 1605 deletions(-) delete mode 100644 engine/inc/com/centreon/engine/configuration/hostextinfo.hh delete mode 100644 engine/inc/com/centreon/engine/configuration/serviceextinfo.hh delete mode 100644 engine/src/configuration/hostextinfo.cc delete mode 100644 engine/src/configuration/serviceextinfo.cc diff --git a/engine/inc/com/centreon/engine/configuration/anomalydetection.hh b/engine/inc/com/centreon/engine/configuration/anomalydetection.hh index d73b2eb01b9..c797a20b8b6 100644 --- a/engine/inc/com/centreon/engine/configuration/anomalydetection.hh +++ b/engine/inc/com/centreon/engine/configuration/anomalydetection.hh @@ -1,22 +1,21 @@ -/* -** Copyright 2011-2013,2015-2017, 2022 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2013,2015-2017, 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCE_CONFIGURATION_ANOMALYDETECTION_HH #define CCE_CONFIGURATION_ANOMALYDETECTION_HH @@ -29,7 +28,6 @@ namespace com::centreon::engine { namespace configuration { -class serviceextinfo; class anomalydetection : public object { public: @@ -53,7 +51,6 @@ class anomalydetection : public object { bool operator<(anomalydetection const& other) const noexcept; void check_validity() const override; key_type key() const; - void merge(configuration::serviceextinfo const& obj); void merge(object const& obj) override; bool parse(char const* key, char const* value) override; @@ -243,6 +240,6 @@ typedef std::unordered_map, map_anomalydetection; } // namespace configuration -} +} // namespace com::centreon::engine #endif // !CCE_CONFIGURATION_ANOMALYDETECTION_HH diff --git a/engine/inc/com/centreon/engine/configuration/applier/anomalydetection.hh b/engine/inc/com/centreon/engine/configuration/applier/anomalydetection.hh index f8e9f1c615f..5cb2cc30522 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/anomalydetection.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/anomalydetection.hh @@ -1,21 +1,21 @@ -/* -** Copyright 2020 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ +/** + * Copyright 2020-2024 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #ifndef CCE_CONFIGURATION_APPLIER_ANOMALYDETECTION_HH #define CCE_CONFIGURATION_APPLIER_ANOMALYDETECTION_HH @@ -48,6 +48,6 @@ class anomalydetection { } // namespace applier } // namespace configuration -} +} // namespace com::centreon::engine #endif // !CCE_CONFIGURATION_APPLIER_ANOMALYDETECTION_HH diff --git a/engine/inc/com/centreon/engine/configuration/applier/command.hh b/engine/inc/com/centreon/engine/configuration/applier/command.hh index eda703e0a9d..8df1d47a62e 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/command.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/command.hh @@ -1,21 +1,21 @@ -/* -** Copyright 2011-2013,2017 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ +/** + * Copyright 2011-2013,2017,2023-2024 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #ifndef CCE_CONFIGURATION_APPLIER_COMMAND_HH #define CCE_CONFIGURATION_APPLIER_COMMAND_HH @@ -50,6 +50,6 @@ class command { } // namespace applier } // namespace configuration -} +} // namespace com::centreon::engine #endif // !CCE_CONFIGURATION_APPLIER_COMMAND_HH diff --git a/engine/inc/com/centreon/engine/configuration/applier/connector.hh b/engine/inc/com/centreon/engine/configuration/applier/connector.hh index f6fd9052736..e42892e53ff 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/connector.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/connector.hh @@ -1,21 +1,21 @@ -/* -** Copyright 2011-2013,2017 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ +/** + * Copyright 2011-2013,2017,2023 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #ifndef CCE_CONFIGURATION_APPLIER_CONNECTOR_HH #define CCE_CONFIGURATION_APPLIER_CONNECTOR_HH @@ -45,6 +45,6 @@ class connector { } // namespace applier } // namespace configuration -} +} // namespace com::centreon::engine #endif // !CCE_CONFIGURATION_APPLIER_CONNECTOR_HH diff --git a/engine/inc/com/centreon/engine/configuration/applier/contact.hh b/engine/inc/com/centreon/engine/configuration/applier/contact.hh index b0ee2bee892..17e2bb6ac78 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/contact.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/contact.hh @@ -1,21 +1,21 @@ -/* -** Copyright 2011-2013,2017 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ +/** + * Copyright 2011-2013,2017,2023 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #ifndef CCE_CONFIGURATION_APPLIER_CONTACT_HH #define CCE_CONFIGURATION_APPLIER_CONTACT_HH @@ -45,6 +45,6 @@ class contact { } // namespace applier } // namespace configuration -} +} // namespace com::centreon::engine #endif // !CCE_CONFIGURATION_APPLIER_CONTACT_HH diff --git a/engine/inc/com/centreon/engine/configuration/applier/contactgroup.hh b/engine/inc/com/centreon/engine/configuration/applier/contactgroup.hh index bc68b9a97c1..75e5fb6af7b 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/contactgroup.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/contactgroup.hh @@ -1,21 +1,21 @@ -/* -** Copyright 2011-2013,2017 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ +/** + * Copyright 2011-2013,2017,2023 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #ifndef CCE_CONFIGURATION_APPLIER_CONTACTGROUP_HH #define CCE_CONFIGURATION_APPLIER_CONTACTGROUP_HH @@ -54,6 +54,6 @@ class contactgroup { } // namespace applier } // namespace configuration -} +} // namespace com::centreon::engine #endif // !CCE_CONFIGURATION_APPLIER_CONTACTGROUP_HH diff --git a/engine/inc/com/centreon/engine/configuration/applier/difference.hh b/engine/inc/com/centreon/engine/configuration/applier/difference.hh index 4d56e54bd26..b451367406a 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/difference.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/difference.hh @@ -85,6 +85,6 @@ class difference { } // namespace applier } // namespace configuration -} +} // namespace com::centreon::engine #endif // !CCE_CONFIGURATION_APPLIER_DIFFERENCE_HH diff --git a/engine/inc/com/centreon/engine/configuration/applier/globals.hh b/engine/inc/com/centreon/engine/configuration/applier/globals.hh index ae9174b4e82..2448c41c05f 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/globals.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/globals.hh @@ -1,21 +1,22 @@ -/* -** Copyright 2011-2013 Merethis -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ +/** + * Copyright 2011-2013 Merethis + * Copyright 2014-2024 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #ifndef CCE_CONFIGURATION_APPLIER_GLOBALS_HH #define CCE_CONFIGURATION_APPLIER_GLOBALS_HH @@ -48,6 +49,6 @@ class globals { } // namespace applier } // namespace configuration -} +} // namespace com::centreon::engine #endif // !CCE_CONFIGURATION_APPLIER_GLOBALS_HH diff --git a/engine/inc/com/centreon/engine/configuration/applier/logging.hh b/engine/inc/com/centreon/engine/configuration/applier/logging.hh index 2d1391ba806..bfaf1dd3980 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/logging.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/logging.hh @@ -58,7 +58,7 @@ class logging { void _del_stderr(); com::centreon::logging::file* _debug; - unsigned long long _debug_level; + int64_t _debug_level; unsigned long _debug_max_size; unsigned int _debug_verbosity; com::centreon::logging::file* _log; @@ -69,6 +69,6 @@ class logging { } // namespace applier } // namespace configuration -} +} // namespace com::centreon::engine #endif // !CCE_CONFIGURATION_APPLIER_LOGGING_HH diff --git a/engine/inc/com/centreon/engine/configuration/applier/scheduler.hh b/engine/inc/com/centreon/engine/configuration/applier/scheduler.hh index b22a7d82845..557a36442ef 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/scheduler.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/scheduler.hh @@ -112,6 +112,6 @@ class scheduler { } // namespace applier } // namespace configuration -} +} // namespace com::centreon::engine #endif // !CCE_CONFIGURATION_APPLIER_SCHEDULER_HH diff --git a/engine/inc/com/centreon/engine/configuration/applier/servicedependency.hh b/engine/inc/com/centreon/engine/configuration/applier/servicedependency.hh index b0cf0c7054a..915817f634e 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/servicedependency.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/servicedependency.hh @@ -1,21 +1,21 @@ -/* -** Copyright 2011-2013,2017 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ +/** + * Copyright 2011-2013,2017 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #ifndef CCE_CONFIGURATION_APPLIER_SERVICEDEPENDENCY_HH #define CCE_CONFIGURATION_APPLIER_SERVICEDEPENDENCY_HH @@ -52,6 +52,6 @@ class servicedependency { } // namespace applier } // namespace configuration -} +} // namespace com::centreon::engine #endif // !CCE_CONFIGURATION_APPLIER_SERVICEDEPENDENCY_HH diff --git a/engine/inc/com/centreon/engine/configuration/applier/serviceescalation.hh b/engine/inc/com/centreon/engine/configuration/applier/serviceescalation.hh index 611e498d3e4..c437ee34089 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/serviceescalation.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/serviceescalation.hh @@ -1,5 +1,5 @@ /* -** Copyright 2011-2013,2017 Centreon +** Copyright 2011-2013,2017,2023 Centreon ** ** This file is part of Centreon Engine. ** @@ -54,6 +54,6 @@ class serviceescalation { } // namespace applier } // namespace configuration -} +} // namespace com::centreon::engine #endif // !CCE_CONFIGURATION_APPLIER_SERVICEESCALATION_HH diff --git a/engine/inc/com/centreon/engine/configuration/command.hh b/engine/inc/com/centreon/engine/configuration/command.hh index 71a3befb715..9702d7db9fe 100644 --- a/engine/inc/com/centreon/engine/configuration/command.hh +++ b/engine/inc/com/centreon/engine/configuration/command.hh @@ -62,6 +62,6 @@ typedef std::shared_ptr command_ptr; typedef std::set set_command; } // namespace configuration -} +} // namespace com::centreon::engine #endif // !CCE_CONFIGURATION_COMMAND_HH diff --git a/engine/inc/com/centreon/engine/configuration/connector.hh b/engine/inc/com/centreon/engine/configuration/connector.hh index 90a91bd343c..98c6129d172 100644 --- a/engine/inc/com/centreon/engine/configuration/connector.hh +++ b/engine/inc/com/centreon/engine/configuration/connector.hh @@ -60,6 +60,6 @@ typedef std::shared_ptr connector_ptr; typedef std::set set_connector; } // namespace configuration -} +} // namespace com::centreon::engine #endif // !CCE_CONFIGURATION_CONNECTOR_HH diff --git a/engine/inc/com/centreon/engine/configuration/contact.hh b/engine/inc/com/centreon/engine/configuration/contact.hh index 3698dd730e0..615181876f7 100644 --- a/engine/inc/com/centreon/engine/configuration/contact.hh +++ b/engine/inc/com/centreon/engine/configuration/contact.hh @@ -1,22 +1,21 @@ -/* -** Copyright 2011-2013,2015,2017 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2013,2015,2017-2024 Centreon (https://www.centreon.com/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCE_CONFIGURATION_CONTACT_HH #define CCE_CONFIGURATION_CONTACT_HH @@ -118,6 +117,6 @@ typedef std::shared_ptr contact_ptr; typedef std::set set_contact; } // namespace configuration -} +} // namespace com::centreon::engine #endif // !CCE_CONFIGURATION_CONTACT_HH diff --git a/engine/inc/com/centreon/engine/configuration/contactgroup.hh b/engine/inc/com/centreon/engine/configuration/contactgroup.hh index a87416ff626..2fb472697c8 100644 --- a/engine/inc/com/centreon/engine/configuration/contactgroup.hh +++ b/engine/inc/com/centreon/engine/configuration/contactgroup.hh @@ -1,21 +1,21 @@ -/* -** Copyright 2011-2013,2017 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ +/** + * Copyright 2011-2013,2017 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #ifndef CCE_CONFIGURATION_CONTACTGROUP_HH #define CCE_CONFIGURATION_CONTACTGROUP_HH @@ -24,9 +24,8 @@ #include "com/centreon/engine/configuration/object.hh" #include "com/centreon/engine/opt.hh" -namespace com::centreon::engine { +namespace com::centreon::engine::configuration { -namespace configuration { class contactgroup : public object { public: typedef std::string key_type; @@ -67,8 +66,7 @@ class contactgroup : public object { typedef std::shared_ptr contactgroup_ptr; typedef std::set set_contactgroup; -} // namespace configuration -} +} // namespace com::centreon::engine::configuration #endif // !CCE_CONFIGURATION_CONTACTGROUP_HH diff --git a/engine/inc/com/centreon/engine/configuration/host.hh b/engine/inc/com/centreon/engine/configuration/host.hh index bf2847a620f..93f831ad357 100644 --- a/engine/inc/com/centreon/engine/configuration/host.hh +++ b/engine/inc/com/centreon/engine/configuration/host.hh @@ -31,7 +31,6 @@ namespace com::centreon::engine { namespace configuration { -class hostextinfo; class host : public object { public: @@ -53,7 +52,6 @@ class host : public object { bool operator<(host const& other) const noexcept; void check_validity() const override; key_type key() const noexcept; - void merge(configuration::hostextinfo const& obj); void merge(object const& obj) override; bool parse(char const* key, char const* value) override; @@ -230,6 +228,6 @@ typedef std::list list_host; typedef std::set set_host; } // namespace configuration -} +} // namespace com::centreon::engine #endif // !CCE_CONFIGURATION_HOST_HH diff --git a/engine/inc/com/centreon/engine/configuration/hostextinfo.hh b/engine/inc/com/centreon/engine/configuration/hostextinfo.hh deleted file mode 100644 index c7e09c417ad..00000000000 --- a/engine/inc/com/centreon/engine/configuration/hostextinfo.hh +++ /dev/null @@ -1,94 +0,0 @@ -/* -** Copyright 2011-2013,2017 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - -#ifndef CCE_CONFIGURATION_HOSTEXTINFO_HH -#define CCE_CONFIGURATION_HOSTEXTINFO_HH - -#include "com/centreon/engine/configuration/group.hh" -#include "com/centreon/engine/configuration/object.hh" -#include "com/centreon/engine/configuration/point_2d.hh" -#include "com/centreon/engine/configuration/point_3d.hh" -#include "com/centreon/engine/opt.hh" - -namespace com::centreon::engine { - -namespace configuration { -class host; -class hostextinfo : public object { - friend class host; - - public: - hostextinfo(); - hostextinfo(hostextinfo const& right); - ~hostextinfo() throw() override; - hostextinfo& operator=(hostextinfo const& right); - bool operator==(hostextinfo const& right) const throw(); - bool operator!=(hostextinfo const& right) const throw(); - void check_validity() const override; - void merge(object const& obj) override; - bool parse(char const* key, char const* value) override; - - std::string const& action_url() const throw(); - point_2d const& coords_2d() const throw(); - point_3d const& coords_3d() const throw(); - set_string const& hostgroups() const throw(); - set_string const& hosts() const throw(); - std::string const& icon_image() const throw(); - std::string const& icon_image_alt() const throw(); - std::string const& notes() const throw(); - std::string const& notes_url() const throw(); - std::string const& statusmap_image() const throw(); - std::string const& vrml_image() const throw(); - - private: - typedef bool (*setter_func)(hostextinfo&, char const*); - - bool _set_action_url(std::string const& value); - bool _set_coords_2d(std::string const& value); - bool _set_coords_3d(std::string const& value); - bool _set_hostgroups(std::string const& value); - bool _set_hosts(std::string const& value); - bool _set_icon_image(std::string const& value); - bool _set_icon_image_alt(std::string const& value); - bool _set_notes(std::string const& value); - bool _set_notes_url(std::string const& value); - bool _set_statusmap_image(std::string const& value); - bool _set_vrml_image(std::string const& value); - - std::string _action_url; - opt _coords_2d; - opt _coords_3d; - group _hostgroups; - group _hosts; - std::string _icon_image; - std::string _icon_image_alt; - std::string _notes; - std::string _notes_url; - static std::unordered_map const _setters; - std::string _statusmap_image; - std::string _vrml_image; -}; - -typedef std::shared_ptr hostextinfo_ptr; -typedef std::list list_hostextinfo; -} // namespace configuration - -} - -#endif // !CCE_CONFIGURATION_HOSTEXTINFO_HH diff --git a/engine/inc/com/centreon/engine/configuration/parser.hh b/engine/inc/com/centreon/engine/configuration/parser.hh index 4c6e37ce7d5..be6652587cc 100644 --- a/engine/inc/com/centreon/engine/configuration/parser.hh +++ b/engine/inc/com/centreon/engine/configuration/parser.hh @@ -28,12 +28,10 @@ #include "com/centreon/engine/configuration/host.hh" #include "com/centreon/engine/configuration/hostdependency.hh" #include "com/centreon/engine/configuration/hostescalation.hh" -#include "com/centreon/engine/configuration/hostextinfo.hh" #include "com/centreon/engine/configuration/object.hh" #include "com/centreon/engine/configuration/service.hh" #include "com/centreon/engine/configuration/servicedependency.hh" #include "com/centreon/engine/configuration/serviceescalation.hh" -#include "com/centreon/engine/configuration/serviceextinfo.hh" #include "com/centreon/engine/configuration/state.hh" #include "com/centreon/engine/configuration/timeperiod.hh" @@ -75,8 +73,6 @@ class parser { void _add_template(object_ptr obj); void _apply(std::list const& lst, void (parser::*pfunc)(std::string const&)); - void _apply_hostextinfo(); - void _apply_serviceextinfo(); file_info const& _get_file_info(object* obj) const; void _get_hosts_by_hostgroups(hostgroup const& hostgroups, list_host& hosts); void _get_hosts_by_hostgroups_name(set_string const& lst_group, @@ -112,6 +108,6 @@ class parser { }; } // namespace configuration -} +} // namespace com::centreon::engine #endif // !CCE_CONFIGURATION_PARSER_HH diff --git a/engine/inc/com/centreon/engine/configuration/service.hh b/engine/inc/com/centreon/engine/configuration/service.hh index a8463180545..49fc7bd5853 100644 --- a/engine/inc/com/centreon/engine/configuration/service.hh +++ b/engine/inc/com/centreon/engine/configuration/service.hh @@ -29,7 +29,6 @@ namespace com::centreon::engine { namespace configuration { -class serviceextinfo; class service : public object { public: @@ -52,7 +51,6 @@ class service : public object { bool operator<(service const& other) const noexcept; void check_validity() const override; key_type key() const; - void merge(configuration::serviceextinfo const& obj); void merge(object const& obj) override; bool parse(char const* key, char const* value) override; @@ -235,6 +233,6 @@ typedef std::unordered_map, service_ptr> map_service; } // namespace configuration -} +} // namespace com::centreon::engine #endif // !CCE_CONFIGURATION_SERVICE_HH diff --git a/engine/inc/com/centreon/engine/configuration/serviceextinfo.hh b/engine/inc/com/centreon/engine/configuration/serviceextinfo.hh deleted file mode 100644 index e3495c437ed..00000000000 --- a/engine/inc/com/centreon/engine/configuration/serviceextinfo.hh +++ /dev/null @@ -1,85 +0,0 @@ -/* -** Copyright 2011-2013,2017 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - -#ifndef CCE_CONFIGURATION_SERVICEEXTINFO_HH -#define CCE_CONFIGURATION_SERVICEEXTINFO_HH - -#include "com/centreon/engine/configuration/group.hh" -#include "com/centreon/engine/configuration/object.hh" -#include "com/centreon/engine/opt.hh" - -namespace com::centreon::engine { - -namespace configuration { -class service; - -class serviceextinfo : public object { - friend class service; - friend class anomalydetection; - - public: - serviceextinfo(); - serviceextinfo(serviceextinfo const& right); - ~serviceextinfo() throw() override; - serviceextinfo& operator=(serviceextinfo const& right); - bool operator==(serviceextinfo const& right) const throw(); - bool operator!=(serviceextinfo const& right) const throw(); - void check_validity() const override; - void merge(object const& obj) override; - bool parse(char const* key, char const* value) override; - - std::string const& action_url() const throw(); - std::string const& icon_image() const throw(); - std::string const& icon_image_alt() const throw(); - set_string const& hostgroups() const throw(); - set_string const& hosts() const throw(); - std::string const& notes() const throw(); - std::string const& notes_url() const throw(); - std::string const& service_description() const throw(); - - private: - typedef bool (*setter_func)(serviceextinfo&, char const*); - - bool _set_action_url(std::string const& value); - bool _set_icon_image(std::string const& value); - bool _set_icon_image_alt(std::string const& value); - bool _set_hosts(std::string const& value); - bool _set_hostgroups(std::string const& value); - bool _set_notes(std::string const& value); - bool _set_notes_url(std::string const& value); - bool _set_service_description(std::string const& value); - - std::string _action_url; - std::string _icon_image; - std::string _icon_image_alt; - group _hostgroups; - group _hosts; - std::string _notes; - std::string _notes_url; - std::string _service_description; - static std::unordered_map const _setters; -}; - -typedef std::shared_ptr serviceextinfo_ptr; -typedef std::list list_serviceextinfo; -} // namespace configuration - -} - -#endif // !CCE_CONFIGURATION_SERVICEEXTINFO_HH diff --git a/engine/src/configuration/CMakeLists.txt b/engine/src/configuration/CMakeLists.txt index d4adc8d11fc..b0bd8910f26 100644 --- a/engine/src/configuration/CMakeLists.txt +++ b/engine/src/configuration/CMakeLists.txt @@ -37,7 +37,6 @@ set(FILES "${SRC_DIR}/host.cc" "${SRC_DIR}/hostdependency.cc" "${SRC_DIR}/hostescalation.cc" - "${SRC_DIR}/hostextinfo.cc" "${SRC_DIR}/hostgroup.cc" "${SRC_DIR}/object.cc" "${SRC_DIR}/parser.cc" @@ -47,7 +46,6 @@ set(FILES "${SRC_DIR}/service.cc" "${SRC_DIR}/servicedependency.cc" "${SRC_DIR}/serviceescalation.cc" - "${SRC_DIR}/serviceextinfo.cc" "${SRC_DIR}/servicegroup.cc" "${SRC_DIR}/severity.cc" "${SRC_DIR}/tag.cc" diff --git a/engine/src/configuration/anomalydetection.cc b/engine/src/configuration/anomalydetection.cc index df58470b648..7ccf1724b99 100644 --- a/engine/src/configuration/anomalydetection.cc +++ b/engine/src/configuration/anomalydetection.cc @@ -21,7 +21,6 @@ #include #include #include -#include "com/centreon/engine/configuration/serviceextinfo.hh" #include "com/centreon/engine/customvariable.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" @@ -920,19 +919,6 @@ anomalydetection::key_type anomalydetection::key() const { return k; } -/** - * Merge object. - * - * @param[in] obj The object to merge. - */ -void anomalydetection::merge(configuration::serviceextinfo const& tmpl) { - MRG_DEFAULT(_action_url); - MRG_DEFAULT(_icon_image); - MRG_DEFAULT(_icon_image_alt); - MRG_DEFAULT(_notes); - MRG_DEFAULT(_notes_url); -} - /** * Merge object. * diff --git a/engine/src/configuration/applier/CMakeLists.txt b/engine/src/configuration/applier/CMakeLists.txt index 541986bfb07..e7279860aab 100644 --- a/engine/src/configuration/applier/CMakeLists.txt +++ b/engine/src/configuration/applier/CMakeLists.txt @@ -1,22 +1,21 @@ -## -## Copyright 2011-2013 Merethis -## -## This file is part of Centreon Engine. -## -## Centreon Engine is free software: you can redistribute it and/or -## modify it under the terms of the GNU General Public License version 2 -## as published by the Free Software Foundation. -## -## Centreon Engine is distributed in the hope that it will be useful, -## but WITHOUT ANY WARRANTY; without even the implied warranty of -## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -## General Public License for more details. -## -## You should have received a copy of the GNU General Public License -## along with Centreon Engine. If not, see -## . -## - +# +# Copyright 2011-2013 Merethis +# Copyright 2014,2017-2024 Centreon +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# For more information : contact@centreon.com +# # Set directories. set(SRC_DIR "${SRC_DIR}/applier") set(INC_DIR "${INC_DIR}/applier") diff --git a/engine/src/configuration/applier/anomalydetection.cc b/engine/src/configuration/applier/anomalydetection.cc index 7050832c5a2..ac3b8ac926f 100644 --- a/engine/src/configuration/applier/anomalydetection.cc +++ b/engine/src/configuration/applier/anomalydetection.cc @@ -1,22 +1,21 @@ /** - * Copyright 2020 Centreon + * Copyright 2020-2024 Centreon * - * This file is part of Centreon Engine. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Centreon Engine is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License version 2 - * as published by the Free Software Foundation. + * http://www.apache.org/licenses/LICENSE-2.0 * - * Centreon Engine is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com * - * You should have received a copy of the GNU General Public License - * along with Centreon Engine. If not, see - * . */ - #include "com/centreon/engine/configuration/applier/anomalydetection.hh" #include "com/centreon/engine/anomalydetection.hh" #include "com/centreon/engine/broker.hh" diff --git a/engine/src/configuration/applier/connector.cc b/engine/src/configuration/applier/connector.cc index 3b075341e3c..0734f526538 100644 --- a/engine/src/configuration/applier/connector.cc +++ b/engine/src/configuration/applier/connector.cc @@ -1,22 +1,21 @@ /** - * Copyright 2011-2013,2017 Centreon + * Copyright 2011-2013,2017-2024 Centreon * - * This file is part of Centreon Engine. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Centreon Engine is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License version 2 - * as published by the Free Software Foundation. + * http://www.apache.org/licenses/LICENSE-2.0 * - * Centreon Engine is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com * - * You should have received a copy of the GNU General Public License - * along with Centreon Engine. If not, see - * . */ - #include "com/centreon/engine/commands/connector.hh" #include "com/centreon/engine/checks/checker.hh" #include "com/centreon/engine/configuration/applier/connector.hh" diff --git a/engine/src/configuration/applier/globals.cc b/engine/src/configuration/applier/globals.cc index 71bc0ef5f68..fc256c6617b 100644 --- a/engine/src/configuration/applier/globals.cc +++ b/engine/src/configuration/applier/globals.cc @@ -1,22 +1,21 @@ /** -* Copyright 2011-2013,2015,2018,2019 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ - + * Copyright 2011-2013,2015,2018,2019-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include "com/centreon/engine/configuration/applier/globals.hh" #include "com/centreon/engine/globals.hh" diff --git a/engine/src/configuration/applier/logging.cc b/engine/src/configuration/applier/logging.cc index 0da587efcb3..40a77191f82 100644 --- a/engine/src/configuration/applier/logging.cc +++ b/engine/src/configuration/applier/logging.cc @@ -1,22 +1,22 @@ /** -* Copyright 2011-2014,2018 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ - + * Copyright 2011-2014,2018-2024 Centreon + * Copyright 2011-2014,2017-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include "com/centreon/engine/configuration/applier/logging.hh" #include #include diff --git a/engine/src/configuration/applier/macros.cc b/engine/src/configuration/applier/macros.cc index 07236fa25fc..18275987d59 100644 --- a/engine/src/configuration/applier/macros.cc +++ b/engine/src/configuration/applier/macros.cc @@ -1,22 +1,21 @@ /** -* Copyright 2011-2013,2016 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ - + * Copyright 2011-2013,2016-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include "com/centreon/engine/configuration/applier/macros.hh" #include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/exceptions/error.hh" diff --git a/engine/src/configuration/applier/serviceescalation.cc b/engine/src/configuration/applier/serviceescalation.cc index 1cf4309b7e7..e5f46604e0e 100644 --- a/engine/src/configuration/applier/serviceescalation.cc +++ b/engine/src/configuration/applier/serviceescalation.cc @@ -16,25 +16,6 @@ * For more information : contact@centreon.com * */ - -/** - * - * This file is part of Centreon Engine. - * - * Centreon Engine is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License version 2 - * as published by the Free Software Foundation. - * - * Centreon Engine is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Centreon Engine. If not, see - * . - */ - #include "com/centreon/engine/configuration/applier/serviceescalation.hh" #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/config.hh" diff --git a/engine/src/configuration/command.cc b/engine/src/configuration/command.cc index 51c0a2f6dd2..6258d974196 100644 --- a/engine/src/configuration/command.cc +++ b/engine/src/configuration/command.cc @@ -1,22 +1,22 @@ /** -* Copyright 2011-2013 Merethis -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ - + * Copyright 2011-2013 Merethis + * Copyright 2017-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include "com/centreon/engine/configuration/command.hh" #include "com/centreon/engine/exceptions/error.hh" diff --git a/engine/src/configuration/connector.cc b/engine/src/configuration/connector.cc index bc9a1821474..1e3b83d920f 100644 --- a/engine/src/configuration/connector.cc +++ b/engine/src/configuration/connector.cc @@ -1,22 +1,22 @@ /** -* Copyright 2011-2013 Merethis -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ - + * Copyright 2011-2013 Merethis + * Copyright 2017-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include "com/centreon/engine/configuration/connector.hh" #include "com/centreon/engine/checks/checker.hh" #include "com/centreon/engine/exceptions/error.hh" diff --git a/engine/src/configuration/contactgroup.cc b/engine/src/configuration/contactgroup.cc index 545819f324f..9bad91e0cf5 100644 --- a/engine/src/configuration/contactgroup.cc +++ b/engine/src/configuration/contactgroup.cc @@ -1,22 +1,21 @@ /** -* Copyright 2011-2013,2017 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ - + * Copyright 2011-2013,2017-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include "com/centreon/engine/configuration/contactgroup.hh" #include "com/centreon/engine/exceptions/error.hh" diff --git a/engine/src/configuration/group.cc b/engine/src/configuration/group.cc index 22620900008..03a19046b06 100644 --- a/engine/src/configuration/group.cc +++ b/engine/src/configuration/group.cc @@ -1,22 +1,21 @@ /** -* Copyright 2011-2013,2017 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ - + * Copyright 2011-2013,2017-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include "com/centreon/engine/configuration/group.hh" #include "com/centreon/engine/string.hh" diff --git a/engine/src/configuration/host.cc b/engine/src/configuration/host.cc index 43b0cdb6ef5..57870514bd5 100644 --- a/engine/src/configuration/host.cc +++ b/engine/src/configuration/host.cc @@ -22,7 +22,6 @@ #include "absl/strings/numbers.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" -#include "com/centreon/engine/configuration/hostextinfo.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" #include "com/centreon/engine/host.hh" @@ -451,23 +450,6 @@ host::key_type host::key() const noexcept { return _host_id; } -/** - * Merge object. - * - * @param[in] obj The object to merge. - */ -void host::merge(configuration::hostextinfo const& tmpl) { - MRG_DEFAULT(_action_url); - MRG_OPTION(_coords_2d); - MRG_OPTION(_coords_3d); - MRG_DEFAULT(_icon_image); - MRG_DEFAULT(_icon_image_alt); - MRG_DEFAULT(_notes); - MRG_DEFAULT(_notes_url); - MRG_DEFAULT(_statusmap_image); - MRG_DEFAULT(_vrml_image); -} - /** * Merge object. * diff --git a/engine/src/configuration/hostescalation.cc b/engine/src/configuration/hostescalation.cc index 97553dd1f74..602616c8245 100644 --- a/engine/src/configuration/hostescalation.cc +++ b/engine/src/configuration/hostescalation.cc @@ -1,22 +1,22 @@ /** -* Copyright 2011-2013,2015 Merethis -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ - + * Copyright 2011-2013,2015 Merethis + * Copyright 2017-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include "com/centreon/engine/configuration/hostescalation.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/string.hh" diff --git a/engine/src/configuration/hostextinfo.cc b/engine/src/configuration/hostextinfo.cc deleted file mode 100644 index 0bb5a966323..00000000000 --- a/engine/src/configuration/hostextinfo.cc +++ /dev/null @@ -1,442 +0,0 @@ -/** -* Copyright 2011-2013 Merethis -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ - -#include "com/centreon/engine/configuration/hostextinfo.hh" -#include "com/centreon/engine/exceptions/error.hh" -#include "com/centreon/engine/string.hh" - -using namespace com::centreon; -using namespace com::centreon::engine::configuration; - -#define SETTER(type, method) \ - &object::setter::generic - -std::unordered_map const - hostextinfo::_setters{ - {"host_name", SETTER(std::string const&, _set_hosts)}, - {"hostgroup", SETTER(std::string const&, _set_hostgroups)}, - {"hostgroup_name", SETTER(std::string const&, _set_hostgroups)}, - {"notes", SETTER(std::string const&, _set_notes)}, - {"notes_url", SETTER(std::string const&, _set_notes_url)}, - {"action_url", SETTER(std::string const&, _set_action_url)}, - {"icon_image", SETTER(std::string const&, _set_icon_image)}, - {"icon_image_alt", SETTER(std::string const&, _set_icon_image_alt)}, - {"vrml_image", SETTER(std::string const&, _set_vrml_image)}, - {"gd2_image", SETTER(std::string const&, _set_statusmap_image)}, - {"statusmap_image", SETTER(std::string const&, _set_statusmap_image)}, - {"2d_coords", SETTER(std::string const&, _set_coords_2d)}, - {"3d_coords", SETTER(std::string const&, _set_coords_3d)}}; - -// Default values. -static point_2d const default_coords_2d(-1, -1); -static point_3d const default_coords_3d(0.0, 0.0, 0.0); - -/** - * Default constructor. - */ -hostextinfo::hostextinfo() - : object(object::hostextinfo), - _coords_2d(default_coords_2d), - _coords_3d(default_coords_3d) {} - -/** - * Copy constructor. - * - * @param[in] right The hostextinfo to copy. - */ -hostextinfo::hostextinfo(hostextinfo const& right) : object(right) { - operator=(right); -} - -/** - * Destructor. - */ -hostextinfo::~hostextinfo() throw() {} - -/** - * Copy constructor. - * - * @param[in] right The hostextinfo to copy. - * - * @return This hostextinfo. - */ -hostextinfo& hostextinfo::operator=(hostextinfo const& right) { - if (this != &right) { - object::operator=(right); - _action_url = right._action_url; - _coords_2d = right._coords_2d; - _coords_3d = right._coords_3d; - _hostgroups = right._hostgroups; - _hosts = right._hosts; - _icon_image = right._icon_image; - _icon_image_alt = right._icon_image_alt; - _notes = right._notes; - _notes_url = right._notes_url; - _statusmap_image = right._statusmap_image; - _vrml_image = right._vrml_image; - } - return *this; -} - -/** - * Equal operator. - * - * @param[in] right The hostextinfo to compare. - * - * @return True if is the same hostextinfo, otherwise false. - */ -bool hostextinfo::operator==(hostextinfo const& right) const throw() { - return (object::operator==(right) && _action_url == right._action_url && - _coords_2d == right._coords_2d && _coords_3d == right._coords_3d && - _hostgroups == right._hostgroups && _hosts == right._hosts && - _icon_image == right._icon_image && - _icon_image_alt == right._icon_image_alt && _notes == right._notes && - _notes_url == right._notes_url && - _statusmap_image == right._statusmap_image && - _vrml_image == right._vrml_image); -} - -/** - * Equal operator. - * - * @param[in] right The hostextinfo to compare. - * - * @return True if is not the same hostextinfo, otherwise false. - */ -bool hostextinfo::operator!=(hostextinfo const& right) const throw() { - return !operator==(right); -} - -/** - * @brief Check if the object is valid. - * - * If the object is not valid, an exception is thrown. - */ -void hostextinfo::check_validity() const { - if (_hostgroups->empty() && _hosts->empty()) - throw(engine_error() - << "Host extended information is not attached" - << " to any host or host group (properties 'host_name' or " - << "'hostgroup_name', respectively)"); - return; -} - -/** - * Merge object. - * - * @param[in] obj The object to merge. - */ -void hostextinfo::merge(object const& obj) { - if (obj.type() != _type) - throw(engine_error() << "Cannot merge host extended information with '" - << obj.type() << "'"); - hostextinfo const& tmpl(static_cast(obj)); - - MRG_DEFAULT(_action_url); - MRG_OPTION(_coords_2d); - MRG_OPTION(_coords_3d); - MRG_INHERIT(_hostgroups); - MRG_INHERIT(_hosts); - MRG_DEFAULT(_icon_image); - MRG_DEFAULT(_icon_image_alt); - MRG_DEFAULT(_notes); - MRG_DEFAULT(_notes_url); - MRG_DEFAULT(_statusmap_image); - MRG_DEFAULT(_vrml_image); -} - -/** - * Parse and set the hostextinfo property. - * - * @param[in] key The property name. - * @param[in] value The property value. - * - * @return True on success, otherwise false. - */ -bool hostextinfo::parse(char const* key, char const* value) { - std::unordered_map::const_iterator it{ - _setters.find(key)}; - if (it != _setters.end()) - return (it->second)(*this, value); - return false; -} - -/** - * Get action_url. - * - * @return The action_url. - */ -std::string const& hostextinfo::action_url() const throw() { - return _action_url; -} - -/** - * Get coords_2d. - * - * @return The coords_2d. - */ -point_2d const& hostextinfo::coords_2d() const throw() { - return _coords_2d.get(); -} - -/** - * Get 3d_coords. - * - * @return The 3d_coords. - */ -point_3d const& hostextinfo::coords_3d() const throw() { - return _coords_3d.get(); -} - -/** - * Get hostgroups. - * - * @return The hostgroups. - */ -set_string const& hostextinfo::hostgroups() const throw() { - return *_hostgroups; -} - -/** - * Get hosts. - * - * @return The hosts. - */ -set_string const& hostextinfo::hosts() const throw() { - return *_hosts; -} - -/** - * Get icon_image. - * - * @return The icon_image. - */ -std::string const& hostextinfo::icon_image() const throw() { - return _icon_image; -} - -/** - * Get icon_image_alt. - * - * @return The icon_image_alt. - */ -std::string const& hostextinfo::icon_image_alt() const throw() { - return _icon_image_alt; -} - -/** - * Get notes. - * - * @return The notes. - */ -std::string const& hostextinfo::notes() const throw() { - return _notes; -} - -/** - * Get notes_url. - * - * @return The notes_url. - */ -std::string const& hostextinfo::notes_url() const throw() { - return _notes_url; -} - -/** - * Get statusmap_image. - * - * @return The statusmap_image. - */ -std::string const& hostextinfo::statusmap_image() const throw() { - return _statusmap_image; -} - -/** - * Get vrml_image. - * - * @return The vrml_image. - */ -std::string const& hostextinfo::vrml_image() const throw() { - return _vrml_image; -} - -/** - * Set action_url value. - * - * @param[in] value The new action_url value. - * - * @return True on success, otherwise false. - */ -bool hostextinfo::_set_action_url(std::string const& value) { - _action_url = value; - return true; -} - -/** - * Set coords_2s value. - * - * @param[in] value The new coords_2d value. - * - * @return True on success, otherwise false. - */ -bool hostextinfo::_set_coords_2d(std::string const& value) { - std::list coords; - string::split(value, coords, ','); - if (coords.size() != 2) - return false; - - int x; - if (!string::to(string::trim(coords.front()).c_str(), x)) - return false; - coords.pop_front(); - - int y; - if (!string::to(string::trim(coords.front()).c_str(), y)) - return false; - - _coords_2d = point_2d(x, y); - return true; -} - -/** - * Set coords_3d value. - * - * @param[in] value The new coords_3d value. - * - * @return True on success, otherwise false. - */ -bool hostextinfo::_set_coords_3d(std::string const& value) { - std::list coords; - string::split(value, coords, ','); - if (coords.size() != 3) - return false; - - double x; - if (!string::to(string::trim(coords.front()).c_str(), x)) - return false; - coords.pop_front(); - - double y; - if (!string::to(string::trim(coords.front()).c_str(), y)) - return false; - coords.pop_front(); - - double z; - if (!string::to(string::trim(coords.front()).c_str(), z)) - return false; - - _coords_3d = point_3d(x, y, z); - return true; -} - -/** - * Set hostgroups value. - * - * @param[in] value The new hostgroups value. - * - * @return True on success, otherwise false. - */ -bool hostextinfo::_set_hostgroups(std::string const& value) { - _hostgroups = value; - return true; -} - -/** - * Set hosts value. - * - * @param[in] value The new hosts value. - * - * @return True on success, otherwise false. - */ -bool hostextinfo::_set_hosts(std::string const& value) { - _hosts = value; - return true; -} - -/** - * Set icon_image value. - * - * @param[in] value The new icon_image value. - * - * @return True on success, otherwise false. - */ -bool hostextinfo::_set_icon_image(std::string const& value) { - _icon_image = value; - return true; -} - -/** - * Set icon_image_alt value. - * - * @param[in] value The new icon_image_alt value. - * - * @return True on success, otherwise false. - */ -bool hostextinfo::_set_icon_image_alt(std::string const& value) { - _icon_image_alt = value; - return true; -} - -/** - * Set notes value. - * - * @param[in] value The new notes value. - * - * @return True on success, otherwise false. - */ -bool hostextinfo::_set_notes(std::string const& value) { - _notes = value; - return true; -} - -/** - * Set notes_url value. - * - * @param[in] value The new notes_url value. - * - * @return True on success, otherwise false. - */ -bool hostextinfo::_set_notes_url(std::string const& value) { - _notes_url = value; - return true; -} - -/** - * Set statusmap_image value. - * - * @param[in] value The new statusmap_image value. - * - * @return True on success, otherwise false. - */ -bool hostextinfo::_set_statusmap_image(std::string const& value) { - _statusmap_image = value; - return true; -} - -/** - * Set vrml_image value. - * - * @param[in] value The new vrml_image value. - * - * @return True on success, otherwise false. - */ -bool hostextinfo::_set_vrml_image(std::string const& value) { - _vrml_image = value; - return true; -} diff --git a/engine/src/configuration/object.cc b/engine/src/configuration/object.cc index 5c87c1498f3..ae0db4ec86f 100644 --- a/engine/src/configuration/object.cc +++ b/engine/src/configuration/object.cc @@ -1,22 +1,22 @@ /** * Copyright 2011-2014 Merethis + * Copyright 2017-2024 Centreon * - * This file is part of Centreon Engine. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Centreon Engine is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License version 2 - * as published by the Free Software Foundation. + * http://www.apache.org/licenses/LICENSE-2.0 * - * Centreon Engine is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com * - * You should have received a copy of the GNU General Public License - * along with Centreon Engine. If not, see - * . */ - #include "com/centreon/engine/configuration/object.hh" #include "com/centreon/engine/configuration/anomalydetection.hh" #include "com/centreon/engine/configuration/command.hh" @@ -26,12 +26,10 @@ #include "com/centreon/engine/configuration/host.hh" #include "com/centreon/engine/configuration/hostdependency.hh" #include "com/centreon/engine/configuration/hostescalation.hh" -#include "com/centreon/engine/configuration/hostextinfo.hh" #include "com/centreon/engine/configuration/hostgroup.hh" #include "com/centreon/engine/configuration/service.hh" #include "com/centreon/engine/configuration/servicedependency.hh" #include "com/centreon/engine/configuration/serviceescalation.hh" -#include "com/centreon/engine/configuration/serviceextinfo.hh" #include "com/centreon/engine/configuration/servicegroup.hh" #include "com/centreon/engine/configuration/severity.hh" #include "com/centreon/engine/configuration/tag.hh" @@ -150,10 +148,6 @@ object_ptr object::create(std::string const& type_name) { obj = std::make_shared(); else if (type_name == "connector") obj = std::make_shared(); - else if (type_name == "serviceextinfo") - obj = std::make_shared(); - else if (type_name == "hostextinfo") - obj = std::make_shared(); else if (type_name == "anomalydetection") obj = std::make_shared(); else if (type_name == "severity") diff --git a/engine/src/configuration/parser.cc b/engine/src/configuration/parser.cc index f2826e4ce94..5c017842d1f 100644 --- a/engine/src/configuration/parser.cc +++ b/engine/src/configuration/parser.cc @@ -83,10 +83,6 @@ void parser::parse(std::string const& path, state& config) { // Apply template. _resolve_template(); - // Apply extended info. - _apply_hostextinfo(); - _apply_serviceextinfo(); - // Fill state. _insert(_map_objects[object::command], config.commands()); _insert(_map_objects[object::connector], config.connectors()); @@ -159,80 +155,6 @@ void parser::_apply(std::list const& lst, (this->*pfunc)(*it); } -/** - * Apply the host extended info. - * - * @warning This function is for compatibility and has very - * poor performance. Didn't use extended info. If you - * want to use the generic template system. - */ -void parser::_apply_hostextinfo() { - map_object& gl_hosts(_map_objects[object::host]); - list_object const& hostextinfos(_lst_objects[object::hostextinfo]); - for (list_object::const_iterator it(hostextinfos.begin()), - end(hostextinfos.end()); - it != end; ++it) { - // Get the current hostextinfo to check. - hostextinfo_ptr obj(std::static_pointer_cast(*it)); - - list_host hosts; - _get_objects_by_list_name(obj->hosts(), gl_hosts, hosts); - _get_hosts_by_hostgroups_name(obj->hostgroups(), hosts); - - for (list_host::iterator it(hosts.begin()), end(hosts.end()); it != end; - ++it) - it->merge(*obj); - } -} - -/** - * Apply the service extended info. - * - * @warning This function is for compatibility and has very - * poor performance. Didn't use extended info. If you - * want to use the generic template system. - */ -void parser::_apply_serviceextinfo() { - map_object& gl_hosts(_map_objects[object::host]); - list_object& gl_services(_lst_objects[object::service]); - list_object const& serviceextinfos(_lst_objects[object::serviceextinfo]); - for (list_object::const_iterator it(serviceextinfos.begin()), - end(serviceextinfos.end()); - it != end; ++it) { - // Get the current serviceextinfo to check. - serviceextinfo_ptr obj(std::static_pointer_cast(*it)); - - list_host hosts; - _get_objects_by_list_name(obj->hosts(), gl_hosts, hosts); - _get_hosts_by_hostgroups_name(obj->hostgroups(), hosts); - - for (list_object::iterator it(gl_services.begin()), end(gl_services.end()); - it != end; ++it) { - service_ptr svc(std::static_pointer_cast(*it)); - if (svc->service_description() != obj->service_description()) - continue; - - list_host svc_hosts; - _get_objects_by_list_name(svc->hosts(), gl_hosts, svc_hosts); - _get_hosts_by_hostgroups_name(svc->hostgroups(), svc_hosts); - - bool found(false); - for (list_host::const_iterator it_host(hosts.begin()), - end_host(hosts.end()); - !found && it_host != end_host; ++it_host) { - for (list_host::const_iterator it_svc_host(svc_hosts.begin()), - end_svc_host(svc_hosts.end()); - it_svc_host != end_svc_host; ++it_svc_host) { - if (it_host->host_name() == it_svc_host->host_name()) { - svc->merge(*obj); - found = true; - } - } - } - } - } -} - /** * Get the file information. * diff --git a/engine/src/configuration/point_2d.cc b/engine/src/configuration/point_2d.cc index 889ddf8fd8f..a777933084b 100644 --- a/engine/src/configuration/point_2d.cc +++ b/engine/src/configuration/point_2d.cc @@ -1,22 +1,22 @@ /** -* Copyright 2011-2013 Merethis -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ - + * Copyright 2011-2013 Merethis + * Copyright 2014-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include "com/centreon/engine/configuration/point_2d.hh" using namespace com::centreon::engine::configuration; diff --git a/engine/src/configuration/point_3d.cc b/engine/src/configuration/point_3d.cc index 3095d8f0e31..102b9183a98 100644 --- a/engine/src/configuration/point_3d.cc +++ b/engine/src/configuration/point_3d.cc @@ -1,22 +1,22 @@ /** -* Copyright 2011-2013 Merethis -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ - + * Copyright 2011-2013 Merethis + * Copyright 2014-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include "com/centreon/engine/configuration/point_3d.hh" using namespace com::centreon::engine::configuration; diff --git a/engine/src/configuration/service.cc b/engine/src/configuration/service.cc index c342beee52b..fdeb2d1d982 100644 --- a/engine/src/configuration/service.cc +++ b/engine/src/configuration/service.cc @@ -21,7 +21,6 @@ #include #include #include -#include "com/centreon/engine/configuration/serviceextinfo.hh" #include "com/centreon/engine/customvariable.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" @@ -828,19 +827,6 @@ service::key_type service::key() const { return k; } -/** - * Merge object. - * - * @param[in] obj The object to merge. - */ -void service::merge(configuration::serviceextinfo const& tmpl) { - MRG_DEFAULT(_action_url); - MRG_DEFAULT(_icon_image); - MRG_DEFAULT(_icon_image_alt); - MRG_DEFAULT(_notes); - MRG_DEFAULT(_notes_url); -} - /** * Merge object. * diff --git a/engine/src/configuration/serviceextinfo.cc b/engine/src/configuration/serviceextinfo.cc deleted file mode 100644 index 2fa3bec1033..00000000000 --- a/engine/src/configuration/serviceextinfo.cc +++ /dev/null @@ -1,332 +0,0 @@ -/** -* Copyright 2011-2013,2017 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ - -#include "com/centreon/engine/configuration/serviceextinfo.hh" -#include "com/centreon/engine/exceptions/error.hh" - -using namespace com::centreon; -using namespace com::centreon::engine::configuration; - -#define SETTER(type, method) \ - &object::setter::generic - -std::unordered_map const - serviceextinfo::_setters{ - {"host_name", SETTER(std::string const&, _set_hosts)}, - {"hostgroup", SETTER(std::string const&, _set_hostgroups)}, - {"hostgroup_name", SETTER(std::string const&, _set_hostgroups)}, - {"service_description", - SETTER(std::string const&, _set_service_description)}, - {"notes", SETTER(std::string const&, _set_notes)}, - {"notes_url", SETTER(std::string const&, _set_notes_url)}, - {"action_url", SETTER(std::string const&, _set_action_url)}, - {"icon_image", SETTER(std::string const&, _set_icon_image)}, - {"icon_image_alt", SETTER(std::string const&, _set_icon_image_alt)}}; - -/** - * Default constructor. - */ -serviceextinfo::serviceextinfo() : object(object::serviceextinfo) {} - -/** - * Copy constructor. - * - * @param[in] right The serviceextinfo to copy. - */ -serviceextinfo::serviceextinfo(serviceextinfo const& right) : object(right) { - operator=(right); -} - -/** - * Destructor. - */ -serviceextinfo::~serviceextinfo() throw() {} - -/** - * Copy constructor. - * - * @param[in] right The serviceextinfo to copy. - * - * @return This serviceextinfo. - */ -serviceextinfo& serviceextinfo::operator=(serviceextinfo const& right) { - if (this != &right) { - object::operator=(right); - _action_url = right._action_url; - _icon_image = right._icon_image; - _icon_image_alt = right._icon_image_alt; - _hosts = right._hosts; - _hostgroups = right._hostgroups; - _notes = right._notes; - _notes_url = right._notes_url; - _service_description = right._service_description; - } - return *this; -} - -/** - * Equal operator. - * - * @param[in] right The serviceextinfo to compare. - * - * @return True if is the same serviceextinfo, otherwise false. - */ -bool serviceextinfo::operator==(serviceextinfo const& right) const throw() { - return (object::operator==(right) && _action_url == right._action_url && - _icon_image == right._icon_image && - _icon_image_alt == right._icon_image_alt && _hosts == right._hosts && - _hostgroups == right._hostgroups && _notes == right._notes && - _notes_url == right._notes_url && - _service_description == right._service_description); -} - -/** - * Equal operator. - * - * @param[in] right The serviceextinfo to compare. - * - * @return True if is not the same serviceextinfo, otherwise false. - */ -bool serviceextinfo::operator!=(serviceextinfo const& right) const throw() { - return !operator==(right); -} - -/** - * @brief Check if the object is valid. - * - * If the object is not valid, an exception is thrown. - */ -void serviceextinfo::check_validity() const { - if (_service_description.empty()) - throw(engine_error() - << "Service extended information is not " - << "attached to a service (property 'service_description')"); - if (_hosts->empty() && _hostgroups->empty()) - throw(engine_error() - << "Service extended information of service '" << _service_description - << "' is not attached to any host or" - << " host group (properties 'host_name' or 'hostgroup_name'" - << ", respectively)"); - return; -} - -/** - * Merge object. - * - * @param[in] obj The object to merge. - */ -void serviceextinfo::merge(object const& obj) { - if (obj.type() != _type) - throw(engine_error() << "Cannot merge service extended information with '" - << obj.type() << "'"); - serviceextinfo const& tmpl(static_cast(obj)); - - MRG_DEFAULT(_action_url); - MRG_DEFAULT(_icon_image); - MRG_DEFAULT(_icon_image_alt); - MRG_INHERIT(_hosts); - MRG_INHERIT(_hostgroups); - MRG_DEFAULT(_notes); - MRG_DEFAULT(_notes_url); - MRG_DEFAULT(_service_description); -} - -/** - * Parse and set the serviceextinfo property. - * - * @param[in] key The property name. - * @param[in] value The property value. - * - * @return True on success, otherwise false. - */ -bool serviceextinfo::parse(char const* key, char const* value) { - std::unordered_map::const_iterator - it{_setters.find(key)}; - if (it != _setters.end()) - return (it->second)(*this, value); - return false; -} - -/** - * Get action_url. - * - * @return The action_url. - */ -std::string const& serviceextinfo::action_url() const throw() { - return _action_url; -} - -/** - * Get icon_image. - * - * @return The icon_image. - */ -std::string const& serviceextinfo::icon_image() const throw() { - return _icon_image; -} - -/** - * Get icon_image_alt. - * - * @return The icon_image_alt. - */ -std::string const& serviceextinfo::icon_image_alt() const throw() { - return _icon_image_alt; -} - -/** - * Get hostgroups. - * - * @return The hostgroups. - */ -set_string const& serviceextinfo::hostgroups() const throw() { - return *_hostgroups; -} - -/** - * Get hosts. - * - * @return The hosts. - */ -set_string const& serviceextinfo::hosts() const throw() { - return *_hosts; -} - -/** - * Get notes. - * - * @return The notes. - */ -std::string const& serviceextinfo::notes() const throw() { - return _notes; -} - -/** - * Get notes_url. - * - * @return The notes_url. - */ -std::string const& serviceextinfo::notes_url() const throw() { - return _notes_url; -} - -/** - * Get service_description. - * - * @return The service_description. - */ -std::string const& serviceextinfo::service_description() const throw() { - return _service_description; -} - -/** - * Set action_url value. - * - * @param[in] value The new action_url value. - * - * @return True on success, otherwise false. - */ -bool serviceextinfo::_set_action_url(std::string const& value) { - _action_url = value; - return true; -} - -/** - * Set icon_image value. - * - * @param[in] value The new icon_image value. - * - * @return True on success, otherwise false. - */ -bool serviceextinfo::_set_icon_image(std::string const& value) { - _icon_image = value; - return true; -} - -/** - * Set icon_image_alt value. - * - * @param[in] value The new icon_image_alt value. - * - * @return True on success, otherwise false. - */ -bool serviceextinfo::_set_icon_image_alt(std::string const& value) { - _icon_image_alt = value; - return true; -} - -/** - * Set hosts value. - * - * @param[in] value The new hosts value. - * - * @return True on success, otherwise false. - */ -bool serviceextinfo::_set_hosts(std::string const& value) { - _hosts = value; - return true; -} - -/** - * Set hostgroups value. - * - * @param[in] value The new hostgroups value. - * - * @return True on success, otherwise false. - */ -bool serviceextinfo::_set_hostgroups(std::string const& value) { - _hostgroups = value; - return true; -} - -/** - * Set notes value. - * - * @param[in] value The new notes value. - * - * @return True on success, otherwise false. - */ -bool serviceextinfo::_set_notes(std::string const& value) { - _notes = value; - return true; -} - -/** - * Set notes_url value. - * - * @param[in] value The new notes_url value. - * - * @return True on success, otherwise false. - */ -bool serviceextinfo::_set_notes_url(std::string const& value) { - _notes_url = value; - return true; -} - -/** - * Set service_description value. - * - * @param[in] value The new service_description value. - * - * @return True on success, otherwise false. - */ -bool serviceextinfo::_set_service_description(std::string const& value) { - _service_description = value; - return true; -} diff --git a/engine/src/configuration/servicegroup.cc b/engine/src/configuration/servicegroup.cc index af88f76bb9e..3855ff80897 100644 --- a/engine/src/configuration/servicegroup.cc +++ b/engine/src/configuration/servicegroup.cc @@ -1,22 +1,21 @@ /** -* Copyright 2011-2013,2017 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ - + * Copyright 2011-2013,2017 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include "com/centreon/engine/configuration/servicegroup.hh" #include "com/centreon/engine/exceptions/error.hh" diff --git a/engine/src/configuration/state.cc b/engine/src/configuration/state.cc index e648c0f03c7..dc4b3ee4e82 100644 --- a/engine/src/configuration/state.cc +++ b/engine/src/configuration/state.cc @@ -1,22 +1,21 @@ /** * Copyright 2011-2013,2015-2017, 2021-2024 Centreon * - * This file is part of Centreon Engine. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Centreon Engine is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License version 2 - * as published by the Free Software Foundation. + * http://www.apache.org/licenses/LICENSE-2.0 * - * Centreon Engine is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com * - * You should have received a copy of the GNU General Public License - * along with Centreon Engine. If not, see - * . */ - #include "com/centreon/engine/configuration/state.hh" #include "com/centreon/common/rapidjson_helper.hh" #include "com/centreon/engine/broker.hh" diff --git a/engine/src/configuration/timeperiod.cc b/engine/src/configuration/timeperiod.cc index 21535000527..5d20d96030d 100644 --- a/engine/src/configuration/timeperiod.cc +++ b/engine/src/configuration/timeperiod.cc @@ -1,22 +1,22 @@ /** -* Copyright 2011-2013 Merethis -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ - + * Copyright 2011-2013 Merethis + * Copyright 2017-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include "com/centreon/engine/configuration/timeperiod.hh" #include "com/centreon/engine/common.hh" From 356de81cff27f76f5470c6b838a3451b9727e521 Mon Sep 17 00:00:00 2001 From: David Boucher Date: Wed, 5 Jun 2024 00:13:45 +0200 Subject: [PATCH 21/60] fix(engine): applier classes simplified --- .../configuration/applier/anomalydetection.hh | 10 +++--- .../engine/configuration/applier/connector.hh | 20 ++++++----- .../engine/configuration/applier/contact.hh | 26 +++++++++------ .../configuration/applier/contactgroup.hh | 31 +++++++++-------- .../engine/configuration/applier/globals.hh | 16 +++++---- .../applier/servicedependency.hh | 25 +++++++------- .../applier/serviceescalation.hh | 23 +++++++------ .../configuration/applier/anomalydetection.cc | 33 ------------------- engine/src/configuration/applier/connector.cc | 10 ------ engine/src/configuration/applier/contact.cc | 23 ------------- .../src/configuration/applier/contactgroup.cc | 32 ------------------ engine/src/configuration/applier/globals.cc | 5 --- .../applier/servicedependency.cc | 10 ------ .../applier/serviceescalation.cc | 10 ------ 14 files changed, 83 insertions(+), 191 deletions(-) diff --git a/engine/inc/com/centreon/engine/configuration/applier/anomalydetection.hh b/engine/inc/com/centreon/engine/configuration/applier/anomalydetection.hh index 5cb2cc30522..88fc8497f6f 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/anomalydetection.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/anomalydetection.hh @@ -35,14 +35,14 @@ class anomalydetection { configuration::state const& s); public: - anomalydetection(); - anomalydetection(anomalydetection const& right); - ~anomalydetection(); - anomalydetection& operator=(anomalydetection const& right); + anomalydetection() = default; + anomalydetection(const anomalydetection&) = delete; + ~anomalydetection() noexcept = default; + anomalydetection& operator=(const anomalydetection&) = delete; void add_object(configuration::anomalydetection const& obj); - void expand_objects(configuration::state& s); void modify_object(configuration::anomalydetection const& obj); void remove_object(configuration::anomalydetection const& obj); + void expand_objects(configuration::state& s); void resolve_object(configuration::anomalydetection const& obj); }; } // namespace applier diff --git a/engine/inc/com/centreon/engine/configuration/applier/connector.hh b/engine/inc/com/centreon/engine/configuration/applier/connector.hh index e42892e53ff..e7e1ea93490 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/connector.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/connector.hh @@ -30,17 +30,21 @@ class state; namespace applier { class connector { public: - connector(); - ~connector() throw(); + /** + * @brief Default constructor. + */ + connector() = default; + /** + * @brief Destructor. + */ + ~connector() noexcept = default; + connector(const connector&) = delete; + connector& operator=(const connector&) = delete; void add_object(configuration::connector const& obj); - void expand_objects(configuration::state& s); - void modify_object(configuration::connector const& obj); + void modify_object(const configuration::connector& obj); void remove_object(configuration::connector const& obj); + void expand_objects(configuration::state& s); void resolve_object(configuration::connector const& obj); - - private: - connector(connector const& right); - connector& operator=(connector const& right); }; } // namespace applier } // namespace configuration diff --git a/engine/inc/com/centreon/engine/configuration/applier/contact.hh b/engine/inc/com/centreon/engine/configuration/applier/contact.hh index 17e2bb6ac78..76a501889f1 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/contact.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/contact.hh @@ -30,17 +30,23 @@ class state; namespace applier { class contact { public: - contact(); - ~contact() throw(); - void add_object(configuration::contact const& obj); - void expand_objects(configuration::state& s); - void modify_object(configuration::contact const& obj); - void remove_object(configuration::contact const& obj); - void resolve_object(configuration::contact const& obj); + /** + * @brief Default constructor. + */ + contact() = default; + + /** + * @brief Destructor + */ + ~contact() noexcept = default; + contact(contact const&) = delete; + contact& operator=(const contact&) = delete; - private: - contact(contact const& right); - contact& operator=(contact const& right); + void add_object(const configuration::contact& obj); + void modify_object(const configuration::contact& obj); + void remove_object(const configuration::contact& obj); + void expand_objects(configuration::state& s); + void resolve_object(const configuration::contact& obj); }; } // namespace applier } // namespace configuration diff --git a/engine/inc/com/centreon/engine/configuration/applier/contactgroup.hh b/engine/inc/com/centreon/engine/configuration/applier/contactgroup.hh index 75e5fb6af7b..642220d8933 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/contactgroup.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/contactgroup.hh @@ -30,26 +30,31 @@ class state; namespace applier { class contactgroup { - public: - contactgroup(); - contactgroup(contactgroup const& right); - ~contactgroup() throw(); - contactgroup& operator=(contactgroup const& right); - void add_object(configuration::contactgroup const& obj); - void expand_objects(configuration::state& s); - void modify_object(configuration::contactgroup const& obj); - void remove_object(configuration::contactgroup const& obj); - void resolve_object(configuration::contactgroup const& obj); - - private: typedef std::map resolved_set; + resolved_set _resolved; + void _resolve_members(configuration::state& s, configuration::contactgroup const& obj); - resolved_set _resolved; + public: + /** + * @brief Default constructor. + */ + contactgroup() = default; + /** + * @brief Destructor. + */ + ~contactgroup() noexcept = default; + contactgroup(const contactgroup&) = delete; + contactgroup& operator=(const contactgroup&) = delete; + void add_object(configuration::contactgroup const& obj); + void modify_object(configuration::contactgroup const& obj); + void remove_object(configuration::contactgroup const& obj); + void expand_objects(configuration::state& s); + void resolve_object(configuration::contactgroup const& obj); }; } // namespace applier } // namespace configuration diff --git a/engine/inc/com/centreon/engine/configuration/applier/globals.hh b/engine/inc/com/centreon/engine/configuration/applier/globals.hh index 2448c41c05f..561ef400403 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/globals.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/globals.hh @@ -34,17 +34,19 @@ namespace applier { * Simple configuration applier for globals class. */ class globals { + /** + * Default constructor. + */ + globals() = default; + globals(globals const&) = delete; + ~globals() noexcept; + globals& operator=(globals const&) = delete; + void _set_global(char*& property, std::string const& value); + public: void apply(configuration::state& globals); static globals& instance(); void clear(); - - private: - globals(); - globals(globals const&); - ~globals() throw(); - globals& operator=(globals const&); - void _set_global(char*& property, std::string const& value); }; } // namespace applier } // namespace configuration diff --git a/engine/inc/com/centreon/engine/configuration/applier/servicedependency.hh b/engine/inc/com/centreon/engine/configuration/applier/servicedependency.hh index 915817f634e..3e8ca2814ce 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/servicedependency.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/servicedependency.hh @@ -29,25 +29,24 @@ class state; namespace applier { class servicedependency { - public: - servicedependency(); - servicedependency(servicedependency const& right) = delete; - ~servicedependency() throw(); - servicedependency& operator=(servicedependency const& right) = delete; - void add_object(configuration::servicedependency const& obj); - void expand_objects(configuration::state& s); - void modify_object(configuration::servicedependency const& obj); - void remove_object(configuration::servicedependency const& obj); - void resolve_object(configuration::servicedependency const& obj); - - private: void _expand_services( std::list const& hst, std::list const& hg, std::list const& svc, std::list const& sg, configuration::state& s, - std::set >& expanded); + std::set>& expanded); + + public: + servicedependency() = default; + ~servicedependency() noexcept = default; + servicedependency(const servicedependency&) = delete; + servicedependency& operator=(const servicedependency&) = delete; + void add_object(configuration::servicedependency const& obj); + void modify_object(configuration::servicedependency const& obj); + void expand_objects(configuration::state& s); + void remove_object(configuration::servicedependency const& obj); + void resolve_object(configuration::servicedependency const& obj); }; } // namespace applier } // namespace configuration diff --git a/engine/inc/com/centreon/engine/configuration/applier/serviceescalation.hh b/engine/inc/com/centreon/engine/configuration/applier/serviceescalation.hh index c437ee34089..8b6b067a414 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/serviceescalation.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/serviceescalation.hh @@ -29,18 +29,6 @@ class state; namespace applier { class serviceescalation { - public: - serviceescalation(); - serviceescalation(serviceescalation const& right) = delete; - ~serviceescalation() throw(); - serviceescalation& operator=(serviceescalation const& right) = delete; - void add_object(configuration::serviceescalation const& obj); - void expand_objects(configuration::state& s); - void modify_object(configuration::serviceescalation const& obj); - void remove_object(configuration::serviceescalation const& obj); - void resolve_object(configuration::serviceescalation const& obj); - - private: void _expand_services( std::list const& hst, std::list const& hg, @@ -50,6 +38,17 @@ class serviceescalation { std::set >& expanded); void _inherits_special_vars(configuration::serviceescalation& obj, configuration::state const& s); + + public: + serviceescalation() = default; + serviceescalation(const serviceescalation&) = delete; + ~serviceescalation() noexcept = default; + serviceescalation& operator=(const serviceescalation&) = delete; + void add_object(const configuration::serviceescalation& obj); + void modify_object(const configuration::serviceescalation& obj); + void remove_object(const configuration::serviceescalation& obj); + void expand_objects(configuration::state& s); + void resolve_object(const configuration::serviceescalation& obj); }; } // namespace applier } // namespace configuration diff --git a/engine/src/configuration/applier/anomalydetection.cc b/engine/src/configuration/applier/anomalydetection.cc index ac3b8ac926f..a4cc5ef1d14 100644 --- a/engine/src/configuration/applier/anomalydetection.cc +++ b/engine/src/configuration/applier/anomalydetection.cc @@ -47,39 +47,6 @@ class servicegroup_name_comparator { std::string _servicegroup_name; }; -/** - * Default constructor. - */ -applier::anomalydetection::anomalydetection() {} - -/** - * Copy constructor. - * - * @param[in] right Object to copy. - */ -applier::anomalydetection::anomalydetection( - applier::anomalydetection const& right) { - (void)right; -} - -/** - * Destructor. - */ -applier::anomalydetection::~anomalydetection() {} - -/** - * Assignment operator. - * - * @param[in] right Object to copy. - * - * @return This object. - */ -applier::anomalydetection& applier::anomalydetection::operator=( - applier::anomalydetection const& right) { - (void)right; - return *this; -} - /** * Add new anomalydetection. * diff --git a/engine/src/configuration/applier/connector.cc b/engine/src/configuration/applier/connector.cc index 0734f526538..ca35ccefea0 100644 --- a/engine/src/configuration/applier/connector.cc +++ b/engine/src/configuration/applier/connector.cc @@ -27,16 +27,6 @@ using namespace com::centreon::engine::configuration; -/** - * Default constructor. - */ -applier::connector::connector() {} - -/** - * Destructor. - */ -applier::connector::~connector() noexcept {} - /** * Add new connector. * diff --git a/engine/src/configuration/applier/contact.cc b/engine/src/configuration/applier/contact.cc index 07d225eb9e5..022737ac760 100644 --- a/engine/src/configuration/applier/contact.cc +++ b/engine/src/configuration/applier/contact.cc @@ -47,29 +47,6 @@ class contactgroup_name_comparator { std::string _contactgroup_name; }; -/** - * Default constructor. - */ -applier::contact::contact() {} - -/** - * Destructor. - */ -applier::contact::~contact() throw() {} - -/** - * Assignment operator. - * - * @param[in] right Object to copy. - * - * @return This object. - */ -// applier::contact& applier::contact::operator=( -// applier::contact const& right) { -// (void)right; -// return *this; -//} - /** * Add new contact. * diff --git a/engine/src/configuration/applier/contactgroup.cc b/engine/src/configuration/applier/contactgroup.cc index 2b27dfa35e0..ebb743a3281 100644 --- a/engine/src/configuration/applier/contactgroup.cc +++ b/engine/src/configuration/applier/contactgroup.cc @@ -29,38 +29,6 @@ using namespace com::centreon::engine::configuration; using namespace com::centreon::engine::logging; -/** - * Default constructor. - */ -applier::contactgroup::contactgroup() {} - -/** - * Copy constructor. - * - * @param[in] right Object to copy. - */ -applier::contactgroup::contactgroup(applier::contactgroup const& right) { - (void)right; -} - -/** - * Destructor. - */ -applier::contactgroup::~contactgroup() throw() {} - -/** - * Assignment operator. - * - * @param[in] right Object to copy. - * - * @return This object. - */ -applier::contactgroup& applier::contactgroup::operator=( - applier::contactgroup const& right) { - (void)right; - return (*this); -} - /** * Add new contactgroup * diff --git a/engine/src/configuration/applier/globals.cc b/engine/src/configuration/applier/globals.cc index fc256c6617b..c85c97079c6 100644 --- a/engine/src/configuration/applier/globals.cc +++ b/engine/src/configuration/applier/globals.cc @@ -100,11 +100,6 @@ void applier::globals::clear() { ::use_timezone = NULL; } -/** - * Default constructor. - */ -applier::globals::globals() {} - /** * Destructor. */ diff --git a/engine/src/configuration/applier/servicedependency.cc b/engine/src/configuration/applier/servicedependency.cc index 25c69f6bf43..f4fd873c949 100644 --- a/engine/src/configuration/applier/servicedependency.cc +++ b/engine/src/configuration/applier/servicedependency.cc @@ -29,16 +29,6 @@ using namespace com::centreon::engine::configuration; -/** - * Default constructor. - */ -applier::servicedependency::servicedependency() {} - -/** - * Destructor. - */ -applier::servicedependency::~servicedependency() throw() {} - /** * Add new service dependency. * diff --git a/engine/src/configuration/applier/serviceescalation.cc b/engine/src/configuration/applier/serviceescalation.cc index e5f46604e0e..8676491c66a 100644 --- a/engine/src/configuration/applier/serviceescalation.cc +++ b/engine/src/configuration/applier/serviceescalation.cc @@ -25,16 +25,6 @@ using namespace com::centreon::engine::configuration; -/** - * Default constructor. - */ -applier::serviceescalation::serviceescalation() {} - -/** - * Destructor. - */ -applier::serviceescalation::~serviceescalation() throw() {} - /** * Add new service escalation. * From 8b3022d32df707ff39453d0f64ed08b9d48cb736 Mon Sep 17 00:00:00 2001 From: David Boucher Date: Wed, 5 Jun 2024 00:40:50 +0200 Subject: [PATCH 22/60] enh(engine): customvariable configuration class added --- .../engine/configuration/customvariable.hh | 48 ++++++++++++++++ engine/src/configuration/customvariable.cc | 56 +++++++++++++++++++ 2 files changed, 104 insertions(+) create mode 100644 engine/inc/com/centreon/engine/configuration/customvariable.hh create mode 100644 engine/src/configuration/customvariable.cc diff --git a/engine/inc/com/centreon/engine/configuration/customvariable.hh b/engine/inc/com/centreon/engine/configuration/customvariable.hh new file mode 100644 index 00000000000..337c1830bf3 --- /dev/null +++ b/engine/inc/com/centreon/engine/configuration/customvariable.hh @@ -0,0 +1,48 @@ +/* + * Copyright 2023 Centreon (https://www.centreon.com/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ +#ifndef CCE_CONFIGURATION_CUSTOMVARIABLE_HH +#define CCE_CONFIGURATION_CUSTOMVARIABLE_HH +#include + +namespace com::centreon::engine::configuration { +/** + * @class customvariable customvariable.hh + * "com/centreon/engine/configuration/customvariable.hh" + * @brief This class represents a customvariable configuration. + * + * It is lighter than the engine::customvariable class and also it is + * separated from the engine core because the configuration module must be + * loadable from cbd. + */ +class customvariable { + std::string _value; + bool _is_sent; + + public: + customvariable(std::string const& value = "", bool is_sent = false); + bool operator==(const customvariable& other) const; + ~customvariable() noexcept = default; + void set_sent(bool sent); + bool is_sent() const; + void set_value(const std::string& value); + const std::string& value() const; +}; +} // namespace com::centreon::engine::configuration + +#endif /* !CCE_CONFIGURATION_CUSTOMVARIABLE_HH */ diff --git a/engine/src/configuration/customvariable.cc b/engine/src/configuration/customvariable.cc new file mode 100644 index 00000000000..d41dd32df75 --- /dev/null +++ b/engine/src/configuration/customvariable.cc @@ -0,0 +1,56 @@ +/* + * Copyright 2023 Centreon (https://www.centreon.com/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ + +#include "com/centreon/engine/configuration/customvariable.hh" + +using namespace com::centreon::engine::configuration; + +customvariable::customvariable(const std::string& value, bool is_sent) + : _value{value}, _is_sent{is_sent} {} + +// customvariable::customvariable(customvariable const& other) +// : _value{other._value}, _is_sent{other._is_sent} {} + +// customvariable& customvariable::operator=(const customvariable& other) { +// if (this != &other) { +// _value = other.value; +// _is_sent = other._is_sent; +// } +// return *this; +// } + +void customvariable::set_sent(bool sent) { + _is_sent = sent; +} + +bool customvariable::is_sent() const { + return _is_sent; +} + +void customvariable::set_value(const std::string& value) { + _value = value; +} + +const std::string& customvariable::value() const { + return _value; +} + +bool customvariable::operator==(const customvariable& other) const { + return _value == other._value && _is_sent == other._is_sent; +} From 69686628e89554332680d10b0f51cdd0bbd1fb58 Mon Sep 17 00:00:00 2001 From: jean-christophe81 <98889244+jean-christophe81@users.noreply.github.com> Date: Wed, 5 Jun 2024 10:39:56 +0200 Subject: [PATCH 23/60] enh(engine): associate otl metrics to hosts-services (#1388) REFS: MON-34004 --- broker/grpc/src/stream.cc | 37 +- clib/inc/com/centreon/misc/get_options.hh | 11 +- clib/src/misc/get_options.cc | 51 +- common/http/src/http_connection.cc | 2 +- .../inc/com/centreon/common/node_allocator.hh | 4 +- common/{test => tests}/test_main.cc | 0 engine/doc/engine-doc.md | 2 +- .../inc/com/centreon/engine/check_result.hh | 52 +- engine/inc/com/centreon/engine/checkable.hh | 7 +- .../com/centreon/engine/commands/command.hh | 70 ++- .../com/centreon/engine/commands/forward.hh | 12 +- .../centreon/engine/commands/otel_command.hh | 98 +++ .../engine/commands/otel_interface.hh | 31 +- .../engine/configuration/applier/command.hh | 9 +- .../centreon/engine/configuration/state.hh | 39 +- engine/inc/com/centreon/engine/host.hh | 49 +- engine/inc/com/centreon/engine/service.hh | 47 +- engine/modules/opentelemetry/CMakeLists.txt | 4 + .../modules/opentelemetry/data_point_fifo.hh | 82 +++ .../data_point_fifo_container.hh | 94 +++ .../opentelemetry/host_serv_extractor.hh | 149 +++++ .../modules/opentelemetry/open_telemetry.hh | 48 +- .../modules/opentelemetry/otl_converter.hh | 117 ++++ .../opentelemetry/src/data_point_fifo.cc | 70 +++ .../src/data_point_fifo_container.cc | 135 +++++ .../opentelemetry/src/host_serv_extractor.cc | 205 +++++++ engine/modules/opentelemetry/src/main.cc | 1 + .../opentelemetry/src/open_telemetry.cc | 248 +++++--- .../opentelemetry/src/otl_converter.cc | 173 ++++++ engine/src/anomalydetection.cc | 54 +- engine/src/check_result.cc | 17 +- engine/src/checks/checker.cc | 25 +- engine/src/commands/CMakeLists.txt | 36 +- engine/src/commands/command.cc | 32 +- engine/src/commands/connector.cc | 4 +- engine/src/commands/forward.cc | 59 +- engine/src/commands/otel_command.cc | 314 ++++++++++ engine/src/commands/otel_interface.cc | 14 +- engine/src/commands/raw.cc | 25 +- engine/src/commands/result.cc | 22 +- engine/src/configuration/applier/command.cc | 47 +- engine/src/configuration/applier/connector.cc | 88 ++- engine/src/configuration/applier/state.cc | 3 + engine/src/configuration/state.cc | 28 +- engine/src/host.cc | 102 +++- engine/src/service.cc | 91 ++- engine/tests/CMakeLists.txt | 5 +- .../opentelemetry/host_serv_extractor_test.cc | 368 ++++++++++++ .../opentelemetry/open_telemetry_test.cc | 141 +++++ .../tests/opentelemetry/otl_converter_test.cc | 563 ++++++++++++++++++ tests/resources/Common.py | 2 +- 51 files changed, 3496 insertions(+), 391 deletions(-) rename common/{test => tests}/test_main.cc (100%) create mode 100644 engine/inc/com/centreon/engine/commands/otel_command.hh create mode 100644 engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/data_point_fifo.hh create mode 100644 engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/data_point_fifo_container.hh create mode 100644 engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/host_serv_extractor.hh create mode 100644 engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_converter.hh create mode 100644 engine/modules/opentelemetry/src/data_point_fifo.cc create mode 100644 engine/modules/opentelemetry/src/data_point_fifo_container.cc create mode 100644 engine/modules/opentelemetry/src/host_serv_extractor.cc create mode 100644 engine/modules/opentelemetry/src/otl_converter.cc create mode 100644 engine/src/commands/otel_command.cc create mode 100644 engine/tests/opentelemetry/host_serv_extractor_test.cc create mode 100644 engine/tests/opentelemetry/open_telemetry_test.cc create mode 100644 engine/tests/opentelemetry/otl_converter_test.cc diff --git a/broker/grpc/src/stream.cc b/broker/grpc/src/stream.cc index ca4942abc2b..282ae57582b 100644 --- a/broker/grpc/src/stream.cc +++ b/broker/grpc/src/stream.cc @@ -120,7 +120,10 @@ std::mutex stream::_instances_m; template stream::stream(const grpc_config::pointer& conf, const std::string_view& class_name) - : io::stream("GRPC"), _conf(conf), _class_name(class_name), _logger{log_v2::instance().get(log_v2::GRPC)} { + : io::stream("GRPC"), + _conf(conf), + _class_name(class_name), + _logger{log_v2::instance().get(log_v2::GRPC)} { SPDLOG_LOGGER_DEBUG(_logger, "create {} this={:p}", _class_name, static_cast(this)); } @@ -223,9 +226,8 @@ bool stream::read(std::shared_ptr& d, d = std::make_shared(); std::static_pointer_cast(d)->_buffer.assign( to_convert.buffer().begin(), to_convert.buffer().end()); - SPDLOG_LOGGER_TRACE(_logger, "{:p} {} read:{}", - static_cast(this), _class_name, - *std::static_pointer_cast(d)); + SPDLOG_LOGGER_TRACE(_logger, "{:p} {} read:{}", static_cast(this), + _class_name, *std::static_pointer_cast(d)); return true; } else { d = protobuf_to_event(first); @@ -277,13 +279,11 @@ void stream::start_write() { } if (to_send->bbdo_event) - SPDLOG_LOGGER_TRACE(_logger, "{:p} {} write: {}", - static_cast(this), _class_name, - *to_send->bbdo_event); + SPDLOG_LOGGER_TRACE(_logger, "{:p} {} write: {}", static_cast(this), + _class_name, *to_send->bbdo_event); else - SPDLOG_LOGGER_TRACE(_logger, "{:p} {} write: {}", - static_cast(this), _class_name, - to_send->grpc_event); + SPDLOG_LOGGER_TRACE(_logger, "{:p} {} write: {}", static_cast(this), + _class_name, to_send->grpc_event); bireactor_class::StartWrite(&to_send->grpc_event); } @@ -365,12 +365,13 @@ void stream::OnDone() { stop(); /**grpc has a bug, sometimes if we delete this class in this handler as it is * described in examples, it also deletes used channel and does a pthread_join - * of the current thread witch go to a EDEADLOCK error and call grpc::Crash. + * of the current thread which go to a EDEADLOCK error and call grpc::Crash. * So we uses asio thread to do the job */ common::pool::io_context().post( [me = std::enable_shared_from_this< - stream>::shared_from_this(), logger = _logger]() { + stream>::shared_from_this(), + logger = _logger]() { std::lock_guard l(_instances_m); SPDLOG_LOGGER_DEBUG(logger, "{:p} server::OnDone()", static_cast(me.get())); @@ -390,13 +391,13 @@ void stream::OnDone(const ::grpc::Status& status) { stop(); /**grpc has a bug, sometimes if we delete this class in this handler as it is * described in examples, it also deletes used channel and does a - * pthread_join of the current thread witch go to a EDEADLOCK error and call + * pthread_join of the current thread which go to a EDEADLOCK error and call * grpc::Crash. So we uses asio thread to do the job */ common::pool::io_context().post( [me = std::enable_shared_from_this< stream>::shared_from_this(), - status, logger=_logger]() { + status, logger = _logger]() { std::lock_guard l(_instances_m); SPDLOG_LOGGER_DEBUG(logger, "{:p} client::OnDone({}) {}", static_cast(me.get()), @@ -412,8 +413,8 @@ void stream::OnDone(const ::grpc::Status& status) { */ template void stream::shutdown() { - SPDLOG_LOGGER_DEBUG(_logger, "{:p} {}::shutdown", - static_cast(this), _class_name); + SPDLOG_LOGGER_DEBUG(_logger, "{:p} {}::shutdown", static_cast(this), + _class_name); } /** @@ -437,8 +438,8 @@ template int32_t stream::stop() { std::lock_guard l(_protect); if (_alive) { - SPDLOG_LOGGER_DEBUG(_logger, "{:p} {}::stop", - static_cast(this), _class_name); + SPDLOG_LOGGER_DEBUG(_logger, "{:p} {}::stop", static_cast(this), + _class_name); _alive = false; this->shutdown(); } diff --git a/clib/inc/com/centreon/misc/get_options.hh b/clib/inc/com/centreon/misc/get_options.hh index 81445747083..4490379bbd5 100644 --- a/clib/inc/com/centreon/misc/get_options.hh +++ b/clib/inc/com/centreon/misc/get_options.hh @@ -1,5 +1,5 @@ /* -** Copyright 2011-2013 Centreon +** Copyright 2011-2024 Centreon ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. @@ -59,6 +59,13 @@ class get_options { void _parse_arguments(std::string const& command_line); virtual void _parse_arguments(std::vector const& args); + void _add_argument(const std::string& long_name, + char name, + const std::string description = "", + bool has_value = false, + bool is_set = false, + const std::string& value = ""); + std::map _arguments; std::vector _parameters; @@ -75,6 +82,6 @@ class get_options { }; } // namespace misc -} +} // namespace com::centreon #endif // !CC_MISC_GET_OPTIONS_HH diff --git a/clib/src/misc/get_options.cc b/clib/src/misc/get_options.cc index e5d9a0b3c08..552a0b708ff 100644 --- a/clib/src/misc/get_options.cc +++ b/clib/src/misc/get_options.cc @@ -1,20 +1,20 @@ /** -* Copyright 2011-2013 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/misc/get_options.hh" #include @@ -346,3 +346,22 @@ bool get_options::_split_short(std::string const& line, key = key.substr(0, 1); return true; } + +/** + * @brief Get the options:: add argument object + * + * @param[in] long_name Argument's long name. + * @param[in] name Argument's name. + * @param[in] has_value Argument need a value. + * @param[in] is_set Argument is set by default. + * @param[in] value The default value. + */ +void get_options::_add_argument(const std::string& long_name, + char name, + const std::string description, + bool has_value, + bool is_set, + const std::string& value) { + _arguments.emplace( + name, argument(long_name, name, description, has_value, is_set, value)); +} diff --git a/common/http/src/http_connection.cc b/common/http/src/http_connection.cc index 8f7ce8f6e52..fc7d60f4597 100644 --- a/common/http/src/http_connection.cc +++ b/common/http/src/http_connection.cc @@ -232,7 +232,7 @@ void http_connection::on_accept(connect_callback_type&& callback) { void http_connection::init_keep_alive() { // we put first keepalive option and then keepalive intervals - // system default interval are 7200s witch is too long to maintain a NAT + // system default interval are 7200s which is too long to maintain a NAT boost::system::error_code err_keep_alive; asio::socket_base::keep_alive opt1(true); _socket.socket().set_option(opt1, err_keep_alive); diff --git a/common/inc/com/centreon/common/node_allocator.hh b/common/inc/com/centreon/common/node_allocator.hh index d3913902c70..3f29c274f05 100644 --- a/common/inc/com/centreon/common/node_allocator.hh +++ b/common/inc/com/centreon/common/node_allocator.hh @@ -245,7 +245,9 @@ template node_allocator::node_allocator( const byte_allocator_type& allocator) : _allocator(allocator) { - _first = reinterpret_cast(_create_chunk()); + chunk* first_chunk = _create_chunk(); + first_chunk->next = nullptr; + _first = reinterpret_cast(first_chunk); } /** diff --git a/common/test/test_main.cc b/common/tests/test_main.cc similarity index 100% rename from common/test/test_main.cc rename to common/tests/test_main.cc diff --git a/engine/doc/engine-doc.md b/engine/doc/engine-doc.md index 6839ce6647c..dbcd93a6432 100644 --- a/engine/doc/engine-doc.md +++ b/engine/doc/engine-doc.md @@ -27,7 +27,7 @@ whitelist: ``` The main main job is done by whitelist class, it parses file and compares final commands to regular expressions -This class is a singleton witch is replace by another instance each time conf is reloaded. +This class is a singleton which is replace by another instance each time conf is reloaded. Checkable class inherited by service and host classes keeps the last result of whitelist's check in cache in order to reduce CPU whitelist usage. diff --git a/engine/inc/com/centreon/engine/check_result.hh b/engine/inc/com/centreon/engine/check_result.hh index 05bcdeaf03b..9d02da8ef3b 100644 --- a/engine/inc/com/centreon/engine/check_result.hh +++ b/engine/inc/com/centreon/engine/check_result.hh @@ -1,22 +1,22 @@ -/* -** Copyright 2002-2006 Ethan Galstad -** Copyright 2011-2013 Merethis -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ +/** + * Copyright 2002-2006 Ethan Galstad + * Copyright 2011-2024 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #ifndef CCE_CHECKS_HH #define CCE_CHECKS_HH @@ -51,6 +51,9 @@ class check_result { return _object_check_type; } void set_object_check_type(enum check_source object_check_type); + uint64_t get_command_id() const { return _command_id; } + void set_command_id(uint64_t command_id) { _command_id = command_id; } + inline notifier* get_notifier() { return _notifier; } void set_notifier(notifier* notifier); inline struct timeval get_finish_time() const { return _finish_time; } @@ -78,6 +81,7 @@ class check_result { private: enum check_source _object_check_type; // is this a service or a host check? + uint64_t _command_id; notifier* _notifier; // was this an active or passive service check? enum checkable::check_type _check_type; @@ -91,6 +95,14 @@ class check_result { int _return_code; // plugin return code std::string _output; // plugin output }; -} + +std::ostream& operator<<(std::ostream& stream, const check_result& res); + +} // namespace com::centreon::engine + +namespace fmt { +template <> +struct formatter : ostream_formatter {}; +} // namespace fmt #endif // !CCE_CHECKS_HH diff --git a/engine/inc/com/centreon/engine/checkable.hh b/engine/inc/com/centreon/engine/checkable.hh index 0932e5d2b80..08deb7f1dcf 100644 --- a/engine/inc/com/centreon/engine/checkable.hh +++ b/engine/inc/com/centreon/engine/checkable.hh @@ -1,5 +1,5 @@ /* - * Copyright 2019,2022 Centreon (https://www.centreon.com/) + * Copyright 2019,2024 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -160,7 +160,7 @@ class checkable { std::string const& get_display_name() const; void set_display_name(std::string const& name); const std::string& name() const; - void set_name(const std::string& name); + virtual void set_name(const std::string& name); std::string const& check_command() const; void set_check_command(std::string const& check_command); uint32_t check_interval() const; @@ -246,7 +246,8 @@ class checkable { virtual bool is_in_downtime() const = 0; void set_event_handler_ptr(commands::command* cmd); commands::command* get_event_handler_ptr() const; - void set_check_command_ptr(const std::shared_ptr& cmd); + virtual void set_check_command_ptr( + const std::shared_ptr& cmd); inline const std::shared_ptr& get_check_command_ptr() const { return _check_command_ptr; diff --git a/engine/inc/com/centreon/engine/commands/command.hh b/engine/inc/com/centreon/engine/commands/command.hh index b9c9544ffbd..9748d289da6 100644 --- a/engine/inc/com/centreon/engine/commands/command.hh +++ b/engine/inc/com/centreon/engine/commands/command.hh @@ -1,21 +1,20 @@ -/* -** Copyright 2011-2013 Merethis -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ +/** + * Copyright 2011-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCE_COMMANDS_COMMAND_HH #define CCE_COMMANDS_COMMAND_HH @@ -28,7 +27,7 @@ namespace com::centreon::engine { namespace commands { class command; } -} +} // namespace com::centreon::engine typedef std::unordered_map< std::string, @@ -46,6 +45,10 @@ namespace commands { * notify listener at the end of the command. */ class command { + public: + enum class e_type { exec, forward, raw, connector, otel }; + const e_type _type; + protected: static uint64_t get_uniq_id(); @@ -90,7 +93,8 @@ class command { command(const std::string& name, const std::string& command_line, - command_listener* listener = nullptr); + command_listener* listener = nullptr, + e_type cmd_type = e_type::exec); virtual ~command() noexcept; command(const command&) = delete; command& operator=(const command&) = delete; @@ -98,6 +102,7 @@ class command { bool operator!=(const command& right) const noexcept; virtual const std::string& get_command_line() const noexcept; virtual const std::string& get_name() const noexcept; + e_type get_type() const { return _type; } virtual std::string process_cmd(nagios_macros* macros) const; virtual uint64_t run(const std::string& processed_cmd, nagios_macros& macors, @@ -109,6 +114,29 @@ class command { uint32_t timeout, result& res) = 0; + /** + * @brief connector and host serv extractor share a list of host serv which is + * updated by this method and unregister_host_serv + * This method add an entry in this list + * Command is the only thing that hosts and service knows. + * So we use it to update host serv list used by host serv extractors + * + * @param host + * @param service_description empty for host command + */ + virtual void register_host_serv(const std::string& host, + const std::string& service_description){}; + + /** + * @brief Remove an entry for host serv list shared between this connector and + * host serv extractor + * + * @param host + * @param service_description empty for host command + */ + virtual void unregister_host_serv(const std::string& host, + const std::string& service_description){}; + template void add_caller_group(caller_iterator begin, caller_iterator end); void remove_caller(void* caller); @@ -138,7 +166,7 @@ inline std::ostream& operator<<(std::ostream& s, const command::pointer& cmd) { } // namespace commands -} +} // namespace com::centreon::engine namespace fmt { template <> diff --git a/engine/inc/com/centreon/engine/commands/forward.hh b/engine/inc/com/centreon/engine/commands/forward.hh index 31d44570435..7e2c5b36b30 100644 --- a/engine/inc/com/centreon/engine/commands/forward.hh +++ b/engine/inc/com/centreon/engine/commands/forward.hh @@ -1,5 +1,5 @@ /* - * Copyright 2011-2013,2015,2019-2021 Centreon (https://www.centreon.com/) + * Copyright 2011-2013,2015,2019-2024 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,7 +39,7 @@ class forward : public command { public: forward(const std::string& command_name, const std::string& command_line, - std::shared_ptr& cmd); + const std::shared_ptr& cmd); ~forward() noexcept = default; forward(const forward&) = delete; forward& operator=(const forward&) = delete; @@ -52,6 +52,14 @@ class forward : public command { nagios_macros& macros, uint32_t timeout, result& res) override; + + std::shared_ptr get_sub_command() const { return _s_command; } + + void register_host_serv(const std::string& host, + const std::string& service_description) override; + + void unregister_host_serv(const std::string& host, + const std::string& service_description) override; }; } // namespace commands diff --git a/engine/inc/com/centreon/engine/commands/otel_command.hh b/engine/inc/com/centreon/engine/commands/otel_command.hh new file mode 100644 index 00000000000..4f73152e7db --- /dev/null +++ b/engine/inc/com/centreon/engine/commands/otel_command.hh @@ -0,0 +1,98 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#ifndef CCE_COMMANDS_OTEL_COMMAND_HH +#define CCE_COMMANDS_OTEL_COMMAND_HH + +#include "com/centreon/engine/commands/command.hh" +#include "com/centreon/engine/commands/otel_interface.hh" + +namespace com::centreon::engine::commands { + +/*** + * This fake connector is used to convert otel metrics to result + * Configuration is divided in 2 parts + * Connector command line configure the object who extract host and service from + * open telemetry request run command line configure converter who converts + * data_points to result + */ +class otel_command : public command, + public std::enable_shared_from_this { + otel::host_serv_list::pointer _host_serv_list; + + public: + using otel_command_container = + absl::flat_hash_map>; + + private: + static otel_command_container _commands; + + std::shared_ptr _extractor; + + std::shared_ptr _logger; + + void init(); + void reset_extractor(); + + public: + static void create(const std::string& connector_name, + const std::string& cmd_line, + commands::command_listener* listener); + + static bool remove(const std::string& connector_name); + + static bool update(const std::string& connector_name, + const std::string& cmd_line); + + static std::shared_ptr get_otel_command( + const std::string& connector_name); + + static void clear(); + + static void init_all(); + static void reset_all_extractor(); + + static const otel_command_container& get_otel_commands() { return _commands; } + + otel_command(const std::string& connector_name, + const std::string& cmd_line, + commands::command_listener* listener); + + void update(const std::string& cmd_line); + + virtual uint64_t run(const std::string& processed_cmd, + nagios_macros& macros, + uint32_t timeout, + const check_result::pointer& to_push_to_checker, + const void* caller = nullptr) override; + + virtual void run(const std::string& process_cmd, + nagios_macros& macros, + uint32_t timeout, + result& res) override; + + void register_host_serv(const std::string& host, + const std::string& service_description) override; + + void unregister_host_serv(const std::string& host, + const std::string& service_description) override; +}; + +} // namespace com::centreon::engine::commands + +#endif diff --git a/engine/inc/com/centreon/engine/commands/otel_interface.hh b/engine/inc/com/centreon/engine/commands/otel_interface.hh index 2d302e34409..1f5801d51e4 100644 --- a/engine/inc/com/centreon/engine/commands/otel_interface.hh +++ b/engine/inc/com/centreon/engine/commands/otel_interface.hh @@ -57,7 +57,7 @@ struct host_serv_metric { */ class host_serv_list { absl::flat_hash_map> _data; - mutable std::mutex _data_m; + mutable absl::Mutex _data_m; public: using pointer = std::shared_ptr; @@ -79,7 +79,7 @@ template host_serv_metric host_serv_list::is_allowed(const host_set& hosts, const service_set& services) const { host_serv_metric ret; - std::lock_guard l(_data_m); + absl::ReaderMutexLock l(&_data_m); for (const auto& host : hosts) { auto host_search = _data.find(host); if (host_search != _data.end()) { @@ -101,10 +101,26 @@ host_serv_metric host_serv_list::is_allowed(const host_set& hosts, return ret; } +/** + * @brief When we receive an opentelemetry metric, we have to extract host and + * service name in order to convert it in check_result. + * This is the job of the daughters of this class + * + */ +class host_serv_extractor { + public: + virtual ~host_serv_extractor() = default; +}; + using result_callback = std::function; class open_telemetry_base; +/** + * @brief access point of opentelemetry module used by engine + * All calls use open_telemetry_base::_instance + * + */ class open_telemetry_base : public std::enable_shared_from_this { protected: @@ -114,6 +130,17 @@ class open_telemetry_base virtual ~open_telemetry_base() = default; static std::shared_ptr& instance() { return _instance; } + + virtual std::shared_ptr create_extractor( + const std::string& cmdline, + const host_serv_list::pointer& host_serv_list) = 0; + + virtual bool check(const std::string& processed_cmd, + uint64_t command_id, + nagios_macros& macros, + uint32_t timeout, + commands::result& res, + result_callback&& handler) = 0; }; }; // namespace com::centreon::engine::commands::otel diff --git a/engine/inc/com/centreon/engine/configuration/applier/command.hh b/engine/inc/com/centreon/engine/configuration/applier/command.hh index 8df1d47a62e..1f07e67c9fe 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/command.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/command.hh @@ -36,16 +36,17 @@ namespace applier { class command { public: command(); + + command(command const&) = delete; + command& operator=(command const&) = delete; + ~command() throw(); + void add_object(configuration::command const& obj); void expand_objects(configuration::state& s); void modify_object(configuration::command const& obj); void remove_object(configuration::command const& obj); void resolve_object(configuration::command const& obj); - - private: - command(command const& right); - command& operator=(command const& right); }; } // namespace applier } // namespace configuration diff --git a/engine/inc/com/centreon/engine/configuration/state.hh b/engine/inc/com/centreon/engine/configuration/state.hh index e0b3cc2d9ab..174c53d4b57 100644 --- a/engine/inc/com/centreon/engine/configuration/state.hh +++ b/engine/inc/com/centreon/engine/configuration/state.hh @@ -1,21 +1,21 @@ -/* -** Copyright 2011-2017 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ +/** + * Copyright 2011-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + #ifndef CCE_CONFIGURATION_STATE_HH #define CCE_CONFIGURATION_STATE_HH @@ -444,6 +444,8 @@ class state { void log_level_process(std::string const& value); std::string const& log_level_runtime() const noexcept; void log_level_runtime(std::string const& value); + std::string const& log_level_otl() const noexcept; + void log_level_otl(std::string const& value); std::string const& use_timezone() const noexcept; void use_timezone(std::string const& value); bool use_true_regexp_matching() const noexcept; @@ -651,6 +653,7 @@ class state { std::string _log_level_macros; std::string _log_level_process; std::string _log_level_runtime; + std::string _log_level_otl; std::string _use_timezone; bool _use_true_regexp_matching; bool _send_recovery_notifications_anyways; diff --git a/engine/inc/com/centreon/engine/host.hh b/engine/inc/com/centreon/engine/host.hh index d135c76424d..c91f28a5e6a 100644 --- a/engine/inc/com/centreon/engine/host.hh +++ b/engine/inc/com/centreon/engine/host.hh @@ -1,21 +1,20 @@ -/* -** Copyright 2011-2019 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ +/** + * Copyright 2011-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCE_HOST_HH #define CCE_HOST_HH @@ -28,7 +27,7 @@ class contact; class host; class hostgroup; class hostescalation; -} +} // namespace com::centreon::engine using host_map = absl::flat_hash_map& cmd) override; + host_map_unsafe parent_hosts; host_map_unsafe child_hosts; static host_map hosts; @@ -256,6 +259,8 @@ class host : public notifier { std::list const& get_parent_groups() const; std::list& get_parent_groups(); + std::string get_check_command_line(nagios_macros* macros); + private: uint64_t _id; std::string _alias; @@ -288,7 +293,7 @@ class host : public notifier { std::list _hostgroups; }; -} +} // namespace com::centreon::engine int is_host_immediate_child_of_host(com::centreon::engine::host* parent, com::centreon::engine::host* child); @@ -311,7 +316,7 @@ bool host_exists(uint64_t host_id) noexcept; uint64_t get_host_id(std::string const& name); std::string get_host_name(const uint64_t host_id); -} +} // namespace com::centreon::engine std::ostream& operator<<(std::ostream& os, host_map_unsafe const& obj); diff --git a/engine/inc/com/centreon/engine/service.hh b/engine/inc/com/centreon/engine/service.hh index 7136e06fd59..64d96b826f7 100644 --- a/engine/inc/com/centreon/engine/service.hh +++ b/engine/inc/com/centreon/engine/service.hh @@ -1,21 +1,20 @@ -/* -** Copyright 2011-2022 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ +/** + * Copyright 2011-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCE_SERVICE_HH #define CCE_SERVICE_HH @@ -37,7 +36,7 @@ class host; class service; class servicegroup; class serviceescalation; -} +} // namespace com::centreon::engine using service_map = absl::flat_hash_map, @@ -118,6 +117,7 @@ class service : public notifier { service_type get_service_type() const; void set_hostname(std::string const& name); std::string const& get_hostname() const; + void set_name(std::string const& desc) override; void set_description(std::string const& desc); const std::string& description() const; void set_event_handler_args(std::string const& event_hdl_args); @@ -214,9 +214,14 @@ class service : public notifier { host* get_host_ptr(); bool get_host_problem_at_last_check() const; + void set_check_command_ptr( + const std::shared_ptr& cmd) override; + static service_map services; static service_id_map services_by_id; + std::string get_check_command_line(nagios_macros* macros); + private: uint64_t _host_id; uint64_t _service_id; @@ -239,7 +244,7 @@ class service : public notifier { host* _host_ptr; bool _host_problem_at_last_check; }; -} +} // namespace com::centreon::engine com::centreon::engine::service* add_service( uint64_t host_id, @@ -310,6 +315,6 @@ std::pair get_host_and_service_names( const uint64_t service_id); uint64_t get_service_id(std::string const& host, std::string const& svc); -} +} // namespace com::centreon::engine #endif // !CCE_SERVICE_HH diff --git a/engine/modules/opentelemetry/CMakeLists.txt b/engine/modules/opentelemetry/CMakeLists.txt index 4214596366a..ea8fabc78d5 100644 --- a/engine/modules/opentelemetry/CMakeLists.txt +++ b/engine/modules/opentelemetry/CMakeLists.txt @@ -45,9 +45,13 @@ endforeach() # mod_externalcmd target. add_library(opentelemetry SHARED +${SRC_DIR}/data_point_fifo.cc +${SRC_DIR}/data_point_fifo_container.cc ${SRC_DIR}/grpc_config.cc +${SRC_DIR}/host_serv_extractor.cc ${SRC_DIR}/open_telemetry.cc ${SRC_DIR}/otl_config.cc +${SRC_DIR}/otl_converter.cc ${SRC_DIR}/otl_data_point.cc ${SRC_DIR}/otl_server.cc ${SRC_DIR}/main.cc diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/data_point_fifo.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/data_point_fifo.hh new file mode 100644 index 00000000000..e6d61249fe6 --- /dev/null +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/data_point_fifo.hh @@ -0,0 +1,82 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ +#ifndef CCE_MOD_OTL_SERVER_DATA_POINT_FIFO_HH +#define CCE_MOD_OTL_SERVER_DATA_POINT_FIFO_HH + +#include "otl_data_point.hh" + +namespace com::centreon::engine::modules::opentelemetry { + +/** + * @brief This class is a multiset of opentelemetry data_point ordered by + * nano_timestamp + * + */ +class data_point_fifo { + struct time_unix_nano_compare { + /** + * @brief mandatory for heterogenous search (abseil or standard associative + * (C++20)) + * https://en.cppreference.com/w/cpp/utility/functional + * + */ + using is_transparent = void; + bool operator()(const data_point& left, const data_point& right) const { + return left.get_nano_timestamp() < right.get_nano_timestamp(); + } + bool operator()(const data_point& left, + uint64_t nano_timestamp_right) const { + return left.get_nano_timestamp() < nano_timestamp_right; + } + bool operator()(uint64_t nano_timestamp_left, + const data_point& right) const { + return nano_timestamp_left < right.get_nano_timestamp(); + } + }; + + public: + using container = absl::btree_multiset; + + private: + static time_t _second_datapoint_expiry; + static size_t _max_size; + + container _fifo; + + public: + const container& get_fifo() const { return _fifo; } + + bool empty() const { return _fifo.empty(); } + + void clear() { _fifo.clear(); } + + size_t size() const { return _fifo.size(); } + + void add_data_point(const data_point& data_pt); + + void clean(); + + static void update_fifo_limit(time_t second_datapoint_expiry, + size_t max_size); +}; + +using metric_name_to_fifo = absl::flat_hash_map; + +} // namespace com::centreon::engine::modules::opentelemetry + +#endif diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/data_point_fifo_container.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/data_point_fifo_container.hh new file mode 100644 index 00000000000..043417b0d6e --- /dev/null +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/data_point_fifo_container.hh @@ -0,0 +1,94 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 * You may obtain a copy of the + License at + + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ +#ifndef CCE_MOD_OTL_SERVER_DATA_POINT_FIFO_CONTAINER_HH +#define CCE_MOD_OTL_SERVER_DATA_POINT_FIFO_CONTAINER_HH + +#include "data_point_fifo.hh" + +namespace com::centreon::engine::modules::opentelemetry { + +/** + * @brief This class is a + * map host_serv -> map metric -> data_point_fifo (list of data_points) + * + */ +class data_point_fifo_container { + public: + private: + /** + * @brief + * metrics are ordered like this: + * => metric1 => data_points list + * => metric2 => data_points list + * + */ + using host_serv_to_metrics = absl::flat_hash_map; + + host_serv_to_metrics _data; + + static metric_name_to_fifo _empty; + + std::mutex _data_m; + + public: + void clean(); + + static void clean_empty_fifos(metric_name_to_fifo& to_clean); + + void add_data_point(const std::string_view& host, + const std::string_view& service, + const std::string_view& metric, + const data_point& data_pt); + + const metric_name_to_fifo& get_fifos(const std::string& host, + const std::string& service) const; + + metric_name_to_fifo& get_fifos(const std::string& host, + const std::string& service); + + void lock() { _data_m.lock(); } + + void unlock() { _data_m.unlock(); } + + void dump(std::string& output) const; +}; + +} // namespace com::centreon::engine::modules::opentelemetry + +namespace fmt { +template <> +struct formatter< + com::centreon::engine::modules::opentelemetry::data_point_fifo_container> + : formatter { + template + auto format(const com::centreon::engine::modules::opentelemetry:: + data_point_fifo_container& cont, + FormatContext& ctx) const -> decltype(ctx.out()) { + std::string output; + cont.dump(output); + return formatter::format(output, ctx); + } +}; + +} // namespace fmt + +#endif diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/host_serv_extractor.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/host_serv_extractor.hh new file mode 100644 index 00000000000..78ceed5b436 --- /dev/null +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/host_serv_extractor.hh @@ -0,0 +1,149 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#ifndef CCE_MOD_OTL_SERVER_HOST_SERV_EXTRACTOR_HH +#define CCE_MOD_OTL_SERVER_HOST_SERV_EXTRACTOR_HH + +#include "com/centreon/engine/commands/otel_interface.hh" +#include "otl_data_point.hh" + +namespace com::centreon::engine::modules::opentelemetry { + +using host_serv_metric = commands::otel::host_serv_metric; + +/** + * @brief base class of host serv extractor + * + */ +class host_serv_extractor : public commands::otel::host_serv_extractor { + const std::string _command_line; + const commands::otel::host_serv_list::pointer _host_serv_list; + + public: + host_serv_extractor( + const std::string& command_line, + const commands::otel::host_serv_list::pointer& host_serv_list) + : _command_line(command_line), _host_serv_list(host_serv_list) {} + + host_serv_extractor(const host_serv_extractor&) = delete; + host_serv_extractor& operator=(const host_serv_extractor&) = delete; + + const std::string& get_command_line() const { return _command_line; } + + static std::shared_ptr create( + const std::string& command_line, + const commands::otel::host_serv_list::pointer& host_serv_list); + + virtual host_serv_metric extract_host_serv_metric( + const data_point&) const = 0; + + bool is_allowed(const std::string& host, + const std::string& service_description) const; + + template + host_serv_metric is_allowed(const host_set& hosts, + const service_set& services) const; +}; + +template +host_serv_metric host_serv_extractor::is_allowed( + const host_set& hosts, + const service_set& services) const { + return _host_serv_list->is_allowed(hosts, services); +} + +/** + * @brief this class try to find host service in opentelemetry attributes object + * It may search in data resource attributes, scope attributes or data_point + * attributes + * An example of telegraf otel data: + * @code {.json} + * "dataPoints": [ + * { + * "timeUnixNano": "1707744430000000000", + * "asDouble": 500, + * "attributes": [ + * { + * "key": "unit", + * "value": { + * "stringValue": "ms" + * } + * }, + * { + * "key": "host", + * "value": { + * "stringValue": "localhost" + * } + * }, + * { + * "key": "perfdata", + * "value": { + * "stringValue": "rta" + * } + * }, + * { + * "key": "service", + * "value": { + * "stringValue": "check_icmp" + * } + * } + * ] + * }, + * @endcode + * + */ +class host_serv_attributes_extractor : public host_serv_extractor { + enum class attribute_owner { resource, scope, data_point }; + attribute_owner _host_path; + std::string _host_key; + attribute_owner _serv_path; + std::string _serv_key; + + public: + host_serv_attributes_extractor( + const std::string& command_line, + const commands::otel::host_serv_list::pointer& host_serv_list); + + host_serv_metric extract_host_serv_metric( + const data_point& data_pt) const override; +}; + +} // namespace com::centreon::engine::modules::opentelemetry + +namespace fmt { + +template <> +struct formatter< + ::com::centreon::engine::modules::opentelemetry::host_serv_extractor> { + constexpr auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) { + return ctx.begin(); + } + + // Formats the point p using the parsed format specification (presentation) + // stored in this formatter. + template + auto format(const ::com::centreon::engine::modules::opentelemetry:: + host_serv_extractor& extract, + FormatContext& ctx) const -> decltype(ctx.out()) { + return format_to(ctx.out(), "cmd_line: {}", extract.get_command_line()); + } +}; + +} // namespace fmt + +#endif diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/open_telemetry.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/open_telemetry.hh index d9206570b46..90aee07ab4a 100644 --- a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/open_telemetry.hh +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/open_telemetry.hh @@ -20,8 +20,10 @@ #include "com/centreon/engine/commands/otel_interface.hh" +#include "data_point_fifo_container.hh" +#include "host_serv_extractor.hh" #include "otl_config.hh" -#include "otl_data_point.hh" +#include "otl_converter.hh" namespace com::centreon::engine::modules::opentelemetry { @@ -43,10 +45,43 @@ class open_telemetry : public commands::otel::open_telemetry_base { asio::system_timer _second_timer; std::shared_ptr _otl_server; + using cmd_line_to_extractor_map = + absl::btree_map>; + cmd_line_to_extractor_map _extractors; + data_point_fifo_container _fifo; std::string _config_file_path; std::unique_ptr _conf; std::shared_ptr _logger; + struct host_serv_getter { + using result_type = host_serv; + const result_type& operator()( + const std::shared_ptr& node) const { + return node->get_host_serv(); + } + }; + + struct time_out_getter { + using result_type = std::chrono::system_clock::time_point; + result_type operator()(const std::shared_ptr& node) const { + return node->get_time_out(); + } + }; + + /** + * @brief when check can't return data right now, we have no metrics in fifo, + * converter is stored in this container. It's indexed by host,serv and by + * timeout + * + */ + using waiting_converter = boost::multi_index::multi_index_container< + std::shared_ptr, + boost::multi_index::indexed_by< + boost::multi_index::hashed_non_unique, + boost::multi_index::ordered_non_unique>>; + + waiting_converter _waiting; + std::shared_ptr _io_context; mutable std::mutex _protect; @@ -83,6 +118,17 @@ class open_telemetry : public commands::otel::open_telemetry_base { } static void unload(const std::shared_ptr& logger); + + bool check(const std::string& processed_cmd, + uint64_t command_id, + nagios_macros& macros, + uint32_t timeout, + commands::result& res, + commands::otel::result_callback&& handler) override; + + std::shared_ptr create_extractor( + const std::string& cmdline, + const commands::otel::host_serv_list::pointer& host_serv_list) override; }; } // namespace com::centreon::engine::modules::opentelemetry diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_converter.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_converter.hh new file mode 100644 index 00000000000..7a7065ce1ef --- /dev/null +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_converter.hh @@ -0,0 +1,117 @@ +/* +** Copyright 2024 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCE_MOD_OTL_CONVERTER_HH +#define CCE_MOD_OTL_CONVERTER_HH + +#include "com/centreon/engine/commands/otel_interface.hh" +#include "data_point_fifo.hh" + +namespace com::centreon::engine::modules::opentelemetry { + +class data_point_fifo_container; + +/** + * @brief The goal of this converter is to convert otel metrics in result + * This object is synchronous and asynchronous + * if needed data are available, it returns a results otherwise it will call + * callback passed in param + * These objects are oneshot, their lifetime is the check duration + * + */ +class otl_converter : public std::enable_shared_from_this { + const std::string _cmd_line; + const uint64_t _command_id; + const std::pair _host_serv; + const std::chrono::system_clock::time_point _timeout; + const commands::otel::result_callback _callback; + + protected: + std::shared_ptr _logger; + + virtual bool _build_result_from_metrics(metric_name_to_fifo&, + commands::result& res) = 0; + + public: + otl_converter(const std::string& cmd_line, + uint64_t command_id, + const host& host, + const service* service, + std::chrono::system_clock::time_point timeout, + commands::otel::result_callback&& handler, + const std::shared_ptr& logger); + + virtual ~otl_converter() = default; + + static std::string remove_converter_type(const std::string& cmd_line); + + const std::string& get_cmd_line() const { return _cmd_line; } + + uint64_t get_command_id() const { return _command_id; } + + const std::string& get_host_name() const { return _host_serv.first; } + const std::string& get_service_description() const { + return _host_serv.second; + } + + const std::pair& get_host_serv() const { + return _host_serv; + } + + std::chrono::system_clock::time_point get_time_out() const { + return _timeout; + } + + bool sync_build_result_from_metrics(data_point_fifo_container& data_pts, + commands::result& res); + + bool async_build_result_from_metrics(data_point_fifo_container& data_pts); + void async_time_out(); + + virtual void dump(std::string& output) const; + + static std::shared_ptr create( + const std::string& cmd_line, + uint64_t command_id, + const host& host, + const service* service, + std::chrono::system_clock::time_point timeout, + commands::otel::result_callback&& handler, + const std::shared_ptr& logger); +}; + +} // namespace com::centreon::engine::modules::opentelemetry + +namespace fmt { + +template <> +struct formatter + : formatter { + template + auto format( + const com::centreon::engine::modules::opentelemetry::otl_converter& cont, + FormatContext& ctx) const -> decltype(ctx.out()) { + std::string output; + (&cont)->dump(output); + return formatter::format(output, ctx); + } +}; + +} // namespace fmt + +#endif diff --git a/engine/modules/opentelemetry/src/data_point_fifo.cc b/engine/modules/opentelemetry/src/data_point_fifo.cc new file mode 100644 index 00000000000..778f7ba6c52 --- /dev/null +++ b/engine/modules/opentelemetry/src/data_point_fifo.cc @@ -0,0 +1,70 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#include "data_point_fifo.hh" + +using namespace com::centreon::engine::modules::opentelemetry; + +time_t data_point_fifo::_second_datapoint_expiry = 600; +size_t data_point_fifo::_max_size = 2; + +/** + * @brief opentelemetry fifo limits share a same value + * The goal of this isto fix these limits + * + * @param second_datapoint_expiry + * @param max_size + */ +void data_point_fifo::update_fifo_limit(time_t second_datapoint_expiry, + size_t max_size) { + _second_datapoint_expiry = second_datapoint_expiry; + _max_size = max_size; +} + +/** + * @brief add one data point to fifo + * + * @param data_pt + */ +void data_point_fifo::add_data_point(const data_point& data_pt) { + clean(); + _fifo.insert(data_pt); +} + +/** + * @brief erase to older data points + * + */ +void data_point_fifo::clean() { + if (!_fifo.empty()) { + auto first = _fifo.begin(); + time_t expiry = time(nullptr) - _second_datapoint_expiry; + if (expiry < 0) { + expiry = 0; + } + + while (!_fifo.empty() && + first->get_nano_timestamp() / 1000000000 < expiry) { + first = _fifo.erase(first); + } + + if (_fifo.size() >= _max_size) { + _fifo.erase(first); + } + } +} diff --git a/engine/modules/opentelemetry/src/data_point_fifo_container.cc b/engine/modules/opentelemetry/src/data_point_fifo_container.cc new file mode 100644 index 00000000000..b2ab98dc433 --- /dev/null +++ b/engine/modules/opentelemetry/src/data_point_fifo_container.cc @@ -0,0 +1,135 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#include "data_point_fifo_container.hh" + +using namespace com::centreon::engine::modules::opentelemetry; + +metric_name_to_fifo data_point_fifo_container::_empty; + +/** + * @brief clean olds data_points + * no need to lock mutex + */ +void data_point_fifo_container::clean() { + std::lock_guard l(_data_m); + for (auto serv_to_fifo_iter = _data.begin(); + !_data.empty() && serv_to_fifo_iter != _data.end();) { + for (auto& fifo : serv_to_fifo_iter->second) { + fifo.second.clean(); + } + if (serv_to_fifo_iter->second.empty()) { + auto to_erase = serv_to_fifo_iter++; + _data.erase(to_erase); + } else { + ++serv_to_fifo_iter; + } + } +} + +/** + * @brief erase empty fifos + * mutex of the owner of to_clean must be locked before call + * + * @param to_clean map metric_name -> fifos + */ +void data_point_fifo_container::clean_empty_fifos( + metric_name_to_fifo& to_clean) { + for (auto to_clean_iter = to_clean.begin(); + !to_clean.empty() && to_clean_iter != to_clean.end();) { + if (to_clean_iter->second.empty()) { + auto to_erase = to_clean_iter++; + to_clean.erase(to_erase); + } else { + ++to_clean_iter; + } + } +} + +/** + * @brief add a data point in the corresponding fifo + * mutex must be locked during returned data use + * + * @param data_pt data_point to add + */ +void data_point_fifo_container::add_data_point(const std::string_view& host, + const std::string_view& service, + const std::string_view& metric, + const data_point& data_pt) { + metric_name_to_fifo& fifos = _data[std::make_pair(host, service)]; + auto exist = fifos.find(metric); + if (exist == fifos.end()) { + exist = fifos.emplace(metric, data_point_fifo()).first; + } + exist->second.add_data_point(data_pt); +} + +/** + * @brief get all fifos of a service + * mutex must be locked during returned data use + * + * @param host + * @param service + * @return const metric_name_to_fifo& + */ +const metric_name_to_fifo& data_point_fifo_container::get_fifos( + const std::string& host, + const std::string& service) const { + auto exist = _data.find({host, service}); + return exist == _data.end() ? _empty : exist->second; +} + +/** + * @brief get all fifos of a service + * mutex must be locked during returned data use + * + * @param host + * @param service + * @return metric_name_to_fifo& + */ +metric_name_to_fifo& data_point_fifo_container::get_fifos( + const std::string& host, + const std::string& service) { + auto exist = _data.find({host, service}); + return exist == _data.end() ? _empty : exist->second; +} + +/** + * @brief debug output + * + * @param output string to log + */ +void data_point_fifo_container::dump(std::string& output) const { + output.push_back('{'); + for (const auto& host_serv : _data) { + output.push_back('"'); + output.append(host_serv.first.first); + output.push_back(','); + output.append(host_serv.first.second); + output.append("\":{"); + for (const auto& metric_to_fifo : host_serv.second) { + output.push_back('"'); + output.append(metric_to_fifo.first); + output.append("\":"); + absl::StrAppend(&output, metric_to_fifo.second.size()); + output.push_back(','); + } + output.append("},"); + } + output.push_back('}'); +} \ No newline at end of file diff --git a/engine/modules/opentelemetry/src/host_serv_extractor.cc b/engine/modules/opentelemetry/src/host_serv_extractor.cc new file mode 100644 index 00000000000..5ac15502e42 --- /dev/null +++ b/engine/modules/opentelemetry/src/host_serv_extractor.cc @@ -0,0 +1,205 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#include "com/centreon/engine/globals.hh" +#include "com/centreon/exceptions/msg_fmt.hh" +#include "com/centreon/misc/get_options.hh" + +#include "host_serv_extractor.hh" + +using namespace com::centreon::engine::modules::opentelemetry; + +/** + * @brief test if a host serv is allowed for this extractor + * + * @param host + * @param service_description + * @return true + * @return false + */ +bool host_serv_extractor::is_allowed( + const std::string& host, + const std::string& service_description) const { + return _host_serv_list->is_allowed(host, service_description); +} + +namespace com::centreon::engine::modules::opentelemetry::options { + +/** + * @brief command line parser for host_serv_attributes_extractor_config + * + */ +class host_serv_attributes_extractor_config_options + : public com::centreon::misc::get_options { + public: + host_serv_attributes_extractor_config_options(); + void parse(const std::string& cmd_line) { _parse_arguments(cmd_line); } +}; + +host_serv_attributes_extractor_config_options:: + host_serv_attributes_extractor_config_options() { + _add_argument("host_attribute", 'h', + "Where to find host attribute allowed values: resource, scope, " + "data_point", + true, true, "data_point"); + _add_argument("host_key", 'i', + "the key of attributes where we can find host name", true, true, + "host"); + _add_argument( + "service_attribute", 's', + "Where to find service attribute allowed values: resource, scope, " + "data_point", + true, true, "data_point"); + _add_argument("service_key", 't', + "the key of attributes where we can find the name of service", + true, true, "service"); +} + +}; // namespace com::centreon::engine::modules::opentelemetry::options + +/** + * @brief create host_serv_extractor according to command_line + * + * @param command_line + * @param host_serv_list list that will be shared bu host_serv_extractor and + * otel_command + * @return std::shared_ptr + */ +std::shared_ptr host_serv_extractor::create( + const std::string& command_line, + const commands::otel::host_serv_list::pointer& host_serv_list) { + // type of the converter is the first field + size_t sep_pos = command_line.find(' '); + std::string conf_type = sep_pos == std::string::npos + ? command_line + : command_line.substr(0, sep_pos); + boost::trim(conf_type); + std::string params = + sep_pos == std::string::npos ? "" : command_line.substr(sep_pos + 1); + + boost::trim(params); + + if (conf_type.empty() || conf_type == "attributes") { + return std::make_shared(params, + host_serv_list); + } else { + SPDLOG_LOGGER_ERROR(config_logger, "unknown converter type:{}", conf_type); + throw exceptions::msg_fmt("unknown converter type:{}", conf_type); + } +} + +/** + * @brief Construct a new host serv attributes extractor::host serv attributes + * extractor object + * + * @param command_line command line that contains options used by extractor + * @param host_serv_list list that will be shared bu host_serv_extractor and + * otel_command + */ +host_serv_attributes_extractor::host_serv_attributes_extractor( + const std::string& command_line, + const commands::otel::host_serv_list::pointer& host_serv_list) + : host_serv_extractor(command_line, host_serv_list) { + options::host_serv_attributes_extractor_config_options args; + args.parse(command_line); + + auto parse_param = + [&args]( + const std::string& attribute, + const std::string& key) -> std::pair { + const std::string& path = args.get_argument(attribute).get_value(); + attribute_owner owner; + if (path == "resource") { + owner = attribute_owner::resource; + } else if (path == "scope") { + owner = attribute_owner::scope; + } else { + owner = attribute_owner::data_point; + } + + std::string ret_key = args.get_argument(key).get_value(); + return std::make_pair(owner, ret_key); + }; + + try { + std::tie(_host_path, _host_key) = parse_param("host_attribute", "host_key"); + } catch (const std::exception&) { // default configuration + _host_path = attribute_owner::data_point; + _host_key = "host"; + } + try { + std::tie(_serv_path, _serv_key) = + parse_param("service_attribute", "service_key"); + } catch (const std::exception&) { // default configuration + _serv_path = attribute_owner::data_point; + _serv_key = "service"; + } +} + +/** + * @brief extract host and service names from configured attribute type + * + * @param data_pt + * @return host_serv_metric host attribute is empty if no expected attribute is + * found + */ +host_serv_metric host_serv_attributes_extractor::extract_host_serv_metric( + const data_point& data_pt) const { + auto extract = + [](const data_point& data_pt, attribute_owner owner, + const std::string& key) -> absl::flat_hash_set { + absl::flat_hash_set ret; + const ::google::protobuf::RepeatedPtrField< + ::opentelemetry::proto::common::v1::KeyValue>* attributes = nullptr; + switch (owner) { + case attribute_owner::data_point: + attributes = &data_pt.get_data_point_attributes(); + break; + case attribute_owner::scope: + attributes = &data_pt.get_scope().attributes(); + break; + case attribute_owner::resource: + attributes = &data_pt.get_resource().attributes(); + break; + default: + return ret; + } + for (const auto& key_val : *attributes) { + if (key_val.key() == key && key_val.value().has_string_value()) { + ret.insert(key_val.value().string_value()); + } + } + return ret; + }; + + host_serv_metric ret; + + absl::flat_hash_set hosts = + extract(data_pt, _host_path, _host_key); + + if (!hosts.empty()) { + absl::flat_hash_set services = + extract(data_pt, _serv_path, _serv_key); + ret = is_allowed(hosts, services); + if (!ret.host.empty()) { + ret.metric = data_pt.get_metric().name(); + } + } + + return ret; +} diff --git a/engine/modules/opentelemetry/src/main.cc b/engine/modules/opentelemetry/src/main.cc index da9d40945c6..d6a06082306 100644 --- a/engine/modules/opentelemetry/src/main.cc +++ b/engine/modules/opentelemetry/src/main.cc @@ -16,6 +16,7 @@ * For more information : contact@centreon.com */ +#include "com/centreon/engine/commands/otel_command.hh" #include "com/centreon/engine/nebmods.hh" #include "com/centreon/engine/nebmodules.hh" #include "com/centreon/exceptions/msg_fmt.hh" diff --git a/engine/modules/opentelemetry/src/open_telemetry.cc b/engine/modules/opentelemetry/src/open_telemetry.cc index 8babb8cb317..3c6ea25fcc3 100644 --- a/engine/modules/opentelemetry/src/open_telemetry.cc +++ b/engine/modules/opentelemetry/src/open_telemetry.cc @@ -60,6 +60,8 @@ void open_telemetry::_reload() { fmt::formatter<::opentelemetry::proto::collector::metrics::v1:: ExportMetricsServiceRequest>::json_grpc_format = new_conf->get_json_grpc_log(); + data_point_fifo::update_fifo_limit(new_conf->get_second_fifo_expiry(), + new_conf->get_max_fifo_size()); _conf = std::move(new_conf); } @@ -86,7 +88,7 @@ std::shared_ptr open_telemetry::load( } /** - * @brief create grpc server witch accept otel collector connections + * @brief create grpc server which accept otel collector connections * * @param server_conf json server config */ @@ -154,6 +156,110 @@ void open_telemetry::_shutdown() { _second_timer.cancel(); } +/** + * @brief create an host serv extractor from connector command line + * + * @param cmdline which begins with name of extractor, following parameters + * are used by extractor + * @param host_serv_list list that will be shared bu host_serv_extractor and + * otel_command + * @return + * std::shared_ptr + * @throw if extractor type is unknown + */ +std::shared_ptr +open_telemetry::create_extractor( + const std::string& cmdline, + const commands::otel::host_serv_list::pointer& host_serv_list) { + // erase host serv extractors that are only owned by this object + auto clean = [this]() { + for (cmd_line_to_extractor_map::const_iterator to_test = + _extractors.begin(); + !_extractors.empty() && to_test != _extractors.end();) { + if (to_test->second.use_count() <= 1) { + SPDLOG_LOGGER_DEBUG(_logger, "remove extractor:{}", *to_test->second); + to_test = _extractors.erase(to_test); + } else { + ++to_test; + } + } + }; + std::lock_guard l(_protect); + auto exist = _extractors.find(cmdline); + if (exist != _extractors.end()) { + std::shared_ptr + to_ret = exist->second; + clean(); + return to_ret; + } + clean(); + try { + std::shared_ptr new_extractor = + host_serv_extractor::create(cmdline, host_serv_list); + _extractors.emplace(cmdline, new_extractor); + SPDLOG_LOGGER_DEBUG(_logger, "create extractor:{}", *new_extractor); + return new_extractor; + } catch (const std::exception& e) { + SPDLOG_LOGGER_ERROR(_logger, "fail to create extractor \"{}\" : {}", + cmdline, e.what()); + throw; + } +} + +/** + * @brief simulate a check by reading in metrics fifos + * It creates an otel_converter, the first word of processed_cmd is the name + * of converter such as nagios_telegraf. Following parameters are used by + * converter + * + * @param processed_cmd converter type with arguments + * @param command_id command id + * @param macros + * @param timeout + * @param res filled if it returns true + * @param handler called later if it returns false + * @return true res is filled with a result + * @return false result will be passed to handler as soon as available or + * timeout + * @throw if converter type is unknown + */ +bool open_telemetry::check(const std::string& processed_cmd, + uint64_t command_id, + nagios_macros& macros, + uint32_t timeout, + commands::result& res, + commands::otel::result_callback&& handler) { + std::shared_ptr to_use; + try { + to_use = otl_converter::create( + processed_cmd, command_id, *macros.host_ptr, macros.service_ptr, + std::chrono::system_clock::now() + std::chrono::seconds(timeout), + std::move(handler), _logger); + } catch (const std::exception& e) { + SPDLOG_LOGGER_ERROR(_logger, "fail to create converter for {} : {}", + processed_cmd, e.what()); + throw; + }; + + bool res_available = to_use->sync_build_result_from_metrics(_fifo, res); + + if (res_available) { + SPDLOG_LOGGER_TRACE(_logger, "data available for command {} converter:{}", + command_id, *to_use); + return true; + } + + SPDLOG_LOGGER_TRACE( + _logger, "data unavailable for command {} timeout: {} converter:{}", + command_id, timeout, *to_use); + + // metrics not yet available = wait for data or until timeout + std::lock_guard l(_protect); + _waiting.insert(to_use); + + return false; +} + /** * @brief called on metric reception * we first fill data_point fifos and then if a converter of a service is @@ -167,62 +273,61 @@ void open_telemetry::_on_metric(const metric_request_ptr& metrics) { std::vector unknown; { std::lock_guard l(_protect); - // if (_extractors.empty()) { - // data_point::extract_data_points(metrics, - // [&unknown](const data_point& data_pt) { - // unknown.push_back(data_pt); - // }); - // } else { - // waiting_converter::nth_index<0>::type& host_serv_index = - // _waiting.get<0>(); - // std::vector> to_notify; - // auto last_success = _extractors.begin(); - // data_point::extract_data_points(metrics, [this, &unknown, - // &last_success, - // &host_serv_index, - // &to_notify]( - // const data_point& data_pt) - // { - // bool data_point_known = false; - // // we try all extractors and we begin with the last witch has - // // achieved to extract host - // for (unsigned tries = 0; tries < _extractors.size(); ++tries) { - // host_serv_metric hostservmetric = - // last_success->second->extract_host_serv_metric(data_pt); + if (_extractors.empty()) { // no extractor configured => all unknown + data_point::extract_data_points(metrics, + [&unknown](const data_point& data_pt) { + unknown.push_back(data_pt); + }); + } else { + waiting_converter::nth_index<0>::type& host_serv_index = + _waiting.get<0>(); + std::vector> to_notify; + auto last_success = _extractors.begin(); + data_point::extract_data_points(metrics, [this, &unknown, &last_success, + &host_serv_index, &to_notify]( + const data_point& data_pt) { + bool data_point_known = false; + // we try all extractors and we begin with the last which has + // achieved to extract host + for (unsigned tries = 0; tries < _extractors.size(); ++tries) { + host_serv_metric hostservmetric = + last_success->second->extract_host_serv_metric(data_pt); - // if (!hostservmetric.host.empty()) { - // _fifo.add_data_point(hostservmetric.host, hostservmetric.service, - // hostservmetric.metric, data_pt); + if (!hostservmetric.host.empty()) { // match + _fifo.add_data_point(hostservmetric.host, hostservmetric.service, + hostservmetric.metric, data_pt); - // auto waiting = host_serv_index.equal_range( - // host_serv{hostservmetric.host, hostservmetric.service}); - // while (waiting.first != waiting.second) { - // to_notify.push_back(*waiting.first); - // waiting.first = host_serv_index.erase(waiting.first); - // } - // data_point_known = true; - // break; - // } - // ++last_success; - // if (last_success == _extractors.end()) { - // last_success = _extractors.begin(); - // } - // } - // if (!data_point_known) { - // unknown.push_back(data_pt); // unknown metric => forward to broker - // } - // }); - // SPDLOG_LOGGER_TRACE(_logger, "fifos:{}", _fifo); - // // we wait that all request datas have been computed to give us more - // // chance of converter success - // for (auto to_callback : to_notify) { - // if (!to_callback->async_build_result_from_metrics( - // _fifo)) { // not enough data => repush in _waiting - // _waiting.insert(to_callback); - // } - // } - // SPDLOG_LOGGER_TRACE(_logger, "fifos:{}", _fifo); - // } + // converters waiting this metric? + auto waiting = host_serv_index.equal_range( + host_serv{hostservmetric.host, hostservmetric.service}); + while (waiting.first != waiting.second) { + to_notify.push_back(*waiting.first); + waiting.first = host_serv_index.erase(waiting.first); + } + data_point_known = true; + break; + } + // no match => we try next extractor + ++last_success; + if (last_success == _extractors.end()) { + last_success = _extractors.begin(); + } + } + if (!data_point_known) { + unknown.push_back(data_pt); // unknown metric => forward to broker + } + }); + SPDLOG_LOGGER_TRACE(_logger, "fifos:{}", _fifo); + // we wait that all request datas have been computed to give us more + // chance of converter success + for (auto to_callback : to_notify) { + if (!to_callback->async_build_result_from_metrics( + _fifo)) { // not enough data => repush in _waiting + _waiting.insert(to_callback); + } + } + SPDLOG_LOGGER_TRACE(_logger, "fifos:{}", _fifo); + } } if (!unknown.empty()) { SPDLOG_LOGGER_TRACE(_logger, "{} unknown data_points", unknown.size()); @@ -250,30 +355,35 @@ void open_telemetry::_start_second_timer() { * */ void open_telemetry::_second_timer_handler() { - // std::vector> to_notify; + std::vector> to_notify; { std::lock_guard l(_protect); std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); - // waiting_converter::nth_index<1>::type& expiry_index = _waiting.get<1>(); - // while (!_waiting.empty()) { - // auto oldest = expiry_index.begin(); - // if ((*oldest)->get_time_out() > now) { - // break; - // } - // to_notify.push_back(*oldest); - // expiry_index.erase(oldest); - // } + waiting_converter::nth_index<1>::type& expiry_index = _waiting.get<1>(); + while (!_waiting.empty()) { + auto oldest = expiry_index.begin(); + if ((*oldest)->get_time_out() > now) { + break; + } + to_notify.push_back(*oldest); + expiry_index.erase(oldest); + } } // notify all timeout - // for (std::shared_ptr to_not : to_notify) { - // SPDLOG_LOGGER_DEBUG(_logger, "time out: {}", *to_not); - // to_not->async_time_out(); - // } + for (std::shared_ptr to_not : to_notify) { + SPDLOG_LOGGER_DEBUG(_logger, "time out: {}", *to_not); + to_not->async_time_out(); + } _start_second_timer(); } +/** + * @brief unknown metrics are directly forwarded to broker + * + * @param unknown + */ void open_telemetry::_forward_to_broker( const std::vector& unknown) {} diff --git a/engine/modules/opentelemetry/src/otl_converter.cc b/engine/modules/opentelemetry/src/otl_converter.cc new file mode 100644 index 00000000000..3ae70c6aee8 --- /dev/null +++ b/engine/modules/opentelemetry/src/otl_converter.cc @@ -0,0 +1,173 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#include "com/centreon/engine/globals.hh" +#include "com/centreon/exceptions/msg_fmt.hh" + +#include "data_point_fifo_container.hh" +#include "otl_converter.hh" + +#include "absl/flags/commandlineflag.h" +#include "absl/strings/str_split.h" + +using namespace com::centreon::engine::modules::opentelemetry; + +/** + * @brief create a otl_converter_config from a command line + * first field identify type of config + * Example: + * @code {.c++} + * std::shared_ptr conf = + * otl_converter_config::load("nagios_telegraf"); + * @endcode + * + * @param cmd_line + * @return std::shared_ptr + * @throw if cmd_line can't be parsed + */ +/****************************************************************** + * otl_converter base + ******************************************************************/ +otl_converter::otl_converter(const std::string& cmd_line, + uint64_t command_id, + const host& host, + const service* service, + std::chrono::system_clock::time_point timeout, + commands::otel::result_callback&& handler, + const std::shared_ptr& logger) + : _cmd_line(cmd_line), + _command_id(command_id), + _host_serv{host.name(), service ? service->description() : ""}, + _timeout(timeout), + _callback(handler), + _logger(logger) {} + +bool otl_converter::sync_build_result_from_metrics( + data_point_fifo_container& data_pts, + commands::result& res) { + std::lock_guard l(data_pts); + auto& fifos = data_pts.get_fifos(_host_serv.first, _host_serv.second); + if (!fifos.empty() && _build_result_from_metrics(fifos, res)) { + return true; + } + // no data available + return false; +} + +/** + * @brief called when data is received from otel + * clients + * + * @param data_pts + * @return true otl_converter has managed to create check result + * @return false + */ +bool otl_converter::async_build_result_from_metrics( + data_point_fifo_container& data_pts) { + commands::result res; + bool success = false; + { + std::lock_guard l(data_pts); + auto& fifos = data_pts.get_fifos(_host_serv.first, _host_serv.second); + success = !fifos.empty() && _build_result_from_metrics(fifos, res); + } + if (success) { + _callback(res); + } + return success; +} + +/** + * @brief called when no data is received before + * _timeout + * + */ +void otl_converter::async_time_out() { + commands::result res; + res.exit_status = process::timeout; + res.command_id = _command_id; + _callback(res); +} + +/** + * @brief create a otl_converter_config from a command line + * first field identify type of config + * Example: + * @code {.c++} + * std::shared_ptr converter = + * otl_converter::create("nagios_telegraf --fifo_depth=5", 5, *host, serv, + * timeout_point, [](const commads::result &res){}, _logger); + * @endcode + * + * @param cmd_line + * @param command_id + * @param host + * @param service + * @param timeout + * @param handler + * @return std::shared_ptr + */ +std::shared_ptr otl_converter::create( + const std::string& cmd_line, + uint64_t command_id, + const host& host, + const service* service, + std::chrono::system_clock::time_point timeout, + commands::otel::result_callback&& handler, + const std::shared_ptr& logger) { + // type of the converter is the first field + size_t sep_pos = cmd_line.find(' '); + std::string conf_type = + sep_pos == std::string::npos ? cmd_line : cmd_line.substr(0, sep_pos); + boost::trim(conf_type); + // NEXT PR + // if (conf_type == "nagios_telegraf") { + // return std::make_shared( + // cmd_line, command_id, host, service, timeout, std::move(handler), + // logger); + // } else { + SPDLOG_LOGGER_ERROR(config_logger, "unknown converter type:{}", conf_type); + throw exceptions::msg_fmt("unknown converter type:{}", conf_type); + // } +} + +/** + * @brief debug infos + * + * @param output string to log + */ +void otl_converter::dump(std::string& output) const { + output = fmt::format( + "host:{}, service:{}, command_id={}, timeout:{} cmdline: \"{}\"", + _host_serv.first, _host_serv.second, _command_id, _timeout, _cmd_line); +} + +/** + * @brief remove converter_type from command_line + * + * @param cmd_line exemple nagios_telegraf + * @return std::string + */ +std::string otl_converter::remove_converter_type(const std::string& cmd_line) { + size_t sep_pos = cmd_line.find(' '); + std::string params = + sep_pos == std::string::npos ? "" : cmd_line.substr(sep_pos + 1); + + boost::trim(params); + return params; +} diff --git a/engine/src/anomalydetection.cc b/engine/src/anomalydetection.cc index 3d73cf162d5..822e06ea15a 100644 --- a/engine/src/anomalydetection.cc +++ b/engine/src/anomalydetection.cc @@ -1,20 +1,19 @@ /** - * Copyright 2020-2021 Centreon + * Copyright 2024 Centreon * - * This file is part of Centreon Engine. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Centreon Engine is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License version 2 - * as published by the Free Software Foundation. + * http://www.apache.org/licenses/LICENSE-2.0 * - * Centreon Engine is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. * - * You should have received a copy of the GNU General Public License - * along with Centreon Engine. If not, see - * . + * For more information : contact@centreon.com */ #include "com/centreon/engine/anomalydetection.hh" @@ -174,6 +173,12 @@ class cancellable_command : public command { nagios_macros& macros, uint32_t timeout, result& res) override; + + void register_host_serv(const std::string& host, + const std::string& service_description) override; + + void unregister_host_serv(const std::string& host, + const std::string& service_description) override; }; const std::string cancellable_command::_empty; @@ -244,6 +249,31 @@ void cancellable_command::set_command_line( "cancellable_command::set_command_line: original command no set"); } } + +/** + * @brief notify a command of host service owner + * + * @param host + * @param service_description empty for host command + */ +void cancellable_command::register_host_serv( + const std::string& host, + const std::string& service_description) { + _original_command->register_host_serv(host, service_description); +}; + +/** + * @brief notify a command that a service is not using it anymore + * + * @param host + * @param service_description empty for host command + */ +void cancellable_command::unregister_host_serv( + const std::string& host, + const std::string& service_description) { + _original_command->unregister_host_serv(host, service_description); +}; + } // namespace commands } // namespace com::centreon::engine diff --git a/engine/src/check_result.cc b/engine/src/check_result.cc index 07f62edc88c..d94e2f4fe2e 100644 --- a/engine/src/check_result.cc +++ b/engine/src/check_result.cc @@ -1,5 +1,5 @@ /** - * Copyright 2011 - 2020 Centreon (https://www.centreon.com/) + * Copyright 2011 - 2024 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,6 +27,7 @@ using namespace com::centreon::engine; check_result::check_result() : _object_check_type{check_source::service_check}, + _command_id(0), _notifier{nullptr}, _check_type(checkable::check_type::check_passive), _check_options{0}, @@ -51,6 +52,7 @@ check_result::check_result(enum check_source object_check_type, int return_code, std::string output) : _object_check_type{object_check_type}, + _command_id(0), _notifier{notifier}, _check_type(check_type), _check_options{check_options}, @@ -118,3 +120,16 @@ void check_result::set_latency(double latency) { void check_result::set_check_options(unsigned check_options) { _check_options = check_options; } + +namespace com::centreon::engine { + +std::ostream& operator<<(std::ostream& stream, const check_result& res) { + stream << "command_id=" << res.get_command_id() + << " timeout=" << res.get_early_timeout() + << " ok=" << res.get_exited_ok() + << " ret_code=" << res.get_return_code() + << " output:" << res.get_output(); + return stream; +} + +} // namespace com::centreon::engine diff --git a/engine/src/checks/checker.cc b/engine/src/checks/checker.cc index 56c412ef5cf..44e57c0b3f2 100644 --- a/engine/src/checks/checker.cc +++ b/engine/src/checks/checker.cc @@ -1,21 +1,19 @@ /** - * Copyright 1999-2010 Ethan Galstad - * Copyright 2011-2024 Centreon + * Copyright 2024 Centreon * - * This file is part of Centreon Engine. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Centreon Engine is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License version 2 - * as published by the Free Software Foundation. + * http://www.apache.org/licenses/LICENSE-2.0 * - * Centreon Engine is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. * - * You should have received a copy of the GNU General Public License - * along with Centreon Engine. If not, see - * . + * For more information : contact@centreon.com */ #include "com/centreon/engine/checks/checker.hh" @@ -398,6 +396,7 @@ void checker::finished(commands::result const& res) noexcept { result->set_exited_ok(res.exit_status == process::normal || res.exit_status == process::timeout); result->set_output(res.output); + result->set_command_id(res.command_id); // Queue check result. lock.lock(); diff --git a/engine/src/commands/CMakeLists.txt b/engine/src/commands/CMakeLists.txt index a0c47ab186e..1ac102e9129 100644 --- a/engine/src/commands/CMakeLists.txt +++ b/engine/src/commands/CMakeLists.txt @@ -1,21 +1,20 @@ -## -## Copyright 2011-2019 Centreon -## -## This file is part of Centreon Scheduler. -## -## Centreon Scheduler is free software: you can redistribute it and/or -## modify it under the terms of the GNU General Public License version 2 -## as published by the Free Software Foundation. -## -## Centreon Scheduler is distributed in the hope that it will be useful, -## but WITHOUT ANY WARRANTY; without even the implied warranty of -## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -## General Public License for more details. -## -## You should have received a copy of the GNU General Public License -## along with Centreon Scheduler. If not, see -## . -## +# +# Copyright 2024 Centreon +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may not +# use this file except in compliance with the License. You may obtain a copy of +# the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations under +# the License. +# +# For more information : contact@centreon.com +# # Set directories. set(SRC_DIR "${SRC_DIR}/commands") @@ -32,6 +31,7 @@ set( "${SRC_DIR}/connector.cc" "${SRC_DIR}/environment.cc" "${SRC_DIR}/forward.cc" + "${SRC_DIR}/otel_command.cc" "${SRC_DIR}/otel_interface.cc" "${SRC_DIR}/processing.cc" "${SRC_DIR}/raw.cc" diff --git a/engine/src/commands/command.cc b/engine/src/commands/command.cc index 32ed393ead5..134c459a8d5 100644 --- a/engine/src/commands/command.cc +++ b/engine/src/commands/command.cc @@ -1,20 +1,19 @@ /** - * Copyright 2011-2013 Merethis + * Copyright 2024 Centreon * - * This file is part of Centreon Engine. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Centreon Engine is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License version 2 - * as published by the Free Software Foundation. + * http://www.apache.org/licenses/LICENSE-2.0 * - * Centreon Engine is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. * - * You should have received a copy of the GNU General Public License - * along with Centreon Engine. If not, see - * . + * For more information : contact@centreon.com */ #include "com/centreon/engine/commands/command.hh" @@ -38,11 +37,16 @@ command_map commands::command::commands; * @param[in] name The command name. * @param[in] command_line The command line. * @param[in] listener The command listener to catch events. + * @param[in] cmd_type object type (exec, forward, raw, connector, otel) */ commands::command::command(const std::string& name, const std::string& command_line, - command_listener* listener) - : _command_line(command_line), _listener{listener}, _name(name) { + command_listener* listener, + e_type cmd_type) + : _type(cmd_type), + _command_line(command_line), + _listener{listener}, + _name(name) { if (_name.empty()) throw engine_error() << "Could not create a command with an empty name"; if (_listener) { diff --git a/engine/src/commands/connector.cc b/engine/src/commands/connector.cc index a017fe32ecb..d95dc58ee6c 100644 --- a/engine/src/commands/connector.cc +++ b/engine/src/commands/connector.cc @@ -1,5 +1,5 @@ /** - * Copyright 2011-2013,2015,2019 Centreon (https://www.centreon.com/) + * Copyright 2011-2013,2015,2019,2024 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,7 +55,7 @@ connector_map connector::connectors; connector::connector(const std::string& connector_name, const std::string& connector_line, command_listener* listener) - : command(connector_name, connector_line, listener), + : command(connector_name, connector_line, listener, e_type::connector), process_listener(), _is_running(false), _query_quit_ok(false), diff --git a/engine/src/commands/forward.cc b/engine/src/commands/forward.cc index a2fcc5768ef..ad7eafa339c 100644 --- a/engine/src/commands/forward.cc +++ b/engine/src/commands/forward.cc @@ -1,21 +1,20 @@ /** -* Copyright 2011-2013 Merethis -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/engine/commands/forward.hh" #include "com/centreon/engine/exceptions/error.hh" @@ -35,8 +34,8 @@ using namespace com::centreon::engine::commands; */ forward::forward(std::string const& command_name, std::string const& command_line, - std::shared_ptr& cmd) - : command(command_name, command_line, nullptr), + const std::shared_ptr& cmd) + : command(command_name, command_line, nullptr, e_type::forward), _s_command(cmd), _command(cmd.get()) { if (_name.empty()) @@ -80,3 +79,25 @@ void forward::run(std::string const& processed_cmd, result& res) { _command->run(processed_cmd, macros, timeout, res); } + +/** + * @brief notify a command of host service owner + * + * @param host + * @param service_description + */ +void forward::register_host_serv(const std::string& host, + const std::string& service_description) { + _command->register_host_serv(host, service_description); +} + +/** + * @brief notify a command that a service is not using it anymore + * + * @param host + * @param service_description + */ +void forward::unregister_host_serv(const std::string& host, + const std::string& service_description) { + _command->unregister_host_serv(host, service_description); +} diff --git a/engine/src/commands/otel_command.cc b/engine/src/commands/otel_command.cc new file mode 100644 index 00000000000..ae0e70b94f2 --- /dev/null +++ b/engine/src/commands/otel_command.cc @@ -0,0 +1,314 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#include "com/centreon/engine/commands/otel_command.hh" +#include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" + +using namespace com::centreon::engine::commands; +using log_v2 = com::centreon::common::log_v2::log_v2; + +/** + * @brief static list of all otel_command + * + */ +absl::flat_hash_map> + otel_command::_commands; + +/** + * @brief create an otel_command + * + * @param connector_name + * @param cmd_line + * @param listener + */ +void otel_command::create(const std::string& connector_name, + const std::string& cmd_line, + commands::command_listener* listener) { + std::shared_ptr cmd( + std::make_shared(connector_name, cmd_line, listener)); + auto iter_res = _commands.emplace(connector_name, cmd); + if (!iter_res.second) { + iter_res.first->second = cmd; + } +} + +/** + * @brief remove otel command from static list _commands + * + * @param connector_name + * @return true + * @return false + */ +bool otel_command::remove(const std::string& connector_name) { + return _commands.erase(connector_name); +} + +/** + * @brief update open telemetry extractor + * + * @param connector_name + * @param cmd_line new command line + * @return true the otel command was found and hist update method was called + * @return false the otel command doesn't exist + */ +bool otel_command::update(const std::string& connector_name, + const std::string& cmd_line) { + auto search = _commands.find(connector_name); + if (search == _commands.end()) { + return false; + } + search->second->update(cmd_line); + return true; +} + +/** + * @brief get otel command from connector name + * + * @param connector_name + * @return std::shared_ptr + */ +std::shared_ptr otel_command::get_otel_command( + const std::string& connector_name) { + auto search = _commands.find(connector_name); + return search != _commands.end() ? search->second + : std::shared_ptr(); +} + +/** + * @brief erase all otel commands + * + */ +void otel_command::clear() { + _commands.clear(); +} + +/** + * @brief to call once otel module have been loaded + * + */ +void otel_command::init_all() { + for (auto& to_init : _commands) { + to_init.second->init(); + } +} + +/** + * @brief to call after otel module unload + * + */ +void otel_command::reset_all_extractor() { + for (auto& to_init : _commands) { + to_init.second->reset_extractor(); + } +} + +/** + * @brief Construct a new otel command::otel command object + * at engine startup, otel module is not yet loaded + * So we can't init some members + * + * @param connector_name + * @param cmd_line + * @param listener + */ +otel_command::otel_command(const std::string& connector_name, + const std::string& cmd_line, + commands::command_listener* listener) + : command(connector_name, cmd_line, listener, e_type::otel), + _host_serv_list(std::make_shared()), + _logger(log_v2::instance().get(log_v2::OTEL)) { + init(); +} + +/** + * @brief + * + * @param cmd_line + */ +void otel_command::update(const std::string& cmd_line) { + if (get_command_line() == cmd_line) { + return; + } + set_command_line(cmd_line); + init(); +} + +/** + * @brief asynchronous check + * this use the engine callback engine, so there is not callback passed in + * parameter, we use update_result_cache and _listener->finished instead + * @param processed_cmd + * @param macros + * @param timeout + * @param to_push_to_checker + * @param caller + * @return uint64_t + */ +uint64_t otel_command::run(const std::string& processed_cmd, + nagios_macros& macros, + uint32_t timeout, + const check_result::pointer& to_push_to_checker, + const void* caller) { + std::shared_ptr otel = + otel::open_telemetry_base::instance(); + + if (!otel) { + SPDLOG_LOGGER_ERROR(_logger, + "open telemetry module not loaded for connector: {}", + get_name()); + throw exceptions::msg_fmt( + "open telemetry module not loaded for connector: {}", get_name()); + } + + uint64_t command_id(get_uniq_id()); + + if (!gest_call_interval(command_id, to_push_to_checker, caller)) { + return command_id; + } + + SPDLOG_LOGGER_TRACE(_logger, + "otel_command::async_run: connector='{}', command_id={}, " + "cmd='{}', timeout={}", + _name, command_id, processed_cmd, timeout); + + result res; + bool res_available = otel->check( + processed_cmd, command_id, macros, timeout, res, + [me = shared_from_this(), command_id](const result& async_res) { + SPDLOG_LOGGER_TRACE( + me->_logger, "otel_command async_run callback: connector='{}' {}", + me->_name, async_res); + me->update_result_cache(command_id, async_res); + if (me->_listener) { + (me->_listener->finished)(async_res); + } + }); + + if (res_available) { + SPDLOG_LOGGER_TRACE(_logger, + "otel_command data available : connector='{}', " + "cmd='{}', {}", + _name, processed_cmd, res); + update_result_cache(command_id, res); + if (_listener) { + (_listener->finished)(res); + } + } + + return command_id; +} + +/** + * @brief emulate an synchronous check run + * as all is asynchronous, we use a condition variable to emulate synchronous + * mode + * + * @param processed_cmd + * @param macros + * @param timeout timeout in seconds + * @param res check result + */ +void otel_command::run(const std::string& processed_cmd, + nagios_macros& macros, + uint32_t timeout, + result& res) { + std::shared_ptr otel = + otel::open_telemetry_base::instance(); + if (!otel) { + SPDLOG_LOGGER_ERROR(_logger, + "open telemetry module not loaded for connector: {}", + get_name()); + throw exceptions::msg_fmt( + "open telemetry module not loaded for connector: {}", get_name()); + } + + uint64_t command_id(get_uniq_id()); + + SPDLOG_LOGGER_TRACE(_logger, + "otel_command::sync_run: connector='{}', cmd='{}', " + "command_id={}, timeout={}", + _name, processed_cmd, command_id, timeout); + + std::condition_variable cv; + std::mutex cv_m; + + bool res_available = otel->check(processed_cmd, command_id, macros, timeout, + res, [&res, &cv](const result& async_res) { + res = async_res; + cv.notify_one(); + }); + + // no data_point available => wait util available or timeout + if (!res_available) { + std::unique_lock l(cv_m); + cv.wait(l); + } + SPDLOG_LOGGER_TRACE( + _logger, "otel_command::end sync_run: connector='{}', cmd='{}', {}", + _name, processed_cmd, res); +} + +/** + * @brief when this object is created, otel module may not have been loaded, so + * we have to init later this method is called by constructor and is effective + * if we are not in startup otherwise, it's called by open_telemetry object at + * otel module loading + * + */ +void otel_command::init() { + if (!_extractor) { + std::shared_ptr otel = + otel::open_telemetry_base::instance(); + if (otel) { + _extractor = otel->create_extractor(get_command_line(), _host_serv_list); + } + } +} + +/** + * @brief reset _extractor attribute, called when otel module is unloaded + * + */ +void otel_command::reset_extractor() { + _extractor.reset(); +} + +/** + * @brief add a host service allowed by the extractor of the connector + * + * @param host + * @param service_description empty if host command + */ +void otel_command::register_host_serv(const std::string& host, + const std::string& service_description) { + _host_serv_list->register_host_serv(host, service_description); +} + +/** + * @brief remove a host service from host service allowed by the extractor of + * the connector + * + * @param host + * @param service_description empty if host command + */ +void otel_command::unregister_host_serv( + const std::string& host, + const std::string& service_description) { + _host_serv_list->unregister_host_serv(host, service_description); +} diff --git a/engine/src/commands/otel_interface.cc b/engine/src/commands/otel_interface.cc index 45d64db7270..6e733c75c24 100644 --- a/engine/src/commands/otel_interface.cc +++ b/engine/src/commands/otel_interface.cc @@ -30,14 +30,14 @@ std::shared_ptr void host_serv_list::register_host_serv( const std::string& host, const std::string& service_description) { - std::lock_guard l(_data_m); + absl::WriterMutexLock l(&_data_m); _data[host].insert(service_description); } void host_serv_list::unregister_host_serv( const std::string& host, const std::string& service_description) { - std::lock_guard l(_data_m); + absl::WriterMutexLock l(&_data_m); auto host_search = _data.find(host); if (host_search != _data.end()) { host_search->second.erase(service_description); @@ -47,9 +47,17 @@ void host_serv_list::unregister_host_serv( } } +/** + * @brief test if a host serv pair is contained in list + * + * @param host + * @param service_description + * @return true found + * @return false not found + */ bool host_serv_list::is_allowed(const std::string& host, const std::string& service_description) const { - std::lock_guard l(_data_m); + absl::ReaderMutexLock l(&_data_m); auto host_search = _data.find(host); if (host_search != _data.end()) { return host_search->second.contains(service_description); diff --git a/engine/src/commands/raw.cc b/engine/src/commands/raw.cc index 50e195545a1..666da9e8bb1 100644 --- a/engine/src/commands/raw.cc +++ b/engine/src/commands/raw.cc @@ -1,20 +1,19 @@ /** - * Copyright 2011-2015,2017 Centreon + * Copyright 2024 Centreon * - * This file is part of Centreon Engine. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Centreon Engine is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License version 2 - * as published by the Free Software Foundation. + * http://www.apache.org/licenses/LICENSE-2.0 * - * Centreon Engine is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. * - * You should have received a copy of the GNU General Public License - * along with Centreon Engine. If not, see - * . + * For more information : contact@centreon.com */ #include "com/centreon/engine/commands/raw.hh" @@ -39,7 +38,7 @@ using namespace com::centreon::engine::commands; raw::raw(std::string const& name, std::string const& command_line, command_listener* listener) - : command(name, command_line, listener), process_listener() { + : command(name, command_line, listener, e_type::raw), process_listener() { if (_command_line.empty()) throw engine_error() << "Could not create '" << _name << "' command: command line is empty"; diff --git a/engine/src/commands/result.cc b/engine/src/commands/result.cc index f263231e5f5..eba88d3f108 100644 --- a/engine/src/commands/result.cc +++ b/engine/src/commands/result.cc @@ -1,5 +1,5 @@ /** - * Copyright 2011 - 2013, 2020 Centreon (https://www.centreon.com/) + * Copyright 2011 - 2013, 2024 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -108,12 +108,26 @@ void result::_internal_copy(result const& right) { output = right.output; } +static const char* status_to_string(com::centreon::process::status status) { + switch (status) { + case com::centreon::process::status::normal: + return "normal"; + case com::centreon::process::status::crash: + return "crash"; + case com::centreon::process::status::timeout: + return "timeout"; + default: + return "unknown status"; + } +} + namespace com::centreon::engine::commands { std::ostream& operator<<(std::ostream& s, const result& to_dump) { - s << "start_time=" << to_dump.start_time << ", end_time=" << to_dump.end_time + s << "command_id=" << to_dump.command_id + << " start_time=" << to_dump.start_time << ", end_time=" << to_dump.end_time << ", exit_code=" << to_dump.exit_code - << ", exit_status=" << to_dump.exit_status << ", output='" << to_dump.output - << '\''; + << ", exit_status=" << status_to_string(to_dump.exit_status) << ", output='" + << to_dump.output << '\''; return s; } diff --git a/engine/src/configuration/applier/command.cc b/engine/src/configuration/applier/command.cc index 48275d2ed3e..bd875742b73 100644 --- a/engine/src/configuration/applier/command.cc +++ b/engine/src/configuration/applier/command.cc @@ -22,6 +22,7 @@ #include "com/centreon/engine/checks/checker.hh" #include "com/centreon/engine/commands/connector.hh" #include "com/centreon/engine/commands/forward.hh" +#include "com/centreon/engine/commands/otel_command.hh" #include "com/centreon/engine/commands/raw.hh" #include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/exceptions/error.hh" @@ -54,12 +55,12 @@ void applier::command::add_object(configuration::command const& obj) { // Add command to the global configuration set. config->commands().insert(obj); - if (obj.connector().empty()) { std::shared_ptr raw = std::make_shared( obj.command_name(), obj.command_line(), &checks::checker::instance()); commands::command::commands[raw->get_name()] = raw; - } else { + } else { // connector or otel, we search it to create the forward command + // that will use it connector_map::iterator found_con{ commands::connector::connectors.find(obj.connector())}; if (found_con != commands::connector::connectors.end() && @@ -68,10 +69,20 @@ void applier::command::add_object(configuration::command const& obj) { std::make_shared( obj.command_name(), obj.command_line(), found_con->second)}; commands::command::commands[forward->get_name()] = forward; - } else - throw engine_error() << "Could not register command '" - << obj.command_name() << "': unable to find '" - << obj.connector() << "'"; + } else { + std::shared_ptr otel_cmd = + commands::otel_command::get_otel_command(obj.connector()); + if (otel_cmd) { + std::shared_ptr forward{ + std::make_shared(obj.command_name(), + obj.command_line(), otel_cmd)}; + commands::command::commands[forward->get_name()] = forward; + } else { + throw engine_error() + << "Could not register command '" << obj.command_name() + << "': unable to find '" << obj.connector() << "'"; + } + } } } @@ -137,10 +148,20 @@ void applier::command::modify_object(configuration::command const& obj) { std::make_shared( obj.command_name(), obj.command_line(), found_con->second)}; commands::command::commands[forward->get_name()] = forward; - } else - throw engine_error() << "Could not register command '" - << obj.command_name() << "': unable to find '" - << obj.connector() << "'"; + } else { + std::shared_ptr otel_cmd = + commands::otel_command::get_otel_command(obj.connector()); + if (otel_cmd) { + std::shared_ptr forward{ + std::make_shared(obj.command_name(), + obj.command_line(), otel_cmd)}; + commands::command::commands[forward->get_name()] = forward; + } else { + throw engine_error() + << "Could not register command '" << obj.command_name() + << "': unable to find '" << obj.connector() << "'"; + } + } } // Notify event broker. timeval tv(get_broker_timestamp(NULL)); @@ -192,7 +213,9 @@ void applier::command::resolve_object(configuration::command const& obj) { if (!obj.connector().empty()) { connector_map::iterator found{ commands::connector::connectors.find(obj.connector())}; - if (found == commands::connector::connectors.end() || !found->second) - throw engine_error() << "unknow command " << obj.connector(); + if (found == commands::connector::connectors.end() || !found->second) { + if (!commands::otel_command::get_otel_command(obj.connector())) + throw engine_error() << "unknow command " << obj.connector(); + } } } diff --git a/engine/src/configuration/applier/connector.cc b/engine/src/configuration/applier/connector.cc index ca35ccefea0..5c965919c4e 100644 --- a/engine/src/configuration/applier/connector.cc +++ b/engine/src/configuration/applier/connector.cc @@ -18,15 +18,19 @@ */ #include "com/centreon/engine/commands/connector.hh" #include "com/centreon/engine/checks/checker.hh" +#include "com/centreon/engine/commands/otel_command.hh" #include "com/centreon/engine/configuration/applier/connector.hh" #include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" #include "com/centreon/engine/macros/misc.hh" #include "com/centreon/engine/macros/process.hh" +#include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon::engine::configuration; +constexpr std::string_view _otel_fake_exe("open_telemetry"); + /** * Add new connector. * @@ -48,9 +52,24 @@ void applier::connector::add_object(configuration::connector const& obj) { config->connectors().insert(obj); // Create connector. - auto cmd = std::make_shared( - obj.connector_name(), processed_cmd, &checks::checker::instance()); - commands::connector::connectors[obj.connector_name()] = cmd; + boost::trim(processed_cmd); + + // if executable connector path ends with open_telemetry, it's a fake + // opentelemetry connector + size_t end_path = processed_cmd.find(' '); + size_t otel_pos = processed_cmd.find(_otel_fake_exe); + + if (otel_pos < end_path) { + commands::otel_command::create( + obj.connector_name(), + boost::algorithm::trim_copy( + processed_cmd.substr(otel_pos + _otel_fake_exe.length())), + &checks::checker::instance()); + } else { + auto cmd = std::make_shared( + obj.connector_name(), processed_cmd, &checks::checker::instance()); + commands::connector::connectors[obj.connector_name()] = cmd; + } } /** @@ -82,27 +101,58 @@ void applier::connector::modify_object(configuration::connector const& obj) { throw(engine_error() << "Cannot modify non-existing connector '" << obj.connector_name() << "'"); - // Find connector object. - connector_map::iterator it_obj( - commands::connector::connectors.find(obj.key())); - if (it_obj == commands::connector::connectors.end()) - throw(engine_error() << "Could not modify non-existing " - << "connector object '" << obj.connector_name() - << "'"); - commands::connector* c(it_obj->second.get()); - - // Update the global configuration set. - config->connectors().erase(it_cfg); - config->connectors().insert(obj); - // Expand command line. nagios_macros* macros(get_global_macros()); std::string command_line; process_macros_r(macros, obj.connector_line(), command_line, 0); std::string processed_cmd(command_line); - // Set the new command line. - c->set_command_line(processed_cmd); + boost::trim(processed_cmd); + + // if executable connector path ends with open_telemetry, it's a fake + // opentelemetry connector + size_t end_path = processed_cmd.find(' '); + size_t otel_pos = processed_cmd.find(_otel_fake_exe); + + connector_map::iterator exist_connector( + commands::connector::connectors.find(obj.key())); + + if (otel_pos < end_path) { + std::string otel_cmdline = boost::algorithm::trim_copy( + processed_cmd.substr(otel_pos + _otel_fake_exe.length())); + + if (!commands::otel_command::update(obj.key(), processed_cmd)) { + // connector object become an otel fake connector + if (exist_connector != commands::connector::connectors.end()) { + commands::connector::connectors.erase(exist_connector); + commands::otel_command::create(obj.key(), processed_cmd, + &checks::checker::instance()); + } else { + throw com::centreon::exceptions::msg_fmt( + "unknown open telemetry command to update: {}", obj.key()); + } + } + } else { + if (exist_connector != commands::connector::connectors.end()) { + // Set the new command line. + exist_connector->second->set_command_line(processed_cmd); + } else { + // old otel_command => connector + if (commands::otel_command::remove(obj.key())) { + auto cmd = std::make_shared( + obj.connector_name(), processed_cmd, &checks::checker::instance()); + commands::connector::connectors[obj.connector_name()] = cmd; + + } else { + throw com::centreon::exceptions::msg_fmt( + "unknown connector to update: {}", obj.key()); + } + } + } + + // Update the global configuration set. + config->connectors().erase(it_cfg); + config->connectors().insert(obj); } /** @@ -124,6 +174,8 @@ void applier::connector::remove_object(configuration::connector const& obj) { commands::connector::connectors.erase(it); } + commands::otel_command::remove(obj.key()); + // Remove connector from the global configuration set. config->connectors().erase(obj); } diff --git a/engine/src/configuration/applier/state.cc b/engine/src/configuration/applier/state.cc index dcf62c66ff0..34b9c2d41f0 100644 --- a/engine/src/configuration/applier/state.cc +++ b/engine/src/configuration/applier/state.cc @@ -21,6 +21,7 @@ #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/commands/connector.hh" +#include "com/centreon/engine/commands/otel_command.hh" #include "com/centreon/engine/config.hh" #include "com/centreon/engine/configuration/applier/anomalydetection.hh" #include "com/centreon/engine/configuration/applier/command.hh" @@ -149,6 +150,7 @@ void applier::state::clear() { engine::hostgroup::hostgroups.clear(); engine::commands::command::commands.clear(); engine::commands::connector::connectors.clear(); + engine::commands::otel_command::clear(); engine::service::services.clear(); engine::service::services_by_id.clear(); engine::servicedependency::servicedependencies.clear(); @@ -187,6 +189,7 @@ applier::state::~state() noexcept { engine::hostgroup::hostgroups.clear(); engine::commands::command::commands.clear(); engine::commands::connector::connectors.clear(); + engine::commands::otel_command::clear(); engine::service::services.clear(); engine::service::services_by_id.clear(); engine::servicedependency::servicedependencies.clear(); diff --git a/engine/src/configuration/state.cc b/engine/src/configuration/state.cc index dc4b3ee4e82..2c5c833e402 100644 --- a/engine/src/configuration/state.cc +++ b/engine/src/configuration/state.cc @@ -1,5 +1,5 @@ /** - * Copyright 2011-2013,2015-2017, 2021-2024 Centreon + * Copyright 2024 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -298,6 +298,7 @@ void state::_init_setter() { SETTER(std::string const&, log_level_macros, "log_level_macros"); SETTER(std::string const&, log_level_process, "log_level_process"); SETTER(std::string const&, log_level_runtime, "log_level_runtime"); + SETTER(std::string const&, log_level_otl, "log_level_otl"); SETTER(std::string const&, use_timezone, "use_timezone"); SETTER(bool, use_true_regexp_matching, "use_true_regexp_matching"); SETTER(std::string const&, _set_comment_file, "xcddefault_comment_file"); @@ -436,6 +437,7 @@ static std::string const default_log_level_comments("error"); static std::string const default_log_level_macros("error"); static std::string const default_log_level_process("info"); static std::string const default_log_level_runtime("error"); +static std::string const default_log_level_otl("error"); static std::string const default_use_timezone(""); static bool const default_use_true_regexp_matching(false); static const std::string default_rpc_listen_address("localhost"); @@ -577,6 +579,7 @@ state::state() _log_level_macros(default_log_level_macros), _log_level_process(default_log_level_process), _log_level_runtime(default_log_level_runtime), + _log_level_otl(default_log_level_otl), _use_timezone(default_use_timezone), _use_true_regexp_matching(default_use_true_regexp_matching), _send_recovery_notifications_anyways(false) { @@ -760,6 +763,7 @@ state& state::operator=(state const& right) { _log_level_macros = right._log_level_macros; _log_level_process = right._log_level_process; _log_level_runtime = right._log_level_runtime; + _log_level_otl = right._log_level_otl; _use_timezone = right._use_timezone; _use_true_regexp_matching = right._use_true_regexp_matching; _send_recovery_notifications_anyways = @@ -927,6 +931,7 @@ bool state::operator==(state const& right) const noexcept { _log_level_macros == right._log_level_macros && _log_level_process == right._log_level_process && _log_level_runtime == right._log_level_runtime && + _log_level_otl == right._log_level_otl && _use_timezone == right._use_timezone && _use_true_regexp_matching == right._use_true_regexp_matching && _send_recovery_notifications_anyways == @@ -4217,6 +4222,27 @@ void state::log_level_runtime(std::string const& value) { throw engine_error() << "error wrong level setted for log_level_runtime"; } +/** + * Get log_level_otl value. + * + * @return The log_level_otl value. + */ +std::string const& state::log_level_otl() const noexcept { + return _log_level_otl; +} + +/** + * Set log_level_otl value. + * + * @param[in] value The new log_level_otl value. + */ +void state::log_level_otl(std::string const& value) { + if (log_v2::instance().contains_level(value)) + _log_level_otl = value; + else + throw engine_error() << "error wrong level setted for log_level_otl"; +} + /** * Get use_timezone value. * diff --git a/engine/src/host.cc b/engine/src/host.cc index 5f7a67444aa..4c96ea8b3fe 100644 --- a/engine/src/host.cc +++ b/engine/src/host.cc @@ -1,20 +1,19 @@ /** - * Copyright 2011 - 2024 Centreon + * Copyright 2024 Centreon * - * This file is part of Centreon Engine. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Centreon Engine is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License version 2 - * as published by the Free Software Foundation. + * http://www.apache.org/licenses/LICENSE-2.0 * - * Centreon Engine is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. * - * You should have received a copy of the GNU General Public License - * along with Centreon Engine. If not, see - * . + * For more information : contact@centreon.com */ #include "com/centreon/engine/host.hh" @@ -300,6 +299,13 @@ host::host(uint64_t host_id, (flap_detection_on_up > 0 ? up : 0)); } +host::~host() { + std::shared_ptr cmd = get_check_command_ptr(); + if (cmd) { + cmd->unregister_host_serv(name(), ""); + } +} + uint64_t host::host_id() const { return _id; } @@ -308,6 +314,25 @@ void host::set_host_id(uint64_t id) { _id = id; } +/** + * @brief change name of the host + * + * @param new_name + */ +void host::set_name(const std::string& new_name) { + if (new_name == name()) { + return; + } + std::shared_ptr cmd = get_check_command_ptr(); + if (cmd) { + cmd->unregister_host_serv(name(), ""); + } + notifier::set_name(new_name); + if (cmd) { + cmd->register_host_serv(name(), ""); + } +} + void host::add_child_host(host* child) { // Make sure we have the data we need. if (!child) @@ -1216,7 +1241,9 @@ int host::handle_async_check_result_3x( struct timeval end_time_hires; engine_logger(dbg_functions, basic) << "handle_async_host_check_result_3x()"; - SPDLOG_LOGGER_TRACE(functions_logger, "handle_async_host_check_result_3x()"); + SPDLOG_LOGGER_TRACE(functions_logger, + "handle_async_host_check_result_3x() host {} res:{}", + name(), queued_check_result); /* get the current time */ time_t current_time = std::time(nullptr); @@ -1761,10 +1788,8 @@ int host::run_async_check(int check_options, // Get current host macros. nagios_macros* macros(get_global_macros()); - grab_host_macros_r(macros, this); - std::string tmp; - get_raw_command_line_r(macros, get_check_command_ptr(), - check_command().c_str(), tmp, 0); + + std::string processed_cmd = get_check_command_line(macros); // Time to start command. gettimeofday(&start_time, nullptr); @@ -1780,10 +1805,6 @@ int host::run_async_check(int check_options, // Set the execution flag. set_is_executing(true); - // Get command object. - commands::command* cmd = get_check_command_ptr().get(); - std::string processed_cmd(cmd->process_cmd(macros)); - // Send event broker. broker_host_check(NEBTYPE_HOSTCHECK_INITIATE, this, checkable::check_active, processed_cmd.c_str(), nullptr); @@ -1835,8 +1856,9 @@ int host::run_async_check(int check_options, retry = false; try { // Run command. - cmd->run(processed_cmd, *macros, config->host_check_timeout(), - check_result_info); + get_check_command_ptr()->run(processed_cmd, *macros, + config->host_check_timeout(), + check_result_info); } catch (com::centreon::exceptions::interruption const& e) { retry = true; } catch (std::exception const& e) { @@ -4020,3 +4042,37 @@ timeperiod* host::get_notification_timeperiod() const { /* if the service has no notification period, inherit one from the host */ return get_notification_period_ptr(); } + +/** + * @brief update check command + * + * @param cmd + */ +void host::set_check_command_ptr( + const std::shared_ptr& cmd) { + std::shared_ptr old = get_check_command_ptr(); + if (cmd == old) { + return; + } + + if (old) { + old->unregister_host_serv(name(), ""); + } + notifier::set_check_command_ptr(cmd); + if (cmd) { + cmd->register_host_serv(name(), ""); + } +} + +/** + * @brief calculate final check command with macros replaced + * + * @return std::string + */ +std::string host::get_check_command_line(nagios_macros* macros) { + grab_host_macros_r(macros, this); + std::string tmp; + get_raw_command_line_r(macros, get_check_command_ptr(), + check_command().c_str(), tmp, 0); + return get_check_command_ptr()->process_cmd(macros); +} diff --git a/engine/src/service.cc b/engine/src/service.cc index 4280f603652..bbf1ea09fb0 100644 --- a/engine/src/service.cc +++ b/engine/src/service.cc @@ -158,8 +158,10 @@ service::service(const std::string& hostname, } service::~service() noexcept { - if (get_check_command_ptr()) { - get_check_command_ptr()->remove_caller(this); + std::shared_ptr cmd = get_check_command_ptr(); + if (cmd) { + cmd->remove_caller(this); + cmd->unregister_host_serv(_hostname, description()); } } @@ -966,8 +968,23 @@ uint64_t service::service_id() const { return _service_id; } +/** + * @brief update hostname and associate command + * + * @param name + */ void service::set_hostname(const std::string& name) { + if (_hostname == name) { + return; + } + std::shared_ptr cmd = get_check_command_ptr(); + if (cmd) { + cmd->unregister_host_serv(_hostname, description()); + } _hostname = name; + if (cmd) { + cmd->register_host_serv(_hostname, description()); + } } /** @@ -979,6 +996,26 @@ const std::string& service::get_hostname() const { return _hostname; } +/** + * @brief update service name + * update also associate command + * + * @param desc + */ +void service::set_name(std::string const& desc) { + if (desc == name()) { + return; + } + std::shared_ptr cmd = get_check_command_ptr(); + if (cmd) { + cmd->unregister_host_serv(_hostname, name()); + } + notifier::set_name(desc); + if (cmd) { + cmd->register_host_serv(_hostname, name()); + } +} + void service::set_description(const std::string& desc) { set_name(desc); } @@ -2615,11 +2652,7 @@ int service::run_async_check_local(int check_options, // Get current host and service macros. nagios_macros* macros(get_global_macros()); - grab_host_macros_r(macros, svc->get_host_ptr()); - grab_service_macros_r(macros, svc); - std::string tmp; - get_raw_command_line_r(macros, get_check_command_ptr(), - svc->check_command().c_str(), tmp, 0); + std::string processed_cmd = svc->get_check_command_line(macros); // Time to start command. gettimeofday(&start_time, nullptr); @@ -2634,10 +2667,6 @@ int service::run_async_check_local(int check_options, // Set the execution flag. set_is_executing(true); - // Get command object. - commands::command* cmd = get_check_command_ptr().get(); - std::string processed_cmd(cmd->process_cmd(macros)); - // Send event broker. res = broker_service_check(NEBTYPE_SERVICECHECK_INITIATE, this, checkable::check_active, processed_cmd.c_str()); @@ -2695,9 +2724,9 @@ int service::run_async_check_local(int check_options, retry = false; try { // Run command. - uint64_t id = - cmd->run(processed_cmd, *macros, config->service_check_timeout(), - check_result_info, this); + uint64_t id = get_check_command_ptr()->run( + processed_cmd, *macros, config->service_check_timeout(), + check_result_info, this); SPDLOG_LOGGER_DEBUG(checks_logger, "run id={} {} for service {} host {}", id, processed_cmd, _service_id, _hostname); @@ -3931,3 +3960,37 @@ bool service::get_host_problem_at_last_check() const { service_type service::get_service_type() const { return _service_type; } + +/** + * @brief update command object + * + * @param cmd + */ +void service::set_check_command_ptr( + const std::shared_ptr& cmd) { + std::shared_ptr old = get_check_command_ptr(); + if (cmd == old) { + return; + } + if (old) { + old->unregister_host_serv(_hostname, description()); + } + notifier::set_check_command_ptr(cmd); + if (cmd) { + cmd->register_host_serv(_hostname, description()); + } +} + +/** + * @brief calculate final check command with macros replaced + * + * @return std::string + */ +std::string service::get_check_command_line(nagios_macros* macros) { + grab_host_macros_r(macros, get_host_ptr()); + grab_service_macros_r(macros, this); + std::string tmp; + get_raw_command_line_r(macros, get_check_command_ptr(), + check_command().c_str(), tmp, 0); + return get_check_command_ptr()->process_cmd(macros); +} diff --git a/engine/tests/CMakeLists.txt b/engine/tests/CMakeLists.txt index 45bbaf7455f..f92ab3c35ba 100755 --- a/engine/tests/CMakeLists.txt +++ b/engine/tests/CMakeLists.txt @@ -1,5 +1,5 @@ # -# Copyright 2016, 2020-2023 Centreon +# Copyright 2016, 2020-2024 Centreon # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of @@ -112,7 +112,10 @@ if(WITH_TESTING) "${TESTS_DIR}/notifications/service_flapping_notification.cc" "${TESTS_DIR}/notifications/service_downtime_notification_test.cc" "${TESTS_DIR}/opentelemetry/grpc_config_test.cc" + "${TESTS_DIR}/opentelemetry/host_serv_extractor_test.cc" "${TESTS_DIR}/opentelemetry/otl_server_test.cc" + "${TESTS_DIR}/opentelemetry/otl_converter_test.cc" + "${TESTS_DIR}/opentelemetry/open_telemetry_test.cc" "${TESTS_DIR}/perfdata/perfdata.cc" "${TESTS_DIR}/retention/host.cc" "${TESTS_DIR}/retention/service.cc" diff --git a/engine/tests/opentelemetry/host_serv_extractor_test.cc b/engine/tests/opentelemetry/host_serv_extractor_test.cc new file mode 100644 index 00000000000..6d3c59e8f44 --- /dev/null +++ b/engine/tests/opentelemetry/host_serv_extractor_test.cc @@ -0,0 +1,368 @@ +/** + * Copyright 2024 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ + +#include + +#include "opentelemetry/proto/collector/metrics/v1/metrics_service.pb.h" +#include "opentelemetry/proto/common/v1/common.pb.h" +#include "opentelemetry/proto/metrics/v1/metrics.pb.h" + +#include "com/centreon/engine/modules/opentelemetry/host_serv_extractor.hh" + +using namespace com::centreon::engine::modules::opentelemetry; +using namespace com::centreon::engine; + +TEST(otl_host_serv_extractor_test, empty_request) { + metric_request_ptr request = + std::make_shared<::opentelemetry::proto::collector::metrics::v1:: + ExportMetricsServiceRequest>(); + + data_point::extract_data_points( + request, [](const data_point& data_pt) { ASSERT_TRUE(false); }); +} + +class otl_host_serv_attributes_extractor_test : public ::testing::Test { + public: + const std::string _conf1; + + const std::string _conf3 = + "attributes --host_attribute=resource --service_attribute=resource"; + const std::string _conf4 = + "attributes --host_attribute=scope --service_attribute=scope"; + const std::string _conf5 = + "attributes --host_attribute=data_point --service_attribute=data_point"; + const std::string _conf6 = + "attributes --host_attribute=data_point --host_key=bad_host " + "--service_attribute=data_point"; +}; + +TEST_F(otl_host_serv_attributes_extractor_test, resource_attrib) { + metric_request_ptr request = + std::make_shared<::opentelemetry::proto::collector::metrics::v1:: + ExportMetricsServiceRequest>(); + + auto resources = request->add_resource_metrics(); + auto host = resources->mutable_resource()->mutable_attributes()->Add(); + host->set_key("host"); + host->mutable_value()->set_string_value("my_host"); + auto host2 = resources->mutable_resource()->mutable_attributes()->Add(); + host2->set_key("host"); + host2->mutable_value()->set_string_value("my_host2"); + auto metric = resources->add_scope_metrics()->add_metrics(); + metric->set_name("metric cpu"); + metric->set_description("metric to send"); + metric->set_unit("%"); + auto gauge = metric->mutable_gauge(); + auto point = gauge->add_data_points(); + point->set_time_unix_nano(time(nullptr)); + + unsigned data_point_extracted_cpt = 0; + + data_point::extract_data_points( + request, [this, &data_point_extracted_cpt](const data_point& data_pt) { + ++data_point_extracted_cpt; + commands::otel::host_serv_list::pointer host_srv_list = + std::make_shared(); + auto extractor = host_serv_extractor::create(_conf3, host_srv_list); + host_srv_list->register_host_serv("my_host2", ""); + host_srv_list->register_host_serv("my_host2", "my_serv2"); + host_serv_metric to_test = extractor->extract_host_serv_metric(data_pt); + ASSERT_EQ(to_test.host, "my_host2"); + ASSERT_EQ(to_test.service, ""); + ASSERT_EQ(to_test.metric, "metric cpu"); + }); + + ASSERT_EQ(data_point_extracted_cpt, 1); + + data_point::extract_data_points( + request, [this, &data_point_extracted_cpt](const data_point& data_pt) { + ++data_point_extracted_cpt; + commands::otel::host_serv_list::pointer host_srv_list = + std::make_shared(); + auto extractor = host_serv_extractor::create(_conf1, host_srv_list); + host_srv_list->register_host_serv("my_host", ""); + host_serv_metric to_test = extractor->extract_host_serv_metric(data_pt); + ASSERT_TRUE(to_test.host.empty()); + }); + + data_point::extract_data_points( + request, [this, &data_point_extracted_cpt](const data_point& data_pt) { + ++data_point_extracted_cpt; + commands::otel::host_serv_list::pointer host_srv_list = + std::make_shared(); + auto extractor = host_serv_extractor::create(_conf4, host_srv_list); + host_srv_list->register_host_serv("my_host", ""); + host_serv_metric to_test = extractor->extract_host_serv_metric(data_pt); + ASSERT_TRUE(to_test.host.empty()); + }); + + data_point::extract_data_points( + request, [this, &data_point_extracted_cpt](const data_point& data_pt) { + ++data_point_extracted_cpt; + commands::otel::host_serv_list::pointer host_srv_list = + std::make_shared(); + auto extractor = host_serv_extractor::create(_conf6, host_srv_list); + host_srv_list->register_host_serv("my_host", ""); + host_serv_metric to_test = extractor->extract_host_serv_metric(data_pt); + ASSERT_TRUE(to_test.host.empty()); + }); + + auto serv = resources->mutable_resource()->mutable_attributes()->Add(); + serv->set_key("service"); + serv->mutable_value()->set_string_value("my_serv"); + data_point::extract_data_points( + request, [this, &data_point_extracted_cpt](const data_point& data_pt) { + ++data_point_extracted_cpt; + commands::otel::host_serv_list::pointer host_srv_list = + std::make_shared(); + auto extractor = host_serv_extractor::create(_conf3, host_srv_list); + host_srv_list->register_host_serv("my_host", "my_serv"); + host_serv_metric to_test = extractor->extract_host_serv_metric(data_pt); + ASSERT_EQ(to_test.host, "my_host"); + ASSERT_EQ(to_test.service, "my_serv"); + ASSERT_EQ(to_test.metric, "metric cpu"); + }); + + data_point::extract_data_points( + request, [this, &data_point_extracted_cpt](const data_point& data_pt) { + ++data_point_extracted_cpt; + commands::otel::host_serv_list::pointer host_srv_list = + std::make_shared(); + auto extractor = host_serv_extractor::create(_conf3, host_srv_list); + host_srv_list->register_host_serv("my_host2", "my_serv"); + host_serv_metric to_test = extractor->extract_host_serv_metric(data_pt); + ASSERT_EQ(to_test.host, "my_host2"); + ASSERT_EQ(to_test.service, "my_serv"); + ASSERT_EQ(to_test.metric, "metric cpu"); + }); + data_point::extract_data_points( + request, [this, &data_point_extracted_cpt](const data_point& data_pt) { + ++data_point_extracted_cpt; + commands::otel::host_serv_list::pointer host_srv_list = + std::make_shared(); + auto extractor = host_serv_extractor::create(_conf3, host_srv_list); + host_srv_list->register_host_serv("my_host3", "my_serv"); + host_serv_metric to_test = extractor->extract_host_serv_metric(data_pt); + ASSERT_TRUE(to_test.host.empty()); + }); + + auto serv2 = resources->mutable_resource()->mutable_attributes()->Add(); + serv2->set_key("service"); + serv2->mutable_value()->set_string_value("my_serv2"); + data_point::extract_data_points( + request, [this, &data_point_extracted_cpt](const data_point& data_pt) { + ++data_point_extracted_cpt; + commands::otel::host_serv_list::pointer host_srv_list = + std::make_shared(); + auto extractor = host_serv_extractor::create(_conf3, host_srv_list); + host_srv_list->register_host_serv("my_host2", ""); + host_srv_list->register_host_serv("my_host2", "my_serv2"); + host_serv_metric to_test = extractor->extract_host_serv_metric(data_pt); + ASSERT_EQ(to_test.host, "my_host2"); + ASSERT_EQ(to_test.service, "my_serv2"); + ASSERT_EQ(to_test.metric, "metric cpu"); + }); +} + +TEST_F(otl_host_serv_attributes_extractor_test, scope_attrib) { + metric_request_ptr request = + std::make_shared<::opentelemetry::proto::collector::metrics::v1:: + ExportMetricsServiceRequest>(); + + auto resources = request->add_resource_metrics(); + auto scope = resources->add_scope_metrics(); + auto host = scope->mutable_scope()->mutable_attributes()->Add(); + host->set_key("host"); + host->mutable_value()->set_string_value("my_host"); + auto burk_host = scope->mutable_scope()->mutable_attributes()->Add(); + burk_host->set_key("host"); + burk_host->mutable_value()->set_string_value("bad_host"); + auto metric = scope->add_metrics(); + metric->set_name("metric cpu"); + metric->set_description("metric to send"); + metric->set_unit("%"); + auto gauge = metric->mutable_gauge(); + auto point = gauge->add_data_points(); + point->set_time_unix_nano(time(nullptr)); + + unsigned data_point_extracted_cpt = 0; + + data_point::extract_data_points( + request, [this, &data_point_extracted_cpt](const data_point& data_pt) { + ++data_point_extracted_cpt; + commands::otel::host_serv_list::pointer host_srv_list = + std::make_shared(); + auto extractor = host_serv_extractor::create(_conf4, host_srv_list); + host_srv_list->register_host_serv("my_host", ""); + host_serv_metric to_test = extractor->extract_host_serv_metric(data_pt); + + ASSERT_EQ(to_test.host, "my_host"); + ASSERT_EQ(to_test.service, ""); + ASSERT_EQ(to_test.metric, "metric cpu"); + }); + + ASSERT_EQ(data_point_extracted_cpt, 1); + + data_point::extract_data_points( + request, [this, &data_point_extracted_cpt](const data_point& data_pt) { + ++data_point_extracted_cpt; + commands::otel::host_serv_list::pointer host_srv_list = + std::make_shared(); + auto extractor = host_serv_extractor::create(_conf1, host_srv_list); + host_srv_list->register_host_serv("my_host", ""); + host_serv_metric to_test = extractor->extract_host_serv_metric(data_pt); + ASSERT_TRUE(to_test.host.empty()); + }); + + data_point::extract_data_points( + request, [this, &data_point_extracted_cpt](const data_point& data_pt) { + ++data_point_extracted_cpt; + commands::otel::host_serv_list::pointer host_srv_list = + std::make_shared(); + auto extractor = host_serv_extractor::create(_conf3, host_srv_list); + host_srv_list->register_host_serv("my_host", ""); + host_serv_metric to_test = extractor->extract_host_serv_metric(data_pt); + ASSERT_TRUE(to_test.host.empty()); + }); + + data_point::extract_data_points( + request, [this, &data_point_extracted_cpt](const data_point& data_pt) { + ++data_point_extracted_cpt; + commands::otel::host_serv_list::pointer host_srv_list = + std::make_shared(); + auto extractor = host_serv_extractor::create(_conf5, host_srv_list); + host_srv_list->register_host_serv("my_host", ""); + host_serv_metric to_test = extractor->extract_host_serv_metric(data_pt); + ASSERT_TRUE(to_test.host.empty()); + }); + + auto serv = scope->mutable_scope()->mutable_attributes()->Add(); + serv->set_key("service"); + serv->mutable_value()->set_string_value("my_serv"); + data_point::extract_data_points( + request, [this, &data_point_extracted_cpt](const data_point& data_pt) { + ++data_point_extracted_cpt; + commands::otel::host_serv_list::pointer host_srv_list = + std::make_shared(); + auto extractor = host_serv_extractor::create(_conf4, host_srv_list); + host_srv_list->register_host_serv("my_host", "my_serv"); + host_serv_metric to_test = extractor->extract_host_serv_metric(data_pt); + ASSERT_EQ(to_test.host, "my_host"); + ASSERT_EQ(to_test.service, "my_serv"); + ASSERT_EQ(to_test.metric, "metric cpu"); + }); +} + +TEST_F(otl_host_serv_attributes_extractor_test, data_point_attrib) { + metric_request_ptr request = + std::make_shared<::opentelemetry::proto::collector::metrics::v1:: + ExportMetricsServiceRequest>(); + + auto resources = request->add_resource_metrics(); + auto scope = resources->add_scope_metrics(); + auto metric = scope->add_metrics(); + metric->set_name("metric cpu"); + metric->set_description("metric to send"); + metric->set_unit("%"); + auto gauge = metric->mutable_gauge(); + auto point = gauge->add_data_points(); + point->set_time_unix_nano(time(nullptr)); + auto host = point->mutable_attributes()->Add(); + host->set_key("host"); + host->mutable_value()->set_string_value("my_host"); + + unsigned data_point_extracted_cpt = 0; + + data_point::extract_data_points( + request, [this, &data_point_extracted_cpt](const data_point& data_pt) { + ++data_point_extracted_cpt; + commands::otel::host_serv_list::pointer host_srv_list = + std::make_shared(); + auto extractor = host_serv_extractor::create(_conf1, host_srv_list); + host_srv_list->register_host_serv("my_host", ""); + host_serv_metric to_test = extractor->extract_host_serv_metric(data_pt); + ASSERT_EQ(to_test.host, "my_host"); + ASSERT_EQ(to_test.service, ""); + ASSERT_EQ(to_test.metric, "metric cpu"); + }); + + data_point::extract_data_points( + request, [this, &data_point_extracted_cpt](const data_point& data_pt) { + ++data_point_extracted_cpt; + commands::otel::host_serv_list::pointer host_srv_list = + std::make_shared(); + auto extractor = host_serv_extractor::create(_conf5, host_srv_list); + host_srv_list->register_host_serv("my_host", ""); + host_serv_metric to_test = extractor->extract_host_serv_metric(data_pt); + ASSERT_EQ(to_test.host, "my_host"); + ASSERT_EQ(to_test.service, ""); + ASSERT_EQ(to_test.metric, "metric cpu"); + }); + + ASSERT_EQ(data_point_extracted_cpt, 2); + + data_point::extract_data_points( + request, [this, &data_point_extracted_cpt](const data_point& data_pt) { + ++data_point_extracted_cpt; + commands::otel::host_serv_list::pointer host_srv_list = + std::make_shared(); + auto extractor = host_serv_extractor::create(_conf3, host_srv_list); + host_srv_list->register_host_serv("my_host", ""); + host_serv_metric to_test = extractor->extract_host_serv_metric(data_pt); + ASSERT_TRUE(to_test.host.empty()); + }); + + data_point::extract_data_points( + request, [this, &data_point_extracted_cpt](const data_point& data_pt) { + ++data_point_extracted_cpt; + commands::otel::host_serv_list::pointer host_srv_list = + std::make_shared(); + auto extractor = host_serv_extractor::create(_conf4, host_srv_list); + host_srv_list->register_host_serv("my_host", ""); + host_serv_metric to_test = extractor->extract_host_serv_metric(data_pt); + ASSERT_TRUE(to_test.host.empty()); + }); + + data_point::extract_data_points( + request, [this, &data_point_extracted_cpt](const data_point& data_pt) { + ++data_point_extracted_cpt; + commands::otel::host_serv_list::pointer host_srv_list = + std::make_shared(); + auto extractor = host_serv_extractor::create(_conf6, host_srv_list); + host_srv_list->register_host_serv("my_host", ""); + host_serv_metric to_test = extractor->extract_host_serv_metric(data_pt); + ASSERT_TRUE(to_test.host.empty()); + }); + + auto serv = point->mutable_attributes()->Add(); + serv->set_key("service"); + serv->mutable_value()->set_string_value("my_serv"); + data_point::extract_data_points( + request, [this, &data_point_extracted_cpt](const data_point& data_pt) { + ++data_point_extracted_cpt; + commands::otel::host_serv_list::pointer host_srv_list = + std::make_shared(); + auto extractor = host_serv_extractor::create(_conf1, host_srv_list); + host_srv_list->register_host_serv("my_host", "my_serv"); + host_serv_metric to_test = extractor->extract_host_serv_metric(data_pt); + ASSERT_EQ(to_test.host, "my_host"); + ASSERT_EQ(to_test.service, "my_serv"); + ASSERT_EQ(to_test.metric, "metric cpu"); + }); +} diff --git a/engine/tests/opentelemetry/open_telemetry_test.cc b/engine/tests/opentelemetry/open_telemetry_test.cc new file mode 100644 index 00000000000..58603487909 --- /dev/null +++ b/engine/tests/opentelemetry/open_telemetry_test.cc @@ -0,0 +1,141 @@ +/** + * Copyright 2024 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include + +#include "com/centreon/common/http/http_server.hh" +#include "com/centreon/engine/configuration/applier/contact.hh" +#include "com/centreon/engine/configuration/applier/host.hh" +#include "com/centreon/engine/configuration/applier/service.hh" +#include "com/centreon/engine/configuration/host.hh" +#include "com/centreon/engine/configuration/service.hh" + +#include "opentelemetry/proto/collector/metrics/v1/metrics_service.pb.h" +#include "opentelemetry/proto/common/v1/common.pb.h" +#include "opentelemetry/proto/metrics/v1/metrics.pb.h" + +#include "com/centreon/engine/modules/opentelemetry/open_telemetry.hh" + +#include "helper.hh" +#include "test_engine.hh" + +using namespace com::centreon::engine::modules::opentelemetry; +using namespace com::centreon::engine; + +extern const char* telegraf_example; + +extern std::shared_ptr g_io_context; + +class open_telemetry + : public com::centreon::engine::modules::opentelemetry::open_telemetry { + protected: + void _create_otl_server(const grpc_config::pointer& server_conf) override {} + + public: + open_telemetry(const std::string_view config_file_path, + const std::shared_ptr& io_context, + const std::shared_ptr& logger) + : com::centreon::engine::modules::opentelemetry::open_telemetry( + config_file_path, + io_context, + logger) {} + + void on_metric(const metric_request_ptr& metric) { _on_metric(metric); } + void shutdown() { _shutdown(); } + static std::shared_ptr load( + const std::string_view& config_path, + const std::shared_ptr& io_context, + const std::shared_ptr& logger) { + std::shared_ptr ret = + std::make_shared(config_path, io_context, logger); + ret->_reload(); + ret->_start_second_timer(); + return ret; + } +}; + +class open_telemetry_test : public TestEngine { + public: + commands::otel::host_serv_list::pointer _host_serv_list; + + open_telemetry_test(); + static void SetUpTestSuite(); + void SetUp() override; + void TearDown() override; +}; + +open_telemetry_test::open_telemetry_test() + : _host_serv_list(std::make_shared()) { + _host_serv_list->register_host_serv("localhost", "check_icmp"); +} + +void open_telemetry_test::SetUpTestSuite() { + std::ofstream conf_file("/tmp/otel_conf.json"); + conf_file << R"({ + "server": { + "host": "127.0.0.1", + "port": 4317 + } +} +)"; + conf_file.close(); + // spdlog::default_logger()->set_level(spdlog::level::trace); +} + +void open_telemetry_test::SetUp() { + init_config_state(); + config->contacts().clear(); + configuration::applier::contact ct_aply; + configuration::contact ctct{new_configuration_contact("admin", true)}; + ct_aply.add_object(ctct); + ct_aply.expand_objects(*config); + ct_aply.resolve_object(ctct); + + configuration::host hst{new_configuration_host("localhost", "admin")}; + configuration::applier::host hst_aply; + hst_aply.add_object(hst); + + configuration::service svc{ + new_configuration_service("localhost", "check_icmp", "admin")}; + configuration::applier::service svc_aply; + svc_aply.add_object(svc); + + hst_aply.resolve_object(hst); + svc_aply.resolve_object(svc); + data_point_fifo::update_fifo_limit(std::numeric_limits::max(), 10); +} + +void open_telemetry_test::TearDown() { + deinit_config_state(); +} diff --git a/engine/tests/opentelemetry/otl_converter_test.cc b/engine/tests/opentelemetry/otl_converter_test.cc new file mode 100644 index 00000000000..900b6f36e55 --- /dev/null +++ b/engine/tests/opentelemetry/otl_converter_test.cc @@ -0,0 +1,563 @@ +/** + * Copyright 2024 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "com/centreon/engine/configuration/applier/contact.hh" +#include "com/centreon/engine/configuration/applier/host.hh" +#include "com/centreon/engine/configuration/applier/service.hh" +#include "com/centreon/engine/configuration/host.hh" +#include "com/centreon/engine/configuration/service.hh" + +#include "opentelemetry/proto/collector/metrics/v1/metrics_service.pb.h" +#include "opentelemetry/proto/common/v1/common.pb.h" +#include "opentelemetry/proto/metrics/v1/metrics.pb.h" + +#include "com/centreon/engine/modules/opentelemetry/data_point_fifo_container.hh" +#include "com/centreon/engine/modules/opentelemetry/otl_converter.hh" + +#include "helper.hh" +#include "test_engine.hh" + +using namespace com::centreon::engine::modules::opentelemetry; +using namespace com::centreon::engine; + +class otl_converter_test : public TestEngine { + public: + void SetUp() override; + void TearDown() override; +}; + +void otl_converter_test::SetUp() { + init_config_state(); + config->contacts().clear(); + configuration::applier::contact ct_aply; + configuration::contact ctct{new_configuration_contact("admin", true)}; + ct_aply.add_object(ctct); + ct_aply.expand_objects(*config); + ct_aply.resolve_object(ctct); + + configuration::host hst{new_configuration_host("localhost", "admin")}; + configuration::applier::host hst_aply; + hst_aply.add_object(hst); + + configuration::service svc{ + new_configuration_service("localhost", "check_icmp", "admin")}; + configuration::applier::service svc_aply; + svc_aply.add_object(svc); + + hst_aply.resolve_object(hst); + svc_aply.resolve_object(svc); + data_point_fifo::update_fifo_limit(std::numeric_limits::max(), 10); +} + +void otl_converter_test::TearDown() { + deinit_config_state(); +} + +const char* telegraf_example = R"( + { + "resourceMetrics": [ + { + "resource": { + "attributes": [ + { + "key": "service.name", + "value": { + "stringValue": "demo_telegraf" + } + } + ] + }, + "scopeMetrics": [ + { + "scope": {}, + "metrics": [ + { + "name": "check_icmp_critical_lt", + "gauge": { + "dataPoints": [ + { + "timeUnixNano": "1707744430000000000", + "asDouble": 0, + "attributes": [ + { + "key": "unit", + "value": { + "stringValue": "ms" + } + }, + { + "key": "host", + "value": { + "stringValue": "localhost" + } + }, + { + "key": "perfdata", + "value": { + "stringValue": "rta" + } + }, + { + "key": "service", + "value": { + "stringValue": "check_icmp" + } + } + ] + }, + { + "timeUnixNano": "1707744430000000000", + "asDouble": 0, + "attributes": [ + { + "key": "host", + "value": { + "stringValue": "localhost" + } + }, + { + "key": "perfdata", + "value": { + "stringValue": "pl" + } + }, + { + "key": "service", + "value": { + "stringValue": "check_icmp" + } + }, + { + "key": "unit", + "value": { + "stringValue": "%" + } + } + ] + } + ] + } + }, + { + "name": "check_icmp_critical_gt", + "gauge": { + "dataPoints": [ + { + "timeUnixNano": "1707744430000000000", + "asDouble": 500, + "attributes": [ + { + "key": "unit", + "value": { + "stringValue": "ms" + } + }, + { + "key": "host", + "value": { + "stringValue": "localhost" + } + }, + { + "key": "perfdata", + "value": { + "stringValue": "rta" + } + }, + { + "key": "service", + "value": { + "stringValue": "check_icmp" + } + } + ] + }, + { + "timeUnixNano": "1707744430000000000", + "asDouble": 80, + "attributes": [ + { + "key": "host", + "value": { + "stringValue": "localhost" + } + }, + { + "key": "perfdata", + "value": { + "stringValue": "pl" + } + }, + { + "key": "service", + "value": { + "stringValue": "check_icmp" + } + }, + { + "key": "unit", + "value": { + "stringValue": "%" + } + } + ] + } + ] + } + }, + { + "name": "check_icmp_min", + "gauge": { + "dataPoints": [ + { + "timeUnixNano": "1707744430000000000", + "asDouble": 0, + "attributes": [ + { + "key": "host", + "value": { + "stringValue": "localhost" + } + }, + { + "key": "perfdata", + "value": { + "stringValue": "rta" + } + }, + { + "key": "service", + "value": { + "stringValue": "check_icmp" + } + }, + { + "key": "unit", + "value": { + "stringValue": "ms" + } + } + ] + } + ] + } + }, + { + "name": "check_icmp_value", + "gauge": { + "dataPoints": [ + { + "timeUnixNano": "1707744430000000000", + "asDouble": 0.022, + "attributes": [ + { + "key": "host", + "value": { + "stringValue": "localhost" + } + }, + { + "key": "perfdata", + "value": { + "stringValue": "rta" + } + }, + { + "key": "service", + "value": { + "stringValue": "check_icmp" + } + }, + { + "key": "unit", + "value": { + "stringValue": "ms" + } + } + ] + }, + { + "timeUnixNano": "1707744430000000000", + "asDouble": 0, + "attributes": [ + { + "key": "host", + "value": { + "stringValue": "localhost" + } + }, + { + "key": "perfdata", + "value": { + "stringValue": "pl" + } + }, + { + "key": "service", + "value": { + "stringValue": "check_icmp" + } + }, + { + "key": "unit", + "value": { + "stringValue": "%" + } + } + ] + }, + { + "timeUnixNano": "1707744430000000000", + "asDouble": 0.071, + "attributes": [ + { + "key": "host", + "value": { + "stringValue": "localhost" + } + }, + { + "key": "perfdata", + "value": { + "stringValue": "rtmax" + } + }, + { + "key": "service", + "value": { + "stringValue": "check_icmp" + } + }, + { + "key": "unit", + "value": { + "stringValue": "ms" + } + } + ] + }, + { + "timeUnixNano": "1707744430000000000", + "asDouble": 0.008, + "attributes": [ + { + "key": "host", + "value": { + "stringValue": "localhost" + } + }, + { + "key": "perfdata", + "value": { + "stringValue": "rtmin" + } + }, + { + "key": "service", + "value": { + "stringValue": "check_icmp" + } + }, + { + "key": "unit", + "value": { + "stringValue": "ms" + } + } + ] + } + ] + } + }, + { + "name": "check_icmp_warning_lt", + "gauge": { + "dataPoints": [ + { + "timeUnixNano": "1707744430000000000", + "asDouble": 0, + "attributes": [ + { + "key": "host", + "value": { + "stringValue": "localhost" + } + }, + { + "key": "perfdata", + "value": { + "stringValue": "rta" + } + }, + { + "key": "service", + "value": { + "stringValue": "check_icmp" + } + }, + { + "key": "unit", + "value": { + "stringValue": "ms" + } + } + ] + }, + { + "timeUnixNano": "1707744430000000000", + "asDouble": 0, + "attributes": [ + { + "key": "host", + "value": { + "stringValue": "localhost" + } + }, + { + "key": "perfdata", + "value": { + "stringValue": "pl" + } + }, + { + "key": "service", + "value": { + "stringValue": "check_icmp" + } + }, + { + "key": "unit", + "value": { + "stringValue": "%" + } + } + ] + } + ] + } + }, + { + "name": "check_icmp_warning_gt", + "gauge": { + "dataPoints": [ + { + "timeUnixNano": "1707744430000000000", + "asDouble": 200, + "attributes": [ + { + "key": "host", + "value": { + "stringValue": "localhost" + } + }, + { + "key": "perfdata", + "value": { + "stringValue": "rta" + } + }, + { + "key": "service", + "value": { + "stringValue": "check_icmp" + } + }, + { + "key": "unit", + "value": { + "stringValue": "ms" + } + } + ] + }, + { + "timeUnixNano": "1707744430000000000", + "asDouble": 40, + "attributes": [ + { + "key": "host", + "value": { + "stringValue": "localhost" + } + }, + { + "key": "perfdata", + "value": { + "stringValue": "pl" + } + }, + { + "key": "service", + "value": { + "stringValue": "check_icmp" + } + }, + { + "key": "unit", + "value": { + "stringValue": "%" + } + } + ] + } + ] + } + }, + { + "name": "check_icmp_state", + "gauge": { + "dataPoints": [ + { + "timeUnixNano": "1707744430000000000", + "asInt": "0", + "attributes": [ + { + "key": "host", + "value": { + "stringValue": "localhost" + } + }, + { + "key": "service", + "value": { + "stringValue": "check_icmp" + } + } + ] + } + ] + } + } + ] + } + ] + } + ] +} +)"; + diff --git a/tests/resources/Common.py b/tests/resources/Common.py index 2bce27f9bdc..6db8270fd95 100644 --- a/tests/resources/Common.py +++ b/tests/resources/Common.py @@ -223,7 +223,7 @@ def ctn_find_in_log_with_timeout(log: str, date, content, timeout: int, **kwargs def ctn_find_in_log_with_timeout_with_line(log: str, date, content, timeout: int): """! search a pattern in log from date param @param log: path of the log file - @param date: date from witch it begins search + @param date: date from which it begins search @param content: array of pattern to search @param timeout: time out in second @return True/False, array of lines found for each pattern From 0a3b58b8e8306f8c7ea1919c19e1f6e3fb399353 Mon Sep 17 00:00:00 2001 From: David Boucher Date: Wed, 5 Jun 2024 11:57:04 +0200 Subject: [PATCH 24/60] enh(engine): customvariables have their own configuration class (#1398) REFS: MON-87279 --- broker/neb/src/initial.cc | 4 +- .../engine/configuration/anomalydetection.hh | 9 +- .../centreon/engine/configuration/contact.hh | 10 +- .../com/centreon/engine/configuration/host.hh | 51 +++---- .../centreon/engine/configuration/service.hh | 54 ++++---- .../centreon/engine/configuration/state.hh | 2 +- .../inc/com/centreon/engine/customvariable.hh | 4 +- engine/src/commands/raw.cc | 15 +-- engine/src/configuration/CMakeLists.txt | 1 + engine/src/configuration/anomalydetection.cc | 10 +- .../configuration/applier/anomalydetection.cc | 41 +++--- engine/src/configuration/applier/contact.cc | 127 +++++++++--------- engine/src/configuration/applier/host.cc | 112 +++++++-------- engine/src/configuration/applier/service.cc | 49 ++++--- engine/src/configuration/applier/state.cc | 2 +- engine/src/configuration/contact.cc | 13 +- engine/src/configuration/host.cc | 9 +- engine/src/configuration/parser.cc | 2 +- engine/src/configuration/service.cc | 12 +- engine/src/configuration/state.cc | 2 +- engine/src/customvariable.cc | 2 +- engine/src/macros.cc | 2 +- engine/src/retention/applier/contact.cc | 36 ++--- engine/src/retention/applier/host.cc | 36 ++--- engine/src/retention/applier/service.cc | 2 +- engine/src/retention/dump.cc | 2 +- engine/src/xsddefault.cc | 6 +- .../configuration/applier/applier-contact.cc | 7 +- .../configuration/applier/applier-state.cc | 2 +- engine/tests/enginerpc/enginerpc.cc | 7 +- 30 files changed, 317 insertions(+), 314 deletions(-) diff --git a/broker/neb/src/initial.cc b/broker/neb/src/initial.cc index 71829c4e99d..a8fad65920e 100644 --- a/broker/neb/src/initial.cc +++ b/broker/neb/src/initial.cc @@ -76,7 +76,7 @@ static void send_custom_variables_list( nscvd.type = NEBTYPE_HOSTCUSTOMVARIABLE_ADD; nscvd.timestamp.tv_sec = time(nullptr); nscvd.var_name = const_cast(name.c_str()); - nscvd.var_value = const_cast(cit->second.get_value().c_str()); + nscvd.var_value = const_cast(cit->second.value().c_str()); nscvd.object_ptr = it->second.get(); // Callback. @@ -103,7 +103,7 @@ static void send_custom_variables_list( nscvd.type = NEBTYPE_SERVICECUSTOMVARIABLE_ADD; nscvd.timestamp.tv_sec = time(nullptr); nscvd.var_name = const_cast(name.c_str()); - nscvd.var_value = const_cast(cit->second.get_value().c_str()); + nscvd.var_value = const_cast(cit->second.value().c_str()); nscvd.object_ptr = it->second.get(); // Callback. diff --git a/engine/inc/com/centreon/engine/configuration/anomalydetection.hh b/engine/inc/com/centreon/engine/configuration/anomalydetection.hh index c797a20b8b6..68fb0d74495 100644 --- a/engine/inc/com/centreon/engine/configuration/anomalydetection.hh +++ b/engine/inc/com/centreon/engine/configuration/anomalydetection.hh @@ -20,9 +20,9 @@ #define CCE_CONFIGURATION_ANOMALYDETECTION_HH #include "com/centreon/engine/common.hh" +#include "com/centreon/engine/configuration/customvariable.hh" #include "com/centreon/engine/configuration/group.hh" #include "com/centreon/engine/configuration/object.hh" -#include "com/centreon/engine/customvariable.hh" #include "com/centreon/engine/opt.hh" namespace com::centreon::engine { @@ -68,8 +68,9 @@ class anomalydetection : public object { set_string& contacts() noexcept; set_string const& contacts() const noexcept; bool contacts_defined() const noexcept; - map_customvar const& customvariables() const noexcept; - map_customvar& customvariables() noexcept; + const std::unordered_map& customvariables() + const noexcept; + std::unordered_map& customvariables() noexcept; std::string const& display_name() const noexcept; std::string const& event_handler() const noexcept; bool event_handler_enabled() const noexcept; @@ -189,7 +190,7 @@ class anomalydetection : public object { opt _check_interval; group _contactgroups; group _contacts; - map_customvar _customvariables; + std::unordered_map _customvariables; std::string _display_name; std::string _event_handler; opt _event_handler_enabled; diff --git a/engine/inc/com/centreon/engine/configuration/contact.hh b/engine/inc/com/centreon/engine/configuration/contact.hh index 615181876f7..fc2651fb4b1 100644 --- a/engine/inc/com/centreon/engine/configuration/contact.hh +++ b/engine/inc/com/centreon/engine/configuration/contact.hh @@ -21,9 +21,9 @@ #include +#include "com/centreon/engine/configuration/customvariable.hh" #include "com/centreon/engine/configuration/group.hh" #include "com/centreon/engine/configuration/object.hh" -#include "com/centreon/engine/customvariable.hh" #include "com/centreon/engine/opt.hh" typedef std::vector tab_string; @@ -53,8 +53,10 @@ class contact : public object { set_string& contactgroups() noexcept; set_string const& contactgroups() const noexcept; std::string const& contact_name() const noexcept; - map_customvar const& customvariables() const noexcept; - map_customvar& customvariables() noexcept; + const std::unordered_map& customvariables() + const noexcept; + std::unordered_map& + mutable_customvariables() noexcept; std::string const& email() const noexcept; bool host_notifications_enabled() const noexcept; list_string const& host_notification_commands() const noexcept; @@ -96,7 +98,7 @@ class contact : public object { opt _can_submit_commands; group _contactgroups; std::string _contact_name; - map_customvar _customvariables; + std::unordered_map _customvariables; std::string _email; opt _host_notifications_enabled; group _host_notification_commands; diff --git a/engine/inc/com/centreon/engine/configuration/host.hh b/engine/inc/com/centreon/engine/configuration/host.hh index 93f831ad357..121ed461116 100644 --- a/engine/inc/com/centreon/engine/configuration/host.hh +++ b/engine/inc/com/centreon/engine/configuration/host.hh @@ -1,31 +1,30 @@ -/* -** Copyright 2011-2013,2015-2017,2022 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2013,2015-2017,2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCE_CONFIGURATION_HOST_HH #define CCE_CONFIGURATION_HOST_HH #include "com/centreon/engine/common.hh" +#include "com/centreon/engine/configuration/customvariable.hh" #include "com/centreon/engine/configuration/group.hh" #include "com/centreon/engine/configuration/object.hh" #include "com/centreon/engine/configuration/point_2d.hh" #include "com/centreon/engine/configuration/point_3d.hh" -#include "com/centreon/engine/customvariable.hh" #include "com/centreon/engine/opt.hh" namespace com::centreon::engine { @@ -68,8 +67,10 @@ class host : public object { set_string const& contacts() const noexcept; point_2d const& coords_2d() const noexcept; point_3d const& coords_3d() const noexcept; - map_customvar const& customvariables() const noexcept; - map_customvar& customvariables() noexcept; + const std::unordered_map& customvariables() + const noexcept; + std::unordered_map& + mut_customvariables() noexcept; std::string const& display_name() const noexcept; std::string const& event_handler() const noexcept; bool event_handler_enabled() const noexcept; @@ -183,7 +184,7 @@ class host : public object { group _contacts; opt _coords_2d; opt _coords_3d; - map_customvar _customvariables; + std::unordered_map _customvariables; std::string _display_name; std::string _event_handler; opt _event_handler_enabled; @@ -197,7 +198,7 @@ class host : public object { std::string _host_name; std::string _icon_image; std::string _icon_image_alt; - opt _initial_state; + uint32_t _initial_state; opt _low_flap_threshold; opt _max_check_attempts; std::string _notes; @@ -225,7 +226,7 @@ class host : public object { typedef std::shared_ptr host_ptr; typedef std::list list_host; -typedef std::set set_host; +using set_host = std::set; } // namespace configuration } // namespace com::centreon::engine diff --git a/engine/inc/com/centreon/engine/configuration/service.hh b/engine/inc/com/centreon/engine/configuration/service.hh index 49fc7bd5853..9cacb129f4a 100644 --- a/engine/inc/com/centreon/engine/configuration/service.hh +++ b/engine/inc/com/centreon/engine/configuration/service.hh @@ -1,34 +1,31 @@ -/* -** Copyright 2011-2013,2015-2017-2022 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2013,2015-2017-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCE_CONFIGURATION_SERVICE_HH #define CCE_CONFIGURATION_SERVICE_HH #include "com/centreon/engine/common.hh" +#include "com/centreon/engine/configuration/customvariable.hh" #include "com/centreon/engine/configuration/group.hh" #include "com/centreon/engine/configuration/object.hh" -#include "com/centreon/engine/customvariable.hh" #include "com/centreon/engine/opt.hh" -namespace com::centreon::engine { - -namespace configuration { +namespace com::centreon::engine::configuration { class service : public object { public: @@ -68,8 +65,10 @@ class service : public object { set_string& contacts() noexcept; set_string const& contacts() const noexcept; bool contacts_defined() const noexcept; - map_customvar const& customvariables() const noexcept; - map_customvar& customvariables() noexcept; + const std::unordered_map& customvariables() + const noexcept; + std::unordered_map& + mut_customvariables() noexcept; std::string const& display_name() const noexcept; std::string const& event_handler() const noexcept; bool event_handler_enabled() const noexcept; @@ -185,7 +184,7 @@ class service : public object { std::string _check_period; group _contactgroups; group _contacts; - map_customvar _customvariables; + std::unordered_map _customvariables; std::string _display_name; std::string _event_handler; opt _event_handler_enabled; @@ -231,8 +230,7 @@ typedef std::list list_service; typedef std::set set_service; typedef std::unordered_map, service_ptr> map_service; -} // namespace configuration -} // namespace com::centreon::engine +} // namespace com::centreon::engine::configuration #endif // !CCE_CONFIGURATION_SERVICE_HH diff --git a/engine/inc/com/centreon/engine/configuration/state.hh b/engine/inc/com/centreon/engine/configuration/state.hh index 174c53d4b57..5c9f8979d27 100644 --- a/engine/inc/com/centreon/engine/configuration/state.hh +++ b/engine/inc/com/centreon/engine/configuration/state.hh @@ -346,7 +346,7 @@ class state { // const set_anomalydetection& anomalydetections() const noexcept; set_anomalydetection& anomalydetections() noexcept; set_service const& services() const noexcept; - set_service& services() noexcept; + set_service& mut_services() noexcept; set_anomalydetection::iterator anomalydetections_find( anomalydetection::key_type const& k); set_service::iterator services_find(service::key_type const& k); diff --git a/engine/inc/com/centreon/engine/customvariable.hh b/engine/inc/com/centreon/engine/customvariable.hh index cf1ad73e40a..3b2e7fefc2e 100644 --- a/engine/inc/com/centreon/engine/customvariable.hh +++ b/engine/inc/com/centreon/engine/customvariable.hh @@ -43,7 +43,7 @@ class customvariable { void set_sent(bool sent); bool is_sent() const; void set_value(std::string const& value); - std::string const& get_value() const; + const std::string& value() const; bool has_been_modified() const; void update(std::string const& value); @@ -55,6 +55,6 @@ class customvariable { typedef std::unordered_map map_customvar; -} +} // namespace com::centreon::engine #endif // !CCE_OBJECTS_CUSTOMVARIABLE_HH diff --git a/engine/src/commands/raw.cc b/engine/src/commands/raw.cc index 666da9e8bb1..b196a80834b 100644 --- a/engine/src/commands/raw.cc +++ b/engine/src/commands/raw.cc @@ -393,9 +393,8 @@ void raw::_build_custom_contact_macro_environment(nagios_macros& macros, // Set custom contact variable into the environement for (auto const& cv : macros.custom_contact_vars) { if (!cv.first.empty()) { - std::string value( - clean_macro_chars(cv.second.get_value(), - STRIP_ILLEGAL_MACRO_CHARS | ESCAPE_MACRO_CHARS)); + std::string value(clean_macro_chars( + cv.second.value(), STRIP_ILLEGAL_MACRO_CHARS | ESCAPE_MACRO_CHARS)); std::string line; line.append(MACRO_ENV_VAR_PREFIX); line.append(cv.first); @@ -428,9 +427,8 @@ void raw::_build_custom_host_macro_environment(nagios_macros& macros, // Set custom host variable into the environement for (auto const& cv : macros.custom_host_vars) { if (!cv.first.empty()) { - std::string value( - clean_macro_chars(cv.second.get_value(), - STRIP_ILLEGAL_MACRO_CHARS | ESCAPE_MACRO_CHARS)); + std::string value(clean_macro_chars( + cv.second.value(), STRIP_ILLEGAL_MACRO_CHARS | ESCAPE_MACRO_CHARS)); std::string line; line.append(MACRO_ENV_VAR_PREFIX); line.append(cv.first); @@ -463,9 +461,8 @@ void raw::_build_custom_service_macro_environment(nagios_macros& macros, // Set custom service variable into the environement for (auto const& cv : macros.custom_service_vars) { if (!cv.first.empty()) { - std::string value( - clean_macro_chars(cv.second.get_value(), - STRIP_ILLEGAL_MACRO_CHARS | ESCAPE_MACRO_CHARS)); + std::string value(clean_macro_chars( + cv.second.value(), STRIP_ILLEGAL_MACRO_CHARS | ESCAPE_MACRO_CHARS)); std::string line; line.append(MACRO_ENV_VAR_PREFIX); line.append(cv.first); diff --git a/engine/src/configuration/CMakeLists.txt b/engine/src/configuration/CMakeLists.txt index b0bd8910f26..ff0c4fcd7a0 100644 --- a/engine/src/configuration/CMakeLists.txt +++ b/engine/src/configuration/CMakeLists.txt @@ -32,6 +32,7 @@ set(FILES "${SRC_DIR}/connector.cc" "${SRC_DIR}/contact.cc" "${SRC_DIR}/contactgroup.cc" + "${SRC_DIR}/customvariable.cc" "${SRC_DIR}/extended_conf.cc" "${SRC_DIR}/group.cc" "${SRC_DIR}/host.cc" diff --git a/engine/src/configuration/anomalydetection.cc b/engine/src/configuration/anomalydetection.cc index 7ccf1724b99..3079186deb5 100644 --- a/engine/src/configuration/anomalydetection.cc +++ b/engine/src/configuration/anomalydetection.cc @@ -994,7 +994,7 @@ bool anomalydetection::parse(char const* key, char const* value) { return (it->second)(*this, value); if (key[0] == '_') { - map_customvar::iterator it{_customvariables.find(key + 1)}; + auto it = _customvariables.find(key + 1); if (it == _customvariables.end()) _customvariables[key + 1] = customvariable(value); else @@ -1136,8 +1136,8 @@ bool anomalydetection::contacts_defined() const noexcept { * * @return The customvariables. */ -com::centreon::engine::map_customvar const& anomalydetection::customvariables() - const noexcept { +const std::unordered_map& +anomalydetection::customvariables() const noexcept { return _customvariables; } @@ -1146,7 +1146,7 @@ com::centreon::engine::map_customvar const& anomalydetection::customvariables() * * @return The customvariables. */ -com::centreon::engine::map_customvar& +std::unordered_map& anomalydetection::customvariables() noexcept { return _customvariables; } @@ -1329,7 +1329,6 @@ bool anomalydetection::notifications_enabled() const noexcept { */ void anomalydetection::notification_interval(unsigned int interval) noexcept { _notification_interval = interval; - return; } /** @@ -1529,7 +1528,6 @@ unsigned short anomalydetection::stalking_options() const noexcept { */ void anomalydetection::timezone(std::string const& time_zone) { _timezone = time_zone; - return; } /** diff --git a/engine/src/configuration/applier/anomalydetection.cc b/engine/src/configuration/applier/anomalydetection.cc index a4cc5ef1d14..3cac2fe529b 100644 --- a/engine/src/configuration/applier/anomalydetection.cc +++ b/engine/src/configuration/applier/anomalydetection.cc @@ -1,5 +1,5 @@ /** - * Copyright 2020-2024 Centreon + * Copyright 2020,2023-2024 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -141,21 +141,22 @@ void applier::anomalydetection::add_object( ad->mut_contacts().insert({*it, nullptr}); // Add contactgroups. - for (set_string::const_iterator it(obj.contactgroups().begin()), - end(obj.contactgroups().end()); + for (set_string::const_iterator it = obj.contactgroups().begin(), + end = obj.contactgroups().end(); it != end; ++it) ad->get_contactgroups().insert({*it, nullptr}); // Add custom variables. - for (map_customvar::const_iterator it(obj.customvariables().begin()), - end(obj.customvariables().end()); + for (auto it = obj.customvariables().begin(), + end = obj.customvariables().end(); it != end; ++it) { - ad->custom_variables[it->first] = it->second; + ad->custom_variables[it->first] = + engine::customvariable(it->second.value(), it->second.is_sent()); if (it->second.is_sent()) { timeval tv(get_broker_timestamp(nullptr)); broker_custom_variable(NEBTYPE_SERVICECUSTOMVARIABLE_ADD, ad, - it->first.c_str(), it->second.get_value().c_str(), + it->first.c_str(), it->second.value().c_str(), &tv); } } @@ -172,21 +173,22 @@ void applier::anomalydetection::add_object( */ void applier::anomalydetection::expand_objects(configuration::state& s) { // Browse all anomalydetections. - for (configuration::set_anomalydetection::iterator - it_ad = s.anomalydetections().begin(), - end_ad = s.anomalydetections().end(); - it_ad != end_ad; ++it_ad) { + configuration::set_anomalydetection new_ads; + // In a set, we cannot change items as it would change their order. So we + // create a new set and replace the old one with the new one at the end. + for (auto ad : s.anomalydetections()) { // Should custom variables be sent to broker ? - for (map_customvar::iterator - it = const_cast(it_ad->customvariables()).begin(), - end = const_cast(it_ad->customvariables()).end(); + for (auto it = ad.customvariables().begin(), + end = ad.customvariables().end(); it != end; ++it) { if (!s.enable_macros_filter() || s.macros_filter().find(it->first) != s.macros_filter().end()) { it->second.set_sent(true); } } + new_ads.insert(std::move(ad)); } + s.anomalydetections() = std::move(new_ads); } /** @@ -373,20 +375,19 @@ void applier::anomalydetection::modify_object( if (c.second.is_sent()) { timeval tv(get_broker_timestamp(nullptr)); broker_custom_variable(NEBTYPE_SERVICECUSTOMVARIABLE_DELETE, s.get(), - c.first.c_str(), c.second.get_value().c_str(), - &tv); + c.first.c_str(), c.second.value().c_str(), &tv); } } s->custom_variables.clear(); for (auto& c : obj.customvariables()) { - s->custom_variables[c.first] = c.second; + s->custom_variables[c.first] = + engine::customvariable(c.second.value(), c.second.is_sent()); if (c.second.is_sent()) { timeval tv(get_broker_timestamp(nullptr)); broker_custom_variable(NEBTYPE_SERVICECUSTOMVARIABLE_ADD, s.get(), - c.first.c_str(), c.second.get_value().c_str(), - &tv); + c.first.c_str(), c.second.value().c_str(), &tv); } } } @@ -524,8 +525,6 @@ void applier::anomalydetection::_expand_service_memberships( // Reinsert anomalydetection group. s.servicegroups().insert(backup); } - - return; } /** diff --git a/engine/src/configuration/applier/contact.cc b/engine/src/configuration/applier/contact.cc index 022737ac760..52469cdb181 100644 --- a/engine/src/configuration/applier/contact.cc +++ b/engine/src/configuration/applier/contact.cc @@ -53,6 +53,10 @@ class contactgroup_name_comparator { * @param[in] obj The new contact to add into the monitoring engine. */ void applier::contact::add_object(configuration::contact const& obj) { + // Make sure we have the data we need. + if (obj.contact_name().empty()) + throw engine_error() << "Could not register contact with an empty name"; + // Logging. engine_logger(logging::dbg_config, logging::more) << "Creating new contact '" << obj.contact_name() << "'."; @@ -98,70 +102,22 @@ void applier::contact::add_object(configuration::contact const& obj) { engine::contact::contacts.insert({c->get_name(), c}); // Add all custom variables. - for (map_customvar::const_iterator it(obj.customvariables().begin()), - end(obj.customvariables().end()); + for (auto it = obj.customvariables().begin(), + end = obj.customvariables().end(); it != end; ++it) { - c->get_custom_variables()[it->first] = it->second; + auto& cv = c->get_custom_variables()[it->first]; + cv.set_value(it->second.value()); + cv.set_sent(it->second.is_sent()); if (it->second.is_sent()) { timeval tv(get_broker_timestamp(nullptr)); broker_custom_variable(NEBTYPE_CONTACTCUSTOMVARIABLE_ADD, c.get(), - it->first.c_str(), it->second.get_value().c_str(), + it->first.c_str(), it->second.value().c_str(), &tv); } } } -/** - * @brief Expand a contact. - * - * During expansion, the contact will be added to its contact groups. - * These will be modified in the state. - * - * @param[in,out] s Configuration state. - */ -void applier::contact::expand_objects(configuration::state& s) { - // Browse all contacts. - for (configuration::set_contact::iterator it_contact(s.contacts().begin()), - end_contact(s.contacts().end()); - it_contact != end_contact; ++it_contact) { - // Should custom variables be sent to broker ? - map_customvar& mcv( - const_cast(it_contact->customvariables())); - for (map_customvar::iterator it{mcv.begin()}, end{mcv.end()}; it != end; - ++it) { - if (!s.enable_macros_filter() || - s.macros_filter().find(it->first) != s.macros_filter().end()) { - it->second.set_sent(true); - } - } - - // Browse current contact's groups. - for (set_string::const_iterator - it_group(it_contact->contactgroups().begin()), - end_group(it_contact->contactgroups().end()); - it_group != end_group; ++it_group) { - // Find contact group. - configuration::set_contactgroup::iterator group( - s.contactgroups_find(*it_group)); - if (group == s.contactgroups().end()) - throw(engine_error() - << "Could not add contact '" << it_contact->contact_name() - << "' to non-existing contact group '" << *it_group << "'"); - - // Remove contact group from state. - configuration::contactgroup backup(*group); - s.contactgroups().erase(group); - - // Add contact to group members. - backup.members().insert(it_contact->contact_name()); - - // Reinsert contact group. - s.contactgroups().insert(backup); - } - } -} - /** * Modified contact. * @@ -298,20 +254,22 @@ void applier::contact::modify_object(configuration::contact const& obj) { if (cus.second.is_sent()) { timeval tv(get_broker_timestamp(nullptr)); broker_custom_variable(NEBTYPE_CONTACTCUSTOMVARIABLE_DELETE, c, - cus.first.c_str(), - cus.second.get_value().c_str(), &tv); + cus.first.c_str(), cus.second.value().c_str(), + &tv); } } c->get_custom_variables().clear(); for (auto& cus : obj.customvariables()) { - c->get_custom_variables()[cus.first] = cus.second; + auto& cv = c->get_custom_variables()[cus.first]; + cv.set_value(cus.second.value()); + cv.set_sent(cus.second.is_sent()); if (cus.second.is_sent()) { timeval tv(get_broker_timestamp(nullptr)); broker_custom_variable(NEBTYPE_CONTACTCUSTOMVARIABLE_ADD, c, - cus.first.c_str(), - cus.second.get_value().c_str(), &tv); + cus.first.c_str(), cus.second.value().c_str(), + &tv); } } } @@ -358,12 +316,61 @@ void applier::contact::remove_object(configuration::contact const& obj) { config->contacts().erase(obj); } +/** + * @brief Expand a contact. + * + * During expansion, the contact will be added to its contact groups. + * These will be modified in the state. + * + * @param[in,out] s Configuration state. + */ +void applier::contact::expand_objects(configuration::state& s) { + // Browse all contacts. + configuration::set_contact new_contacts; + // We loop on s.contacts() but we make a copy of each element because the + // container is a set and changing its element has an impact on the order + // they are stored. So we copy each element, modify them and move the result + // to a new set. + for (auto contact : s.contacts()) { + // Should custom variables be sent to broker ? + auto& mcv = contact.mutable_customvariables(); + for (auto& cv : mcv) { + if (!s.enable_macros_filter() || + s.macros_filter().find(cv.first) != s.macros_filter().end()) { + cv.second.set_sent(true); + } + } + + // Browse current contact's groups. + for (auto& g : contact.contactgroups()) { + // Find contact group. + configuration::set_contactgroup::iterator group(s.contactgroups_find(g)); + if (group == s.contactgroups().end()) + throw(engine_error() + << "Could not add contact '" << contact.contact_name() + << "' to non-existing contact group '" << g << "'"); + + // Remove contact group from state. + configuration::contactgroup backup(*group); + s.contactgroups().erase(group); + + // Add contact to group members. + backup.members().insert(contact.contact_name()); + + // Reinsert contact group. + s.contactgroups().insert(backup); + } + new_contacts.insert(std::move(contact)); + } + s.contacts() = std::move(new_contacts); +} + /** * Resolve a contact. * * @param[in,out] obj Object to resolve. */ -void applier::contact::resolve_object(configuration::contact const& obj) { +void applier::contact::resolve_object(const configuration::contact& obj) { // Logging. engine_logger(logging::dbg_config, logging::more) << "Resolving contact '" << obj.contact_name() << "'."; diff --git a/engine/src/configuration/applier/host.cc b/engine/src/configuration/applier/host.cc index 6ca6239e0a8..8459866d7ac 100644 --- a/engine/src/configuration/applier/host.cc +++ b/engine/src/configuration/applier/host.cc @@ -119,15 +119,16 @@ void applier::host::add_object(configuration::host const& obj) { h->get_contactgroups().insert({*it, nullptr}); // Custom variables. - for (map_customvar::const_iterator it(obj.customvariables().begin()), - end(obj.customvariables().end()); + for (auto it = obj.customvariables().begin(), + end = obj.customvariables().end(); it != end; ++it) { - h->custom_variables[it->first] = it->second; + h->custom_variables[it->first] = + engine::customvariable(it->second.value(), it->second.is_sent()); if (it->second.is_sent()) { timeval tv(get_broker_timestamp(nullptr)); broker_custom_variable(NEBTYPE_HOSTCUSTOMVARIABLE_ADD, h.get(), - it->first.c_str(), it->second.get_value().c_str(), + it->first.c_str(), it->second.value().c_str(), &tv); } } @@ -169,53 +170,6 @@ void applier::host::add_object(configuration::host const& obj) { h.get(), MODATTR_ALL); } -/** - * @brief Expand a host. - * - * During expansion, the host will be added to its host groups. These - * will be modified in the state. - * - * @param[int,out] s Configuration state. - */ -void applier::host::expand_objects(configuration::state& s) { - // Browse all hosts. - for (auto& host_cfg : s.hosts()) { - // Should custom variables be sent to broker ? - for (map_customvar::iterator - it(const_cast(host_cfg.customvariables()).begin()), - end(const_cast(host_cfg.customvariables()).end()); - it != end; ++it) { - if (!s.enable_macros_filter() || - s.macros_filter().find(it->first) != s.macros_filter().end()) { - it->second.set_sent(true); - } - } - - // Browse current host's groups. - for (set_string::const_iterator it_group(host_cfg.hostgroups().begin()), - end_group(host_cfg.hostgroups().end()); - it_group != end_group; ++it_group) { - // Find host group. - configuration::set_hostgroup::iterator group( - s.hostgroups_find(*it_group)); - if (group == s.hostgroups().end()) - throw(engine_error() - << "Could not add host '" << host_cfg.host_name() - << "' to non-existing host group '" << *it_group << "'"); - - // Remove host group from state. - configuration::hostgroup backup(*group); - s.hostgroups().erase(group); - - // Add host to group members. - backup.members().insert(host_cfg.host_name()); - - // Reinsert host group. - s.hostgroups().insert(backup); - } - } -} - /** * Modified host. * @@ -381,19 +335,20 @@ void applier::host::modify_object(configuration::host const& obj) { timeval tv(get_broker_timestamp(nullptr)); broker_custom_variable(NEBTYPE_HOSTCUSTOMVARIABLE_DELETE, it_obj->second.get(), c.first.c_str(), - c.second.get_value().c_str(), &tv); + c.second.value().c_str(), &tv); } } it_obj->second->custom_variables.clear(); for (auto& c : obj.customvariables()) { - it_obj->second->custom_variables[c.first] = c.second; + it_obj->second->custom_variables[c.first] = + engine::customvariable(c.second.value(), c.second.is_sent()); if (c.second.is_sent()) { timeval tv(get_broker_timestamp(nullptr)); broker_custom_variable(NEBTYPE_HOSTCUSTOMVARIABLE_ADD, it_obj->second.get(), c.first.c_str(), - c.second.get_value().c_str(), &tv); + c.second.value().c_str(), &tv); } } } @@ -540,3 +495,52 @@ void applier::host::resolve_object(configuration::host const& obj) { // Resolve host. it->second->resolve(config_warnings, config_errors); } + +/** + * @brief Expand a host. + * + * During expansion, the host will be added to its host groups. These + * will be modified in the state. + * + * @param[int,out] s Configuration state. + */ +void applier::host::expand_objects(configuration::state& s) { + // Browse all hosts. + set_host new_hosts; + for (auto host_cfg : s.hosts()) { + // Should custom variables be sent to broker ? + for (auto it = host_cfg.mut_customvariables().begin(), + end = host_cfg.mut_customvariables().end(); + it != end; ++it) { + if (!s.enable_macros_filter() || + s.macros_filter().find(it->first) != s.macros_filter().end()) { + it->second.set_sent(true); + } + } + + // Browse current host's groups. + for (set_string::const_iterator it_group(host_cfg.hostgroups().begin()), + end_group(host_cfg.hostgroups().end()); + it_group != end_group; ++it_group) { + // Find host group. + configuration::set_hostgroup::iterator group( + s.hostgroups_find(*it_group)); + if (group == s.hostgroups().end()) + throw(engine_error() + << "Could not add host '" << host_cfg.host_name() + << "' to non-existing host group '" << *it_group << "'"); + + // Remove host group from state. + configuration::hostgroup backup(*group); + s.hostgroups().erase(group); + + // Add host to group members. + backup.members().insert(host_cfg.host_name()); + + // Reinsert host group. + s.hostgroups().insert(backup); + } + new_hosts.insert(host_cfg); + } + s.hosts() = std::move(new_hosts); +} diff --git a/engine/src/configuration/applier/service.cc b/engine/src/configuration/applier/service.cc index e26d4f3d955..3d83fb17eb5 100644 --- a/engine/src/configuration/applier/service.cc +++ b/engine/src/configuration/applier/service.cc @@ -113,7 +113,7 @@ void applier::service::add_object(configuration::service const& obj) { obj.service_description(), *obj.hosts().begin()); // Add service to the global configuration set. - config->services().insert(obj); + config->mut_services().insert(obj); // Create service. engine::service* svc{add_service( @@ -185,15 +185,16 @@ void applier::service::add_object(configuration::service const& obj) { svc->get_contactgroups().insert({*it, nullptr}); // Add custom variables. - for (map_customvar::const_iterator it(obj.customvariables().begin()), - end(obj.customvariables().end()); + for (auto it = obj.customvariables().begin(), + end = obj.customvariables().end(); it != end; ++it) { - svc->custom_variables[it->first] = it->second; + svc->custom_variables[it->first] = + engine::customvariable(it->second.value(), it->second.is_sent()); if (it->second.is_sent()) { timeval tv(get_broker_timestamp(nullptr)); broker_custom_variable(NEBTYPE_SERVICECUSTOMVARIABLE_ADD, svc, - it->first.c_str(), it->second.get_value().c_str(), + it->first.c_str(), it->second.value().c_str(), &tv); } } @@ -238,13 +239,10 @@ void applier::service::add_object(configuration::service const& obj) { void applier::service::expand_objects(configuration::state& s) { // Browse all services. configuration::set_service expanded; - for (configuration::set_service::iterator it_svc(s.services().begin()), - end_svc(s.services().end()); - it_svc != end_svc; ++it_svc) { + for (auto svc_cfg : s.services()) { // Should custom variables be sent to broker ? - for (map_customvar::iterator - it(const_cast(it_svc->customvariables()).begin()), - end(const_cast(it_svc->customvariables()).end()); + for (auto it = svc_cfg.mut_customvariables().begin(), + end = svc_cfg.mut_customvariables().end(); it != end; ++it) { if (!s.enable_macros_filter() || s.macros_filter().find(it->first) != s.macros_filter().end()) { @@ -256,24 +254,24 @@ void applier::service::expand_objects(configuration::state& s) { std::set target_hosts; // Hosts members. - target_hosts = it_svc->hosts(); + target_hosts = svc_cfg.hosts(); // Host group members. - for (set_string::const_iterator it(it_svc->hostgroups().begin()), - end(it_svc->hostgroups().end()); + for (set_string::const_iterator it(svc_cfg.hostgroups().begin()), + end(svc_cfg.hostgroups().end()); it != end; ++it) { // Find host group. set_hostgroup::iterator it2(s.hostgroups_find(*it)); if (it2 == s.hostgroups().end()) throw(engine_error() << "Could not find host group '" << *it << "' on which to apply service '" - << it_svc->service_description() << "'"); + << svc_cfg.service_description() << "'"); // Check host group and user configuration. if (it2->members().empty() && !s.allow_empty_hostgroup_assignment()) throw(engine_error() << "Could not expand host group '" << *it << "' specified in service '" - << it_svc->service_description() << "'"); + << svc_cfg.service_description() << "'"); // Add host group members. target_hosts.insert(it2->members().begin(), it2->members().end()); @@ -284,7 +282,7 @@ void applier::service::expand_objects(configuration::state& s) { end(target_hosts.end()); it != end; ++it) { // Create service instance. - configuration::service svc(*it_svc); + configuration::service svc(svc_cfg); svc.hostgroups().clear(); svc.hosts().clear(); svc.hosts().insert(*it); @@ -301,7 +299,7 @@ void applier::service::expand_objects(configuration::state& s) { } // Set expanded services in configuration state. - s.services().swap(expanded); + s.mut_services().swap(expanded); } /** @@ -340,8 +338,8 @@ void applier::service::modify_object(configuration::service const& obj) { // Update the global configuration set. configuration::service obj_old(*it_cfg); - config->services().erase(it_cfg); - config->services().insert(obj); + config->mut_services().erase(it_cfg); + config->mut_services().insert(obj); // Modify properties. if (it_obj->second->get_hostname() != *obj.hosts().begin() || @@ -482,20 +480,19 @@ void applier::service::modify_object(configuration::service const& obj) { if (c.second.is_sent()) { timeval tv(get_broker_timestamp(nullptr)); broker_custom_variable(NEBTYPE_SERVICECUSTOMVARIABLE_DELETE, s.get(), - c.first.c_str(), c.second.get_value().c_str(), - &tv); + c.first.c_str(), c.second.value().c_str(), &tv); } } s->custom_variables.clear(); for (auto& c : obj.customvariables()) { - s->custom_variables[c.first] = c.second; + s->custom_variables[c.first] = + engine::customvariable(c.second.value(), c.second.is_sent()); if (c.second.is_sent()) { timeval tv(get_broker_timestamp(nullptr)); broker_custom_variable(NEBTYPE_SERVICECUSTOMVARIABLE_ADD, s.get(), - c.first.c_str(), c.second.get_value().c_str(), - &tv); + c.first.c_str(), c.second.value().c_str(), &tv); } } } @@ -591,7 +588,7 @@ void applier::service::remove_object(configuration::service const& obj) { } // Remove service from the global configuration set. - config->services().erase(obj); + config->mut_services().erase(obj); } /** diff --git a/engine/src/configuration/applier/state.cc b/engine/src/configuration/applier/state.cc index 34b9c2d41f0..30c687fabb2 100644 --- a/engine/src/configuration/applier/state.cc +++ b/engine/src/configuration/applier/state.cc @@ -1471,7 +1471,7 @@ void applier::state::_processing(configuration::state& new_cfg, config->hostgroups()); // Resolve services. - _resolve(config->services()); + _resolve(config->mut_services()); // Resolve anomalydetections. _resolve( diff --git a/engine/src/configuration/contact.cc b/engine/src/configuration/contact.cc index ea0733d2364..874e74b4fec 100644 --- a/engine/src/configuration/contact.cc +++ b/engine/src/configuration/contact.cc @@ -1,5 +1,5 @@ /** - * Copyright 2011-2019 Centreon (https://www.centreon.com/) + * Copyright 2011-2024 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -234,7 +234,6 @@ bool contact::operator<(contact const& other) const noexcept { void contact::check_validity() const { if (_contact_name.empty()) throw(engine_error() << "Contact has no name (property 'contact_name')"); - return; } /** @@ -293,7 +292,7 @@ bool contact::parse(char const* key, char const* value) { if (!strncmp(key, ADDRESS_PROPERTY, sizeof(ADDRESS_PROPERTY) - 1)) return _set_address(key + sizeof(ADDRESS_PROPERTY) - 1, value); else if (key[0] == '_') { - map_customvar::iterator it(_customvariables.find(key + 1)); + auto it = _customvariables.find(key + 1); if (it == _customvariables.end()) _customvariables[key + 1] = customvariable(value); else @@ -363,7 +362,8 @@ std::string const& contact::contact_name() const noexcept { * * @return The customvariables. */ -map_customvar const& contact::customvariables() const noexcept { +const std::unordered_map& +contact::customvariables() const noexcept { return _customvariables; } @@ -372,7 +372,8 @@ map_customvar const& contact::customvariables() const noexcept { * * @return The customvariables. */ -map_customvar& contact::customvariables() noexcept { +std::unordered_map& +contact::mutable_customvariables() noexcept { return _customvariables; } @@ -501,7 +502,7 @@ std::string const& contact::timezone() const noexcept { * * @return True on success, otherwise false. */ -bool contact::_set_address(std::string const& key, std::string const& value) { +bool contact::_set_address(const std::string& key, const std::string& value) { unsigned int id; if (!string::to(key.c_str(), id) || (id < 1) || (id > MAX_ADDRESSES)) return false; diff --git a/engine/src/configuration/host.cc b/engine/src/configuration/host.cc index 57870514bd5..6b514d39037 100644 --- a/engine/src/configuration/host.cc +++ b/engine/src/configuration/host.cc @@ -487,7 +487,6 @@ void host::merge(object const& obj) { MRG_DEFAULT(_host_name); MRG_DEFAULT(_icon_image); MRG_DEFAULT(_icon_image_alt); - MRG_OPTION(_initial_state); MRG_OPTION(_low_flap_threshold); MRG_OPTION(_max_check_attempts); MRG_DEFAULT(_notes); @@ -526,7 +525,7 @@ bool host::parse(char const* key, char const* value) { if (it != _setters.end()) return (it->second)(*this, value); if (key[0] == '_') { - map_customvar::iterator it(_customvariables.find(key + 1)); + auto it = _customvariables.find(key + 1); if (it == _customvariables.end()) _customvariables[key + 1] = customvariable(value); else @@ -659,7 +658,8 @@ point_3d const& host::coords_3d() const noexcept { * * @return The customvariables. */ -engine::map_customvar const& host::customvariables() const noexcept { +const std::unordered_map& host::customvariables() + const noexcept { return _customvariables; } @@ -668,7 +668,8 @@ engine::map_customvar const& host::customvariables() const noexcept { * * @return The customvariables. */ -engine::map_customvar& host::customvariables() noexcept { +std::unordered_map& +host::mut_customvariables() noexcept { return _customvariables; } diff --git a/engine/src/configuration/parser.cc b/engine/src/configuration/parser.cc index 5c017842d1f..112ef90061c 100644 --- a/engine/src/configuration/parser.cc +++ b/engine/src/configuration/parser.cc @@ -96,7 +96,7 @@ void parser::parse(std::string const& path, state& config) { config.servicedependencies()); _insert(_lst_objects[object::serviceescalation], config.serviceescalations()); _insert(_map_objects[object::servicegroup], config.servicegroups()); - _insert(_lst_objects[object::service], config.services()); + _insert(_lst_objects[object::service], config.mut_services()); _insert(_lst_objects[object::anomalydetection], config.anomalydetections()); _insert(_map_objects[object::timeperiod], config.timeperiods()); _insert(_lst_objects[object::severity], config.mut_severities()); diff --git a/engine/src/configuration/service.cc b/engine/src/configuration/service.cc index fdeb2d1d982..7a3f99568b9 100644 --- a/engine/src/configuration/service.cc +++ b/engine/src/configuration/service.cc @@ -900,7 +900,7 @@ bool service::parse(char const* key, char const* value) { return (it->second)(*this, value); if (key[0] == '_') { - map_customvar::iterator it{_customvariables.find(key + 1)}; + auto it = _customvariables.find(key + 1); if (it == _customvariables.end()) _customvariables[key + 1] = customvariable(value); else @@ -1042,8 +1042,8 @@ bool service::contacts_defined() const noexcept { * * @return The customvariables. */ -com::centreon::engine::map_customvar const& service::customvariables() - const noexcept { +const std::unordered_map& +service::customvariables() const noexcept { return _customvariables; } @@ -1052,7 +1052,8 @@ com::centreon::engine::map_customvar const& service::customvariables() * * @return The customvariables. */ -com::centreon::engine::map_customvar& service::customvariables() noexcept { +std::unordered_map& +service::mut_customvariables() noexcept { return _customvariables; } @@ -1261,7 +1262,6 @@ bool service::notifications_enabled() const noexcept { */ void service::notification_interval(unsigned int interval) noexcept { _notification_interval = interval; - return; } /** @@ -1298,7 +1298,6 @@ unsigned short service::notification_options() const noexcept { */ void service::notification_period(std::string const& period) { _notification_period = period; - return; } /** @@ -1434,7 +1433,6 @@ unsigned short service::stalking_options() const noexcept { */ void service::timezone(std::string const& time_zone) { _timezone = time_zone; - return; } /** diff --git a/engine/src/configuration/state.cc b/engine/src/configuration/state.cc index 2c5c833e402..69d0159a562 100644 --- a/engine/src/configuration/state.cc +++ b/engine/src/configuration/state.cc @@ -3218,7 +3218,7 @@ set_service const& state::services() const noexcept { * * @return All engine services. */ -set_service& state::services() noexcept { +set_service& state::mut_services() noexcept { return _services; } diff --git a/engine/src/customvariable.cc b/engine/src/customvariable.cc index 99be377b54f..077a437048d 100644 --- a/engine/src/customvariable.cc +++ b/engine/src/customvariable.cc @@ -83,7 +83,7 @@ bool customvariable::is_sent() const { * * @return The value of the customvariable */ -std::string const& customvariable::get_value() const { +const std::string& customvariable::value() const { return _value; } diff --git a/engine/src/macros.cc b/engine/src/macros.cc index 451c3756464..673b76b8856 100644 --- a/engine/src/macros.cc +++ b/engine/src/macros.cc @@ -644,7 +644,7 @@ int grab_custom_object_macro_r(nagios_macros* mac, /* get the custom variable */ for (auto const& cv : vars) { if (macro_name == cv.first) { - output = cv.second.get_value(); + output = cv.second.value(); result = OK; break; } diff --git a/engine/src/retention/applier/contact.cc b/engine/src/retention/applier/contact.cc index 69f9c1fbca3..5ffce899e14 100644 --- a/engine/src/retention/applier/contact.cc +++ b/engine/src/retention/applier/contact.cc @@ -1,21 +1,21 @@ /** -* Copyright 2011-2013,2016 Merethis -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2013,2016 Merethis + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/retention/applier/contact.hh" #include "com/centreon/engine/configuration/applier/state.hh" @@ -129,7 +129,7 @@ void applier::contact::_update(configuration::state const& config, if (!state.customvariables().empty() && (obj->get_modified_attributes() & MODATTR_CUSTOM_VARIABLE)) { for (auto const& cv : state.customvariables()) { - obj->get_custom_variables()[cv.first].update(cv.second.get_value()); + obj->get_custom_variables()[cv.first].update(cv.second.value()); } } } diff --git a/engine/src/retention/applier/host.cc b/engine/src/retention/applier/host.cc index c4c3057d216..c1f6e94f6a9 100644 --- a/engine/src/retention/applier/host.cc +++ b/engine/src/retention/applier/host.cc @@ -1,21 +1,21 @@ /** -* Copyright 2011-2013,2015-2016,2022 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2013,2015-2016,2022 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "com/centreon/engine/retention/applier/host.hh" #include "com/centreon/engine/configuration/applier/state.hh" @@ -255,7 +255,7 @@ void applier::host::_update(configuration::state const& config, for (map_customvar::const_iterator it(state.customvariables().begin()), end(state.customvariables().end()); it != end; ++it) - obj.custom_variables[it->first].update(it->second.get_value()); + obj.custom_variables[it->first].update(it->second.value()); } } // Adjust modified attributes if necessary. diff --git a/engine/src/retention/applier/service.cc b/engine/src/retention/applier/service.cc index d8e060eec3b..13783948e2d 100644 --- a/engine/src/retention/applier/service.cc +++ b/engine/src/retention/applier/service.cc @@ -264,7 +264,7 @@ void applier::service::update(configuration::state const& config, for (map_customvar::const_iterator it(state.customvariables().begin()), end(state.customvariables().end()); it != end; ++it) - obj.custom_variables[it->first].update(it->second.get_value()); + obj.custom_variables[it->first].update(it->second.value()); } } // Adjust modified attributes if necessary. diff --git a/engine/src/retention/dump.cc b/engine/src/retention/dump.cc index 37a345833be..5e8962e3917 100644 --- a/engine/src/retention/dump.cc +++ b/engine/src/retention/dump.cc @@ -191,7 +191,7 @@ std::ostream& dump::customvariables(std::ostream& os, map_customvar const& obj) { for (auto const& cv : obj) os << "_" << cv.first << "=" << cv.second.has_been_modified() << "," - << cv.second.get_value() << "\n"; + << cv.second.value() << "\n"; return os; } diff --git a/engine/src/xsddefault.cc b/engine/src/xsddefault.cc index 9ae791a047d..93a219b608d 100644 --- a/engine/src/xsddefault.cc +++ b/engine/src/xsddefault.cc @@ -449,7 +449,7 @@ int xsddefault_save_status_data() { for (auto const& cv : it->second->custom_variables) { if (!cv.first.empty()) stream << "\t_" << cv.first << "=" << cv.second.has_been_modified() - << ";" << cv.second.get_value() << "\n"; + << ";" << cv.second.value() << "\n"; } stream << "\t}\n\n"; } @@ -625,7 +625,7 @@ int xsddefault_save_status_data() { for (auto const& cv : it->second->custom_variables) { if (!cv.first.empty()) stream << "\t_" << cv.first << "=" << cv.second.has_been_modified() - << ";" << cv.second.get_value() << "\n"; + << ";" << cv.second.value() << "\n"; } stream << "\t}\n\n"; } @@ -669,7 +669,7 @@ int xsddefault_save_status_data() { for (auto const& cv : cntct->get_custom_variables()) { if (!cv.first.empty()) stream << "\t_" << cv.first << "=" << cv.second.has_been_modified() - << ";" << cv.second.get_value() << "\n"; + << ";" << cv.second.value() << "\n"; } stream << "\t}\n\n"; } diff --git a/engine/tests/configuration/applier/applier-contact.cc b/engine/tests/configuration/applier/applier-contact.cc index d55dc5ab9ad..cf7752674be 100644 --- a/engine/tests/configuration/applier/applier-contact.cc +++ b/engine/tests/configuration/applier/applier-contact.cc @@ -133,8 +133,7 @@ TEST_F(ApplierContact, ModifyContactFromConfig) { ASSERT_TRUE(ctct.parse("service_notification_commands", "svc1,svc2")); ASSERT_TRUE(ctct.parse("_superVar", "superValue")); ASSERT_TRUE(ctct.customvariables().size() == 1); - ASSERT_TRUE(ctct.customvariables().at("superVar").get_value() == - "superValue"); + ASSERT_TRUE(ctct.customvariables().at("superVar").value() == "superValue"); configuration::applier::command cmd_aply; configuration::applier::connector cnn_aply; @@ -159,9 +158,9 @@ TEST_F(ApplierContact, ModifyContactFromConfig) { contact_map::const_iterator ct_it{engine::contact::contacts.find("test")}; ASSERT_TRUE(ct_it != engine::contact::contacts.end()); ASSERT_EQ(ct_it->second->get_custom_variables().size(), 2u); - ASSERT_TRUE(ct_it->second->get_custom_variables()["superVar"].get_value() == + ASSERT_TRUE(ct_it->second->get_custom_variables()["superVar"].value() == "Super"); - ASSERT_TRUE(ct_it->second->get_custom_variables()["superVar1"].get_value() == + ASSERT_TRUE(ct_it->second->get_custom_variables()["superVar1"].value() == "Super1"); ASSERT_TRUE(ct_it->second->get_alias() == "newAlias"); ASSERT_FALSE(ct_it->second->notify_on(notifier::service_notification, diff --git a/engine/tests/configuration/applier/applier-state.cc b/engine/tests/configuration/applier/applier-state.cc index cd6feb66e0a..cf5251b391a 100644 --- a/engine/tests/configuration/applier/applier-state.cc +++ b/engine/tests/configuration/applier/applier-state.cc @@ -891,7 +891,7 @@ TEST_F(ApplierState, StateLegacyParsing) { ASSERT_EQ(adit->dependent_service_id(), 1); ASSERT_TRUE(adit->metric_name() == "metric2"); ASSERT_EQ(adit->customvariables().size(), 1); - ASSERT_EQ(adit->customvariables().at("ad_cv").get_value(), + ASSERT_EQ(adit->customvariables().at("ad_cv").value(), std::string("this_is_a_test")); ASSERT_EQ(adit->contactgroups().size(), 2); ASSERT_EQ(adit->contacts().size(), 1); diff --git a/engine/tests/enginerpc/enginerpc.cc b/engine/tests/enginerpc/enginerpc.cc index 762e1886436..2cc77c5d18e 100644 --- a/engine/tests/enginerpc/enginerpc.cc +++ b/engine/tests/enginerpc/enginerpc.cc @@ -1688,7 +1688,7 @@ TEST_F(EngineRpc, ChangeHostObjectCustomVar) { th->join(); ASSERT_EQ(_host->custom_variables.size(), 1u); - ASSERT_EQ(_host->custom_variables["TEST_VAR"].get_value(), "test_val"); + ASSERT_EQ(_host->custom_variables["TEST_VAR"].value(), "test_val"); _host->custom_variables.clear(); ASSERT_EQ(_host->custom_variables.size(), 0u); erpc.shutdown(); @@ -1715,7 +1715,7 @@ TEST_F(EngineRpc, ChangeServiceObjectCustomVar) { th->join(); ASSERT_EQ(_svc->custom_variables.size(), 1u); - ASSERT_EQ(_svc->custom_variables["TEST_VAR"].get_value(), "test_val"); + ASSERT_EQ(_svc->custom_variables["TEST_VAR"].value(), "test_val"); _svc->custom_variables.clear(); ASSERT_EQ(_svc->custom_variables.size(), 0u); erpc.shutdown(); @@ -1740,8 +1740,7 @@ TEST_F(EngineRpc, ChangeContactObjectCustomVar) { condvar.notify_one(); th->join(); ASSERT_EQ(_contact->get_custom_variables().size(), 1u); - ASSERT_EQ(_contact->get_custom_variables()["TEST_VAR"].get_value(), - "test_val"); + ASSERT_EQ(_contact->get_custom_variables()["TEST_VAR"].value(), "test_val"); erpc.shutdown(); } From 51864fc780cd80e4e978a1a19b2ddfcc5f352cf6 Mon Sep 17 00:00:00 2001 From: Kevin Duret Date: Thu, 6 Jun 2024 10:17:06 +0200 Subject: [PATCH 25/60] fix(logs): do not insert logs when testing configuration (#1406) * fix(engine): when verify_config is enabled, loggers still log to stdout * fix(engine): same behaviour with test_scheduling REFS: MON-108616 --------- Co-authored-by: David Boucher --- engine/src/configuration/applier/state.cc | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/engine/src/configuration/applier/state.cc b/engine/src/configuration/applier/state.cc index 30c687fabb2..c7cbb337439 100644 --- a/engine/src/configuration/applier/state.cc +++ b/engine/src/configuration/applier/state.cc @@ -1139,6 +1139,12 @@ void applier::state::_check_hosts() const { #endif void applier::state::apply_log_config(configuration::state& new_cfg) { + /* During the verification, loggers write to stdout. After this step, they + * will log as it is written in their configurations. So if we check the + * configuration, we don't want to change them. */ + if (verify_config || test_scheduling) + return; + using log_v2_config = com::centreon::common::log_v2::config; log_v2_config::logger_type log_type; if (new_cfg.log_v2_enabled()) { From 6717e1a6e7bf7bd231287bc5a356485aef7ba23a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane=20Chapron?= <34628915+sc979@users.noreply.github.com> Date: Thu, 6 Jun 2024 12:24:57 +0200 Subject: [PATCH 26/60] fix(ci): force veracode action to 0.2.6 (#1401) --- .github/workflows/veracode-analysis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/veracode-analysis.yml b/.github/workflows/veracode-analysis.yml index db17f1ed72a..5a29d429e75 100644 --- a/.github/workflows/veracode-analysis.yml +++ b/.github/workflows/veracode-analysis.yml @@ -169,7 +169,7 @@ jobs: key: "${{ inputs.module_name }}-${{ github.sha }}-${{ github.run_id }}-veracode-binary" - name: Sandbox scan - uses: veracode/veracode-uploadandscan-action@v1.0 + uses: veracode/veracode-uploadandscan-action@f7e1fbf02c5c899fba9f12e3f537b62f2f1230e1 # master using 0.2.6 continue-on-error: ${{ vars.VERACODE_CONTINUE_ON_ERROR == 'true' }} with: appname: "${{ inputs.module_name }}" From 5635b9279a4a0284678005ff2ebcb1c203e0bd74 Mon Sep 17 00:00:00 2001 From: jean-christophe81 <98889244+jean-christophe81@users.noreply.github.com> Date: Thu, 6 Jun 2024 13:22:02 +0200 Subject: [PATCH 27/60] enh(engine): new extractor and telegraf nagios converter REFS: MON-35539 --- .../Dockerfile.centreon-collect-alma9-test | 2 +- ...file.centreon-collect-debian-bookworm-test | 2 +- ...file.centreon-collect-debian-bullseye-test | 2 +- ...ckerfile.centreon-collect-mysql-alma9-test | 2 +- broker/http_tsdb/test/stream_test.cc | 2 +- broker/neb/precomp_inc/precomp.hpp | 1 + broker/sql/precomp_inc/precomp.hpp | 35 +- broker/storage/precomp_inc/precomp.hpp | 35 +- broker/test/CMakeLists.txt | 1 + broker/unified_sql/precomp_inc/precomp.hpp | 35 +- common/http/CMakeLists.txt | 3 +- common/http/doc/common-http.md | 9 +- .../centreon/common/http/http_connection.hh | 13 +- .../centreon/common/http/https_connection.hh | 7 +- common/http/src/http_client.cc | 2 +- common/http/src/http_connection.cc | 73 ++- common/http/src/http_server.cc | 29 +- common/http/src/https_connection.cc | 122 ++++- common/http/test/http_client_test.cc | 5 +- common/http/test/http_connection_test.cc | 54 +-- common/http/test/http_server_test.cc | 452 ++++++++++++++++++ common/precomp_inc/precomp.hh | 3 - common/tests/CMakeLists.txt | 17 +- engine/CMakeLists.txt | 3 + engine/enginerpc/precomp_inc/precomp.hh | 38 +- .../com/centreon/engine/command_manager.hh | 4 +- .../com/centreon/engine/commands/command.hh | 9 +- .../com/centreon/engine/commands/forward.hh | 2 +- engine/inc/com/centreon/engine/service.hh | 4 +- .../external_commands/precomp_inc/precomp.hh | 38 +- engine/modules/opentelemetry/CMakeLists.txt | 2 + .../opentelemetry/doc/opentelemetry.md | 206 ++++++++ .../modules/opentelemetry/data_point_fifo.hh | 2 + .../modules/opentelemetry/open_telemetry.hh | 7 + .../modules/opentelemetry/otl_config.hh | 8 +- .../opentelemetry/telegraf/conf_server.hh | 110 +++++ .../telegraf/nagios_converter.hh | 118 +++++ .../opentelemetry/src/data_point_fifo.cc | 11 + engine/modules/opentelemetry/src/main.cc | 1 + .../opentelemetry/src/open_telemetry.cc | 56 +++ .../modules/opentelemetry/src/otl_config.cc | 15 +- .../opentelemetry/src/otl_converter.cc | 18 +- .../opentelemetry/src/telegraf/conf_server.cc | 435 +++++++++++++++++ .../src/telegraf/nagios_converter.cc | 265 ++++++++++ engine/precomp_inc/precomp.hh | 36 +- engine/src/configuration/applier/command.cc | 2 +- engine/src/main.cc | 2 + engine/tests/CMakeLists.txt | 3 + .../tests/opentelemetry/opentelemetry_test.cc | 240 ++++++++++ .../tests/opentelemetry/otl_converter_test.cc | 109 +++++ ...ntreon-engine-opentelemetry-debuginfo.yaml | 42 ++ packaging/centreon-engine-opentelemetry.yaml | 34 ++ tests/README.md | 2 +- tests/broker-engine/notifications.robot | 9 +- tests/broker-engine/opentelemetry.robot | 428 +++++++++++++++++ tests/resources/Common.py | 182 +++++++ tests/resources/Engine.py | 228 +++++++++ tests/resources/import.resource | 1 + tests/resources/opentelemetry/telegraf.conf | 54 +++ tests/resources/resources.resource | 1 + tests/resources/scripts/dump-otl-event.lua | 13 + tests/update-doc.py | 2 +- 62 files changed, 3410 insertions(+), 236 deletions(-) create mode 100644 common/http/test/http_server_test.cc create mode 100644 engine/modules/opentelemetry/doc/opentelemetry.md create mode 100644 engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/telegraf/conf_server.hh create mode 100644 engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/telegraf/nagios_converter.hh create mode 100644 engine/modules/opentelemetry/src/telegraf/conf_server.cc create mode 100644 engine/modules/opentelemetry/src/telegraf/nagios_converter.cc create mode 100644 engine/tests/opentelemetry/opentelemetry_test.cc create mode 100644 packaging/centreon-engine-opentelemetry-debuginfo.yaml create mode 100644 packaging/centreon-engine-opentelemetry.yaml create mode 100644 tests/broker-engine/opentelemetry.robot create mode 100644 tests/resources/opentelemetry/telegraf.conf create mode 100644 tests/resources/scripts/dump-otl-event.lua diff --git a/.github/docker/Dockerfile.centreon-collect-alma9-test b/.github/docker/Dockerfile.centreon-collect-alma9-test index 5663575f503..7e0bde0c59d 100644 --- a/.github/docker/Dockerfile.centreon-collect-alma9-test +++ b/.github/docker/Dockerfile.centreon-collect-alma9-test @@ -43,7 +43,7 @@ dnf clean all echo "install robot and dependencies" pip3 install -U robotframework robotframework-databaselibrary robotframework-httpctrl robotframework-examples pymysql python-dateutil psutil -pip3 install grpcio grpcio_tools py-cpuinfo cython unqlite gitpython boto3 +pip3 install grpcio grpcio_tools py-cpuinfo cython unqlite gitpython boto3 robotframework-requests cd /tmp/collect diff --git a/.github/docker/Dockerfile.centreon-collect-debian-bookworm-test b/.github/docker/Dockerfile.centreon-collect-debian-bookworm-test index 8d7ad4c1170..ade34ced961 100644 --- a/.github/docker/Dockerfile.centreon-collect-debian-bookworm-test +++ b/.github/docker/Dockerfile.centreon-collect-debian-bookworm-test @@ -39,7 +39,7 @@ apt-get clean localedef -i en_US -c -f UTF-8 -A /usr/share/locale/locale.alias en_US.UTF-8 pip3 install --break-system-packages -U robotframework robotframework-databaselibrary robotframework-httpctrl robotframework-examples pymysql python-dateutil psutil -pip3 install --break-system-packages grpcio grpcio_tools py-cpuinfo cython unqlite gitpython boto3 +pip3 install --break-system-packages grpcio grpcio_tools py-cpuinfo cython unqlite gitpython boto3 robotframework-requests cd /tmp/collect diff --git a/.github/docker/Dockerfile.centreon-collect-debian-bullseye-test b/.github/docker/Dockerfile.centreon-collect-debian-bullseye-test index 900d5642f18..d69a78fdd3e 100644 --- a/.github/docker/Dockerfile.centreon-collect-debian-bullseye-test +++ b/.github/docker/Dockerfile.centreon-collect-debian-bullseye-test @@ -39,7 +39,7 @@ apt-get clean localedef -i en_US -c -f UTF-8 -A /usr/share/locale/locale.alias en_US.UTF-8 pip3 install -U robotframework robotframework-databaselibrary robotframework-httpctrl robotframework-examples pymysql python-dateutil psutil -pip3 install grpcio grpcio_tools py-cpuinfo cython unqlite gitpython boto3 +pip3 install grpcio grpcio_tools py-cpuinfo cython unqlite gitpython boto3 robotframework-requests cd /tmp/collect diff --git a/.github/docker/Dockerfile.centreon-collect-mysql-alma9-test b/.github/docker/Dockerfile.centreon-collect-mysql-alma9-test index 06ac8b57d4d..8d5a10771f9 100644 --- a/.github/docker/Dockerfile.centreon-collect-mysql-alma9-test +++ b/.github/docker/Dockerfile.centreon-collect-mysql-alma9-test @@ -43,7 +43,7 @@ dnf clean all echo "install robot and dependencies" pip3 install -U robotframework robotframework-databaselibrary robotframework-httpctrl robotframework-examples pymysql python-dateutil psutil -pip3 install grpcio grpcio_tools py-cpuinfo cython unqlite gitpython boto3 +pip3 install grpcio grpcio_tools py-cpuinfo cython unqlite gitpython boto3 robotframework-requests cd /tmp/collect diff --git a/broker/http_tsdb/test/stream_test.cc b/broker/http_tsdb/test/stream_test.cc index 4e6d9db0ade..b7aec6f5d36 100644 --- a/broker/http_tsdb/test/stream_test.cc +++ b/broker/http_tsdb/test/stream_test.cc @@ -171,7 +171,7 @@ class connection_send_bagot : public http::connection_base { } } - void on_accept(http::connect_callback_type&& callback) override{}; + void _on_accept(http::connect_callback_type&& callback) override{}; void answer(const http::response_ptr& response, http::answer_callback_type&& callback) override {} diff --git a/broker/neb/precomp_inc/precomp.hpp b/broker/neb/precomp_inc/precomp.hpp index f1090687dce..0c373302776 100644 --- a/broker/neb/precomp_inc/precomp.hpp +++ b/broker/neb/precomp_inc/precomp.hpp @@ -32,6 +32,7 @@ #include #include +#include #include #include diff --git a/broker/sql/precomp_inc/precomp.hpp b/broker/sql/precomp_inc/precomp.hpp index 6b7691d032d..52cf1c3e3a2 100644 --- a/broker/sql/precomp_inc/precomp.hpp +++ b/broker/sql/precomp_inc/precomp.hpp @@ -1,20 +1,20 @@ -/* -** Copyright 2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CC_SQL_PRECOMP_HH #define CC_SQL_PRECOMP_HH @@ -30,6 +30,7 @@ #include #include +#include #include #include #include diff --git a/broker/storage/precomp_inc/precomp.hpp b/broker/storage/precomp_inc/precomp.hpp index 09c1d06f498..429bddd2a96 100644 --- a/broker/storage/precomp_inc/precomp.hpp +++ b/broker/storage/precomp_inc/precomp.hpp @@ -1,20 +1,20 @@ -/* -** Copyright 2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CC_STATS_PRECOMP_HH #define CC_STATS_PRECOMP_HH @@ -27,6 +27,7 @@ #include #include +#include #include #include #include diff --git a/broker/test/CMakeLists.txt b/broker/test/CMakeLists.txt index 064b57fd6d3..7f74fab7779 100644 --- a/broker/test/CMakeLists.txt +++ b/broker/test/CMakeLists.txt @@ -150,6 +150,7 @@ target_link_libraries( ${TESTS_LIBRARIES} conflictmgr centreon_common + centreon_grpc stdc++fs nlohmann_json::nlohmann_json fmt::fmt diff --git a/broker/unified_sql/precomp_inc/precomp.hpp b/broker/unified_sql/precomp_inc/precomp.hpp index 516e54ef025..2cb7740dd23 100644 --- a/broker/unified_sql/precomp_inc/precomp.hpp +++ b/broker/unified_sql/precomp_inc/precomp.hpp @@ -1,20 +1,20 @@ -/* -** Copyright 2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CC_UNIFIED_SQL_PRECOMP_HH #define CC_UNIFIED_SQL_PRECOMP_HH @@ -30,6 +30,7 @@ #include #include +#include #include #include #include diff --git a/common/http/CMakeLists.txt b/common/http/CMakeLists.txt index d57e20e73b0..2bb1e2c4fb8 100644 --- a/common/http/CMakeLists.txt +++ b/common/http/CMakeLists.txt @@ -42,7 +42,8 @@ set_target_properties(centreon_http PROPERTIES COMPILE_FLAGS "-fPIC") if(WITH_TESTING) set(TESTS_SOURCES ${TESTS_SOURCES} - ${TEST_DIR}/http_connection_test.cc ${TEST_DIR}/http_client_test.cc + ${TEST_DIR}/http_connection_test.cc + ${TEST_DIR}/http_server_test.cc PARENT_SCOPE) endif(WITH_TESTING) diff --git a/common/http/doc/common-http.md b/common/http/doc/common-http.md index 500f427c8e3..1448b32074b 100644 --- a/common/http/doc/common-http.md +++ b/common/http/doc/common-http.md @@ -117,7 +117,7 @@ class session_test : public connection_class { void wait_for_request(); - void answer(const std::shared_ptr& request); + void answer_to_request(const std::shared_ptr& request); public: session_test(const std::shared_ptr& io_context, @@ -142,7 +142,8 @@ class session_test : public connection_class { */ template void session_test::on_accept() { - connection_class::on_accept( +// lambda will be called once handshake is done + connection_class::_on_accept( [me = shared_from_this()](const boost::beast::error_code& err, const std::string&) { if (!err) @@ -167,7 +168,7 @@ void session_test::wait_for_request() { err.what()); return; } - me->answer(request); + me->answer_to_request(request); }); } @@ -180,7 +181,7 @@ void session_test::wait_for_request() { * @param request */ template -void session_test::answer( +void session_test::answer_to_request( const std::shared_ptr& request) { response_ptr resp(std::make_shared()); resp->version(request->version()); diff --git a/common/http/inc/com/centreon/common/http/http_connection.hh b/common/http/inc/com/centreon/common/http/http_connection.hh index 840d5f32c41..b650bac138b 100644 --- a/common/http/inc/com/centreon/common/http/http_connection.hh +++ b/common/http/inc/com/centreon/common/http/http_connection.hh @@ -140,6 +140,8 @@ class connection_base : public std::enable_shared_from_this { http_config::pointer _conf; + virtual void _on_accept(connect_callback_type&& callback) = 0; + public: enum e_state { e_not_connected, @@ -176,14 +178,12 @@ class connection_base : public std::enable_shared_from_this { // server version /** * @brief to override in accepted session objects - * It has to call on_accept(connect_callback_type&& callback) in order to + * It has to call _on_accept(connect_callback_type&& callback) in order to * receive * */ virtual void on_accept() {} - virtual void on_accept(connect_callback_type&& callback) = 0; - virtual void answer(const response_ptr& response, answer_callback_type&& callback) = 0; virtual void receive_request(request_callback_type&& callback) = 0; @@ -198,6 +198,9 @@ class connection_base : public std::enable_shared_from_this { asio::ip::tcp::endpoint& get_peer() { return _peer; } const asio::ip::tcp::endpoint& get_peer() const { return _peer; } + + virtual void add_keep_alive_to_server_response( + const response_ptr& response) const; }; /** @@ -247,6 +250,8 @@ class http_connection : public connection_base { send_callback_type& callback, const response_ptr& resp); + void _on_accept(connect_callback_type&& callback) override; + public: std::shared_ptr shared_from_this() { return std::static_pointer_cast( @@ -266,8 +271,6 @@ class http_connection : public connection_base { void send(request_ptr request, send_callback_type&& callback) override; - void on_accept(connect_callback_type&& callback) override; - void answer(const response_ptr& response, answer_callback_type&& callback) override; void receive_request(request_callback_type&& callback) override; diff --git a/common/http/inc/com/centreon/common/http/https_connection.hh b/common/http/inc/com/centreon/common/http/https_connection.hh index 049b5824735..5fe9daa2325 100644 --- a/common/http/inc/com/centreon/common/http/https_connection.hh +++ b/common/http/inc/com/centreon/common/http/https_connection.hh @@ -62,6 +62,8 @@ class https_connection : public connection_base { send_callback_type& callback, const response_ptr& resp); + void _on_accept(connect_callback_type&& callback) override; + public: std::shared_ptr shared_from_this() { return std::static_pointer_cast( @@ -82,8 +84,6 @@ class https_connection : public connection_base { void send(request_ptr request, send_callback_type&& callback) override; - void on_accept(connect_callback_type&& callback) override; - void answer(const response_ptr& response, answer_callback_type&& callback) override; void receive_request(request_callback_type&& callback) override; @@ -92,6 +92,9 @@ class https_connection : public connection_base { static void load_client_certificate(asio::ssl::context& ctx, const http_config::pointer& conf); + + static void load_server_certificate(asio::ssl::context& ctx, + const http_config::pointer& conf); }; } // namespace com::centreon::common::http diff --git a/common/http/src/http_client.cc b/common/http/src/http_client.cc index fee72c2c674..c7eaffa08e6 100644 --- a/common/http/src/http_client.cc +++ b/common/http/src/http_client.cc @@ -402,4 +402,4 @@ void client::_retry(const boost::beast::error_code& error, }); } } -} \ No newline at end of file +} diff --git a/common/http/src/http_connection.cc b/common/http/src/http_connection.cc index fc7d60f4597..f17ea0b5904 100644 --- a/common/http/src/http_connection.cc +++ b/common/http/src/http_connection.cc @@ -33,6 +33,8 @@ std::string connection_base::state_to_str(unsigned state) { return "e_send"; case http_connection::e_state::e_receive: return "e_receive"; + case http_connection::e_state::e_shutdown: + return "e_shutdown"; default: return fmt::format("unknown state {}", state); } @@ -105,6 +107,27 @@ void connection_base::gest_keepalive(const response_ptr& resp) { } } +/** + * @brief used on server side + * it adds keepalive header with the value of receive timeout + * + * @param response + */ +void connection_base::add_keep_alive_to_server_response( + const response_ptr& response) const { + if (_conf->get_default_http_keepalive_duration() >= std::chrono::seconds(1)) { + response->keep_alive(true); + response->insert( + boost::beast::http::field::keep_alive, + fmt::format("timeout={}", + std::chrono::duration_cast( + _conf->get_default_http_keepalive_duration()) + .count())); + } else { + response->keep_alive(false); + } +} + /************************************************************************** * http_connection **************************************************************************/ @@ -213,9 +236,9 @@ void http_connection::on_connect(const boost::beast::error_code& err, * callback is useless in this case but is mandatory to have the same interface * than https_connection * - * @param callback called via io_context::post + * @param callback called via io_context::post (must have the same signature as https) */ -void http_connection::on_accept(connect_callback_type&& callback) { +void http_connection::_on_accept(connect_callback_type&& callback) { unsigned expected = e_not_connected; if (!_state.compare_exchange_strong(expected, e_idle)) { BAD_CONNECT_STATE_ERROR("on_tcp_connect to {}, bad state {}"); @@ -291,8 +314,9 @@ void http_connection::send(request_ptr request, send_callback_type&& callback) { boost::beast::http::async_write( _socket, *request, [me = shared_from_this(), request, cb = std::move(callback)]( - const boost::beast::error_code& err, - size_t bytes_transfered) mutable { me->on_sent(err, request, cb); }); + const boost::beast::error_code& err, size_t) mutable { + me->on_sent(err, request, cb); + }); } /** @@ -331,6 +355,10 @@ void http_connection::on_sent(const boost::beast::error_code& err, request->_sent = system_clock::now(); response_ptr resp = std::make_shared(); + std::lock_guard l(_socket_m); + if (_conf->get_receive_timeout() >= std::chrono::seconds(1)) { + _socket.expires_after(_conf->get_receive_timeout()); + } boost::beast::http::async_read( _socket, _recv_buffer, *resp, [me = shared_from_this(), request, cb = std::move(callback), resp]( @@ -355,7 +383,9 @@ void http_connection::on_read(const boost::beast::error_code& err, std::string detail = fmt::format("{:p} fail receive {} from {}: {}", static_cast(this), *request, *_conf, err.message()); - SPDLOG_LOGGER_ERROR(_logger, detail); + if (err != boost::asio::error::operation_aborted) { + SPDLOG_LOGGER_ERROR(_logger, detail); + } callback(err, detail, response_ptr()); shutdown(); return; @@ -384,6 +414,13 @@ void http_connection::on_read(const boost::beast::error_code& err, callback(err, {}, resp); } +/** + * @brief server side, send response to client + * in case of receive time out < 1s, socket is closed after response sent + * + * @param response + * @param callback + */ void http_connection::answer(const response_ptr& response, answer_callback_type&& callback) { unsigned expected = e_idle; @@ -399,6 +436,8 @@ void http_connection::answer(const response_ptr& response, return; } + add_keep_alive_to_server_response(response); + std::lock_guard l(_socket_m); _socket.expires_after(_conf->get_send_timeout()); boost::beast::http::async_write( @@ -414,6 +453,9 @@ void http_connection::answer(const response_ptr& response, } else { unsigned expected = e_send; me->_state.compare_exchange_strong(expected, e_idle); + if (me->_conf->get_receive_timeout() < std::chrono::seconds(1)) { + me->shutdown(); + } } SPDLOG_LOGGER_TRACE(me->_logger, "{:p} response sent: {}", static_cast(me.get()), *response); @@ -421,6 +463,11 @@ void http_connection::answer(const response_ptr& response, }); } +/** + * @brief wait for incoming request + * + * @param callback + */ void http_connection::receive_request(request_callback_type&& callback) { unsigned expected = e_idle; if (!_state.compare_exchange_strong(expected, e_receive)) { @@ -437,16 +484,24 @@ void http_connection::receive_request(request_callback_type&& callback) { } std::lock_guard l(_socket_m); - _socket.expires_after(_conf->get_receive_timeout()); + if (_conf->get_receive_timeout() >= std::chrono::seconds(1)) + _socket.expires_after(_conf->get_receive_timeout()); + auto req = std::make_shared(); boost::beast::http::async_read( _socket, _recv_buffer, *req, [me = shared_from_this(), req, cb = std::move(callback)]( const boost::beast::error_code& ec, std::size_t) mutable { if (ec) { - SPDLOG_LOGGER_ERROR( - me->_logger, "{:p} fail to receive request from {}: {}", - static_cast(me.get()), me->get_peer(), ec.message()); + if (ec == boost::beast::http::error::end_of_stream) { + SPDLOG_LOGGER_DEBUG( + me->_logger, "{:p} fail to receive request from {}: {}", + static_cast(me.get()), me->get_peer(), ec.message()); + } else { + SPDLOG_LOGGER_ERROR( + me->_logger, "{:p} fail to receive request from {}: {}", + static_cast(me.get()), me->get_peer(), ec.message()); + } me->shutdown(); } else { unsigned expected = e_receive; diff --git a/common/http/src/http_server.cc b/common/http/src/http_server.cc index 16bfa336d36..4548279cd81 100644 --- a/common/http/src/http_server.cc +++ b/common/http/src/http_server.cc @@ -30,13 +30,22 @@ server::server(const std::shared_ptr& io_context, _conf(conf), _conn_creator(conn_creator), _acceptor(*io_context) { - _acceptor.open(_conf->get_endpoint().protocol()); - _acceptor.set_option(asio::ip::tcp::socket::reuse_address(true)); + SPDLOG_LOGGER_INFO(logger, "create http(s) server listening on {}", + conf->get_endpoint()); - // Bind to the server address - _acceptor.bind(_conf->get_endpoint()); - // Start listening for connections - _acceptor.listen(asio::ip::tcp::socket::max_listen_connections); + try { + _acceptor.open(_conf->get_endpoint().protocol()); + _acceptor.set_option(asio::ip::tcp::socket::reuse_address(true)); + + // Bind to the server address + _acceptor.bind(_conf->get_endpoint()); + // Start listening for connections + _acceptor.listen(asio::ip::tcp::socket::max_listen_connections); + } catch (const std::exception& e) { + SPDLOG_LOGGER_ERROR(logger, "fail to listen on {}: {}", + _conf->get_endpoint(), e.what()); + throw; + } } server::~server() { @@ -69,10 +78,12 @@ void server::start_accept() { } void server::on_accept(const boost::beast::error_code& err, - const connection_base::pointer& conn) { + const connection_base::pointer& conn) { if (err) { - SPDLOG_LOGGER_ERROR(_logger, "fail accept connection on {}: {}", - _conf->get_endpoint(), err.message()); + if (err != boost::asio::error::operation_aborted) { + SPDLOG_LOGGER_ERROR(_logger, "fail accept connection on {}: {}", + _conf->get_endpoint(), err.message()); + } return; } SPDLOG_LOGGER_DEBUG(_logger, "connection accepted from {} to {}", diff --git a/common/http/src/https_connection.cc b/common/http/src/https_connection.cc index 7e2e68e59d3..20defaa2685 100644 --- a/common/http/src/https_connection.cc +++ b/common/http/src/https_connection.cc @@ -134,7 +134,12 @@ https_connection::https_connection( const ssl_ctx_initializer& ssl_init) : connection_base(io_context, logger, conf), _sslcontext(conf->get_ssl_method()) { - ssl_init(_sslcontext, conf); + try { + if (ssl_init) + ssl_init(_sslcontext, conf); + } catch (const std::exception& e) { + SPDLOG_LOGGER_ERROR(logger, "fail to init ssl context: {}", e.what()); + } _stream = std::make_unique(beast::net::make_strand(*io_context), _sslcontext); SPDLOG_LOGGER_DEBUG(_logger, "create https_connection {:p} to {}", @@ -255,9 +260,9 @@ void https_connection::init_keep_alive() { * @brief to call in case of we are an http server * it initialize http keepalive and launch ssl handshake * - * @param callback + * @param callback (called once handshake os done) */ -void https_connection::on_accept(connect_callback_type&& callback) { +void https_connection::_on_accept(connect_callback_type&& callback) { unsigned expected = e_not_connected; if (!_state.compare_exchange_strong(expected, e_handshake)) { BAD_CONNECT_STATE_ERROR("on_tcp_connect to {}, bad state {}"); @@ -300,14 +305,15 @@ void https_connection::on_handshake(const beast::error_code err, callback(err, {}); } -#define BAD_SEND_STATE_ERROR(error_string) \ - std::string detail = \ - fmt::format(error_string, *_conf, state_to_str(expected)); \ - SPDLOG_LOGGER_ERROR(_logger, detail); \ - _io_context->post([cb = std::move(callback), detail]() { \ - cb(std::make_error_code(std::errc::invalid_argument), detail, \ - response_ptr()); \ - }); \ +#define BAD_SEND_STATE_ERROR(error_string) \ + std::string detail = \ + fmt::format(error_string, static_cast(this), *_conf, \ + state_to_str(expected)); \ + SPDLOG_LOGGER_ERROR(_logger, detail); \ + _io_context->post([cb = std::move(callback), detail]() { \ + cb(std::make_error_code(std::errc::invalid_argument), detail, \ + response_ptr()); \ + }); \ return; /** @@ -320,7 +326,7 @@ void https_connection::send(request_ptr request, send_callback_type&& callback) { unsigned expected = e_idle; if (!_state.compare_exchange_strong(expected, e_send)) { - BAD_SEND_STATE_ERROR("send to {}, bad state {}"); + BAD_SEND_STATE_ERROR("{:p} send to {}, bad state {}"); } request->_send = system_clock::now(); @@ -338,7 +344,7 @@ void https_connection::send(request_ptr request, beast::http::async_write( *_stream, *request, [me = shared_from_this(), request, cb = std::move(callback)]( - const beast::error_code& err, size_t bytes_transfered) mutable { + const beast::error_code& err, size_t) mutable { me->on_sent(err, request, cb); }); } @@ -364,7 +370,7 @@ void https_connection::on_sent(const beast::error_code& err, unsigned expected = e_send; if (!_state.compare_exchange_strong(expected, e_receive)) { - BAD_SEND_STATE_ERROR("on_sent to {}, bad state {}"); + BAD_SEND_STATE_ERROR("{:p} on_sent to {}, bad state {}"); } if (_logger->level() == spdlog::level::trace) { @@ -376,6 +382,10 @@ void https_connection::on_sent(const beast::error_code& err, request->_sent = system_clock::now(); std::lock_guard l(_socket_m); + if (_conf->get_receive_timeout() >= std::chrono::seconds(1)) { + beast::get_lowest_layer(*_stream).expires_after( + _conf->get_receive_timeout()); + } response_ptr resp = std::make_shared(); beast::http::async_read( *_stream, _recv_buffer, *resp, @@ -400,7 +410,9 @@ void https_connection::on_read(const beast::error_code& err, if (err) { std::string detail = fmt::format("fail receive {} from {}: {}", *request, *_conf, err.message()); - SPDLOG_LOGGER_ERROR(_logger, detail); + if (err != boost::asio::error::operation_aborted) { + SPDLOG_LOGGER_ERROR(_logger, detail); + } callback(err, detail, response_ptr()); shutdown(); return; @@ -408,7 +420,7 @@ void https_connection::on_read(const beast::error_code& err, unsigned expected = e_receive; if (!_state.compare_exchange_strong(expected, e_idle)) { - BAD_SEND_STATE_ERROR("on_read to {}, bad state {}"); + BAD_SEND_STATE_ERROR("{:p} on_read to {}, bad state {}"); } request->_receive = system_clock::now(); @@ -425,6 +437,13 @@ void https_connection::on_read(const beast::error_code& err, callback(err, {}, resp); } +/** + * @brief server part, send response to client + * in case of receive time out < 1s, socket is closed after response sent + * + * @param response + * @param callback + */ void https_connection::answer(const response_ptr& response, answer_callback_type&& callback) { unsigned expected = e_idle; @@ -440,6 +459,8 @@ void https_connection::answer(const response_ptr& response, return; } + add_keep_alive_to_server_response(response); + std::lock_guard l(_socket_m); beast::get_lowest_layer(*_stream).expires_after(_conf->get_send_timeout()); beast::http::async_write( @@ -455,6 +476,9 @@ void https_connection::answer(const response_ptr& response, } else { unsigned expected = e_send; me->_state.compare_exchange_strong(expected, e_idle); + if (me->_conf->get_receive_timeout() < std::chrono::seconds(1)) { + me->shutdown(); + } } SPDLOG_LOGGER_TRACE(me->_logger, "{:p} response sent: {}", static_cast(me.get()), *response); @@ -462,6 +486,11 @@ void https_connection::answer(const response_ptr& response, }); } +/** + * @brief server part: wait for incoming request + * + * @param callback + */ void https_connection::receive_request(request_callback_type&& callback) { unsigned expected = e_idle; if (!_state.compare_exchange_strong(expected, e_receive)) { @@ -478,16 +507,24 @@ void https_connection::receive_request(request_callback_type&& callback) { } std::lock_guard l(_socket_m); - beast::get_lowest_layer(*_stream).expires_after(_conf->get_receive_timeout()); + if (_conf->get_receive_timeout() >= std::chrono::seconds(1)) + beast::get_lowest_layer(*_stream).expires_after( + _conf->get_receive_timeout()); auto req = std::make_shared(); beast::http::async_read( *_stream, _recv_buffer, *req, [me = shared_from_this(), req, cb = std::move(callback)]( const boost::beast::error_code& ec, std::size_t) mutable { if (ec) { - SPDLOG_LOGGER_ERROR( - me->_logger, "{:p} fail to receive request from {}: {}", - static_cast(me.get()), me->get_peer(), ec.message()); + if (ec == boost::beast::http::error::end_of_stream) { + SPDLOG_LOGGER_DEBUG( + me->_logger, "{:p} fail to receive request from {}: {}", + static_cast(me.get()), me->get_peer(), ec.message()); + } else { + SPDLOG_LOGGER_ERROR( + me->_logger, "{:p} fail to receive request from {}: {}", + static_cast(me.get()), me->get_peer(), ec.message()); + } me->shutdown(); } else { unsigned expected = e_receive; @@ -543,7 +580,7 @@ asio::ip::tcp::socket& https_connection::get_socket() { * when implementing https client as: * @code {.c++} * auto conn = https_connection::load(g_io_context, logger, - * conf,[conf](asio::ssl::context& ctx) { + * conf,(asio::ssl::context& ctx, const http_config::pointer & conf) { * https_connection::load_client_certificate(ctx, conf); * }); * @@ -564,3 +601,46 @@ void https_connection::load_client_certificate( asio::buffer(cert_content->c_str(), cert_content->length())); } } + +/** + * @brief This helper can be passed to https_connection constructor fourth param + * when implementing https server as: + * @code {.c++} + * auto conn = https_connection::load(g_io_context, logger, + * conf,(asio::ssl::context& ctx, const http_config::pointer & conf) { + * https_connection::load_client_certificate(ctx, conf); + * }); + * + * @endcode + * You can generate cert and key with this command: + * @code {.shell} + * openssl req -newkey rsa:2048 -nodes -keyout ../server.key -x509 -days 10000 + * -out ../server.crt + * -subj "/C=US/ST=CA/L=Los Angeles/O=Beast/CN=www.example.com" + * -addext "subjectAltName=DNS:localhost,IP:172.17.0.1" + * @endcode + * + * + * @param ctx + * @param conf + */ +void https_connection::load_server_certificate( + asio::ssl::context& ctx, + const http_config::pointer& conf) { + if (!conf->get_certificate_path().empty() && !conf->get_key_path().empty()) { + std::shared_ptr cert_content = + detail::certificate_cache::get_mutable_instance().get_certificate( + conf->get_certificate_path()); + std::shared_ptr key_content = + detail::certificate_cache::get_mutable_instance().get_certificate( + conf->get_key_path()); + + ctx.use_certificate_chain( + boost::asio::buffer(cert_content->c_str(), cert_content->length())); + ctx.use_private_key( + boost::asio::buffer(key_content->c_str(), key_content->length()), + boost::asio::ssl::context::file_format::pem); + ctx.set_options(boost::asio::ssl::context::default_workarounds | + boost::asio::ssl::context::no_sslv2); + } +} diff --git a/common/http/test/http_client_test.cc b/common/http/test/http_client_test.cc index b668262ca67..27e1f1aa5d7 100644 --- a/common/http/test/http_client_test.cc +++ b/common/http/test/http_client_test.cc @@ -25,7 +25,6 @@ using system_clock = std::chrono::system_clock; using time_point = system_clock::time_point; using duration = system_clock::duration; -using com::centreon::common::log_v2::log_v2; #include "http_client.hh" @@ -100,7 +99,7 @@ class connection_ok : public connection_base { ++_request_counter; } - void on_accept(connect_callback_type&& callback) override {} + void _on_accept(connect_callback_type&& callback) override {} void answer(const response_ptr& response, answer_callback_type&& callback) override {} @@ -273,7 +272,7 @@ class connection_bagot : public connection_base { } } - void on_accept(connect_callback_type&& callback) override {} + void _on_accept(connect_callback_type&& callback) override {} void answer(const response_ptr& response, answer_callback_type&& callback) override {} diff --git a/common/http/test/http_connection_test.cc b/common/http/test/http_connection_test.cc index 2407f3871f5..b093db90e12 100644 --- a/common/http/test/http_connection_test.cc +++ b/common/http/test/http_connection_test.cc @@ -24,7 +24,6 @@ using system_clock = std::chrono::system_clock; using time_point = system_clock::time_point; using duration = system_clock::duration; -using com::centreon::common::log_v2::log_v2; #include "http_connection.hh" #include "http_server.hh" @@ -208,7 +207,7 @@ class dummy_connection : public connection_base { void send(request_ptr request, send_callback_type&& callback) override {} - void on_accept(connect_callback_type&& callback) override{}; + void _on_accept(connect_callback_type&& callback) override{}; void answer(const response_ptr& response, answer_callback_type&& callback) override{}; void receive_request(request_callback_type&& callback) override{}; @@ -217,7 +216,6 @@ class dummy_connection : public connection_base { }; TEST(http_keepalive_test, ConnectionClose) { - auto logger = log_v2::instance().get(log_v2::TCP); dummy_connection conn( g_io_context, logger, std::make_shared(test_endpoint, "localhost")); @@ -229,7 +227,6 @@ TEST(http_keepalive_test, ConnectionClose) { } TEST(http_keepalive_test, KeepAliveWithoutTimeout) { - auto logger = log_v2::instance().get(log_v2::TCP); auto conf = std::make_shared(test_endpoint, "localhost"); dummy_connection conn(g_io_context, logger, conf); response_ptr resp(std::make_shared()); @@ -246,7 +243,6 @@ TEST(http_keepalive_test, KeepAliveWithoutTimeout) { } TEST(http_keepalive_test, KeepAliveWithTimeout) { - auto logger = log_v2::instance().get(log_v2::TCP); auto conf = std::make_shared(test_endpoint, "localhost"); dummy_connection conn(g_io_context, logger, conf); response_ptr resp(std::make_shared()); @@ -324,9 +320,9 @@ class answer_no_keep_alive : public base_class { : base_class(io_context, logger, conf, ssl_initializer) {} void on_accept() override { - base_class::on_accept([me = base_class::shared_from_this()]( - const boost::beast::error_code ec, - const std::string&) { + base_class::_on_accept([me = base_class::shared_from_this()]( + const boost::beast::error_code ec, + const std::string&) { ASSERT_FALSE(ec); me->receive_request([me](const boost::beast::error_code ec, const std::string&, @@ -343,6 +339,8 @@ class answer_no_keep_alive : public base_class { }); }); } + void add_keep_alive_to_server_response( + const response_ptr& response) const override {} }; TEST_P(http_test, connect_send_answer_without_keepalive) { @@ -422,9 +420,9 @@ class answer_keep_alive : public base_class { : base_class(io_context, logger, conf, ssl_initializer), _counter(0) {} void on_accept() override { - base_class::on_accept([me = base_class::shared_from_this()]( - const boost::beast::error_code ec, - const std::string&) { + base_class::_on_accept([me = base_class::shared_from_this()]( + const boost::beast::error_code ec, + const std::string&) { ASSERT_FALSE(ec); me->receive_request([me](const boost::beast::error_code ec, const std::string&, @@ -432,33 +430,33 @@ class answer_keep_alive : public base_class { ASSERT_FALSE(ec); ASSERT_EQ(request->body(), "hello server"); SPDLOG_LOGGER_DEBUG(logger, "request receiver => answer"); - std::static_pointer_cast(me)->answer(request); + std::static_pointer_cast(me)->answer_to_request(request); }); }); } - void answer(const std::shared_ptr& request) { + void answer_to_request(const std::shared_ptr& request) { response_ptr resp(std::make_shared(beast::http::status::ok, request->version())); resp->keep_alive(true); resp->body() = fmt::format("hello client {}", _counter++); resp->content_length(resp->body().length()); SPDLOG_LOGGER_DEBUG(logger, "answer to client"); - base_class::answer( - resp, [me = base_class::shared_from_this()]( - const boost::beast::error_code ec, const std::string&) { - ASSERT_FALSE(ec); - me->receive_request( - [me](const boost::beast::error_code ec, const std::string&, - const std::shared_ptr& request) { - if (ec) { - return; - } - ASSERT_EQ(request->body(), "hello server"); - SPDLOG_LOGGER_DEBUG(logger, "request receiver => answer"); - std::static_pointer_cast(me)->answer(request); - }); - }); + base_class::answer(resp, [me = base_class::shared_from_this()]( + const boost::beast::error_code ec, + const std::string&) { + ASSERT_FALSE(ec); + me->receive_request([me](const boost::beast::error_code ec, + const std::string&, + const std::shared_ptr& request) { + if (ec) { + return; + } + ASSERT_EQ(request->body(), "hello server"); + SPDLOG_LOGGER_DEBUG(logger, "request receiver => answer"); + std::static_pointer_cast(me)->answer_to_request(request); + }); + }); } }; diff --git a/common/http/test/http_server_test.cc b/common/http/test/http_server_test.cc new file mode 100644 index 00000000000..52d06f7d510 --- /dev/null +++ b/common/http/test/http_server_test.cc @@ -0,0 +1,452 @@ +/** + * Copyright 2024 Centreon (https://www.centreon.com/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + * + */ +#include + +#include + +using system_clock = std::chrono::system_clock; +using time_point = system_clock::time_point; +using duration = system_clock::duration; + +#include "http_client.hh" +#include "http_connection.hh" +#include "http_server.hh" +#include "https_connection.hh" + +using namespace com::centreon::common::http; +namespace beast = boost::beast; + +extern std::shared_ptr g_io_context; + +constexpr unsigned port = 5796; + +const asio::ip::tcp::endpoint test_endpoint(asio::ip::make_address("127.0.0.1"), + port); + +const asio::ip::tcp::endpoint listen_endpoint(asio::ip::make_address("0.0.0.0"), + port); + +static void load_server_certificate(boost::asio::ssl::context& ctx, + const http_config::pointer&) { + /* + The certificate was generated from bash on Ubuntu (OpenSSL 1.1.1f) using: + + openssl dhparam -out dh.pem 2048 + openssl req -newkey rsa:2048 -nodes -keyout key.pem -x509 -days 10000 -out + cert.pem -subj "/C=US/ST=CA/L=Los Angeles/O=Beast/CN=www.example.com" + */ + + std::string const cert = + "-----BEGIN CERTIFICATE-----\n" + "MIIDlTCCAn2gAwIBAgIUOLxr3q7Wd/pto1+2MsW4fdRheCIwDQYJKoZIhvcNAQEL\n" + "BQAwWjELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAkNBMRQwEgYDVQQHDAtMb3MgQW5n\n" + "ZWxlczEOMAwGA1UECgwFQmVhc3QxGDAWBgNVBAMMD3d3dy5leGFtcGxlLmNvbTAe\n" + "Fw0yMTA3MDYwMTQ5MjVaFw00ODExMjEwMTQ5MjVaMFoxCzAJBgNVBAYTAlVTMQsw\n" + "CQYDVQQIDAJDQTEUMBIGA1UEBwwLTG9zIEFuZ2VsZXMxDjAMBgNVBAoMBUJlYXN0\n" + "MRgwFgYDVQQDDA93d3cuZXhhbXBsZS5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IB\n" + "DwAwggEKAoIBAQCz0GwgnxSBhygxBdhTHGx5LDLIJSuIDJ6nMwZFvAjdhLnB/vOT\n" + "Lppr5MKxqQHEpYdyDYGD1noBoz4TiIRj5JapChMgx58NLq5QyXkHV/ONT7yi8x05\n" + "P41c2F9pBEnUwUxIUG1Cb6AN0cZWF/wSMOZ0w3DoBhnl1sdQfQiS25MTK6x4tATm\n" + "Wm9SJc2lsjWptbyIN6hFXLYPXTwnYzCLvv1EK6Ft7tMPc/FcJpd/wYHgl8shDmY7\n" + "rV+AiGTxUU35V0AzpJlmvct5aJV/5vSRRLwT9qLZSddE9zy/0rovC5GML6S7BUC4\n" + "lIzJ8yxzOzSStBPxvdrOobSSNlRZIlE7gnyNAgMBAAGjUzBRMB0GA1UdDgQWBBR+\n" + "dYtY9zmFSw9GYpEXC1iJKHC0/jAfBgNVHSMEGDAWgBR+dYtY9zmFSw9GYpEXC1iJ\n" + "KHC0/jAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQBzKrsiYywl\n" + "RKeB2LbddgSf7ahiQMXCZpAjZeJikIoEmx+AmjQk1bam+M7WfpRAMnCKooU+Utp5\n" + "TwtijjnJydkZHFR6UH6oCWm8RsUVxruao/B0UFRlD8q+ZxGd4fGTdLg/ztmA+9oC\n" + "EmrcQNdz/KIxJj/fRB3j9GM4lkdaIju47V998Z619E/6pt7GWcAySm1faPB0X4fL\n" + "FJ6iYR2r/kJLoppPqL0EE49uwyYQ1dKhXS2hk+IIfA9mBn8eAFb/0435A2fXutds\n" + "qhvwIOmAObCzcoKkz3sChbk4ToUTqbC0TmFAXI5Upz1wnADzjpbJrpegCA3pmvhT\n" + "7356drqnCGY9\n" + "-----END CERTIFICATE-----\n"; + + std::string const key = + "-----BEGIN PRIVATE KEY-----\n" + "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCz0GwgnxSBhygx\n" + "BdhTHGx5LDLIJSuIDJ6nMwZFvAjdhLnB/vOTLppr5MKxqQHEpYdyDYGD1noBoz4T\n" + "iIRj5JapChMgx58NLq5QyXkHV/ONT7yi8x05P41c2F9pBEnUwUxIUG1Cb6AN0cZW\n" + "F/wSMOZ0w3DoBhnl1sdQfQiS25MTK6x4tATmWm9SJc2lsjWptbyIN6hFXLYPXTwn\n" + "YzCLvv1EK6Ft7tMPc/FcJpd/wYHgl8shDmY7rV+AiGTxUU35V0AzpJlmvct5aJV/\n" + "5vSRRLwT9qLZSddE9zy/0rovC5GML6S7BUC4lIzJ8yxzOzSStBPxvdrOobSSNlRZ\n" + "IlE7gnyNAgMBAAECggEAY0RorQmldGx9D7M+XYOPjsWLs1px0cXFwGA20kCgVEp1\n" + "kleBeHt93JqJsTKwOzN2tswl9/ZrnIPWPUpcbBlB40ggjzQk5k4jBY50Nk2jsxuV\n" + "9A9qzrP7AoqhAYTQjZe42SMtbkPZhEeOyvCqxBAi6csLhcv4eB4+In0kQo7dfvLs\n" + "Xu/3WhSsuAWqdD9EGnhD3n+hVTtgiasRe9318/3R9DzP+IokoQGOtXm+1dsfP0mV\n" + "8XGzQHBpUtJNn0yi6SC4kGEQuKkX33zORlSnZgT5VBLofNgra0THd7x3atOx1lbr\n" + "V0QizvCdBa6j6FwhOQwW8UwgOCnUbWXl/Xn4OaofMQKBgQDdRXSMyys7qUMe4SYM\n" + "Mdawj+rjv0Hg98/xORuXKEISh2snJGKEwV7L0vCn468n+sM19z62Axz+lvOUH8Qr\n" + "hLkBNqJvtIP+b0ljRjem78K4a4qIqUlpejpRLw6a/+44L76pMJXrYg3zdBfwzfwu\n" + "b9NXdwHzWoNuj4v36teGP6xOUwKBgQDQCT52XX96NseNC6HeK5BgWYYjjxmhksHi\n" + "stjzPJKySWXZqJpHfXI8qpOd0Sd1FHB+q1s3hand9c+Rxs762OXlqA9Q4i+4qEYZ\n" + "qhyRkTsl+2BhgzxmoqGd5gsVT7KV8XqtuHWLmetNEi+7+mGSFf2iNFnonKlvT1JX\n" + "4OQZC7ntnwKBgH/ORFmmaFxXkfteFLnqd5UYK5ZMvGKTALrWP4d5q2BEc7HyJC2F\n" + "+5lDR9nRezRedS7QlppPBgpPanXeO1LfoHSA+CYJYEwwP3Vl83Mq/Y/EHgp9rXeN\n" + "L+4AfjEtLo2pljjnZVDGHETIg6OFdunjkXDtvmSvnUbZBwG11bMnSAEdAoGBAKFw\n" + "qwJb6FNFM3JnNoQctnuuvYPWxwM1yjRMqkOIHCczAlD4oFEeLoqZrNhpuP8Ij4wd\n" + "GjpqBbpzyVLNP043B6FC3C/edz4Lh+resjDczVPaUZ8aosLbLiREoxE0udfWf2dU\n" + "oBNnrMwwcs6jrRga7Kr1iVgUSwBQRAxiP2CYUv7tAoGBAKdPdekPNP/rCnHkKIkj\n" + "o13pr+LJ8t+15vVzZNHwPHUWiYXFhG8Ivx7rqLQSPGcuPhNss3bg1RJiZAUvF6fd\n" + "e6QS4EZM9dhhlO2FmPQCJMrRVDXaV+9TcJZXCbclQnzzBus9pwZZyw4Anxo0vmir\n" + "nOMOU6XI4lO9Xge/QDEN4Y2R\n" + "-----END PRIVATE KEY-----\n"; + + std::string const dh = + "-----BEGIN DH PARAMETERS-----\n" + "MIIBCAKCAQEArzQc5mpm0Fs8yahDeySj31JZlwEphUdZ9StM2D8+Fo7TMduGtSi+\n" + "/HRWVwHcTFAgrxVdm+dl474mOUqqaz4MpzIb6+6OVfWHbQJmXPepZKyu4LgUPvY/\n" + "4q3/iDMjIS0fLOu/bLuObwU5ccZmDgfhmz1GanRlTQOiYRty3FiOATWZBRh6uv4u\n" + "tff4A9Bm3V9tLx9S6djq31w31Gl7OQhryodW28kc16t9TvO1BzcV3HjRPwpe701X\n" + "oEEZdnZWANkkpR/m/pfgdmGPU66S2sXMHgsliViQWpDCYeehrvFRHEdR9NV+XJfC\n" + "QMUk26jPTIVTLfXmmwU0u8vUkpR7LQKkwwIBAg==\n" + "-----END DH PARAMETERS-----\n"; + + ctx.set_password_callback( + [](std::size_t, boost::asio::ssl::context_base::password_purpose) { + return "test"; + }); + + ctx.set_options(boost::asio::ssl::context::default_workarounds | + boost::asio::ssl::context::no_sslv2 | + boost::asio::ssl::context::single_dh_use); + + ctx.use_certificate_chain(boost::asio::buffer(cert.data(), cert.size())); + + ctx.use_private_key(boost::asio::buffer(key.data(), key.size()), + boost::asio::ssl::context::file_format::pem); + + ctx.use_tmp_dh(boost::asio::buffer(dh.data(), dh.size())); +} + +static std::shared_ptr logger = + spdlog::stdout_color_mt("http_server_test"); + +static std::atomic_uint session_cpt(0); + +template +class session_test : public connection_class { + std::atomic_uint _request_cpt; + + void wait_for_request(); + + void answer_to_request(const std::shared_ptr& request); + + public: + session_test(const std::shared_ptr& io_context, + const std::shared_ptr& logger, + const http_config::pointer& conf, + const ssl_ctx_initializer& ssl_initializer) + : connection_class(io_context, logger, conf, ssl_initializer) { + session_cpt.fetch_add(1); + } + + ~session_test() { session_cpt.fetch_sub(1); } + + std::shared_ptr shared_from_this() { + return std::static_pointer_cast( + connection_class::shared_from_this()); + } + + void on_accept() override; +}; + +template +void session_test::on_accept() { + connection_class::_on_accept( + [me = shared_from_this()](const boost::beast::error_code& err, + const std::string&) { + if (!err) + me->wait_for_request(); + }); +} + +template +void session_test::wait_for_request() { + connection_class::receive_request( + [me = shared_from_this()](const boost::beast::error_code& err, + const std::string& detail, + const std::shared_ptr& request) { + if (err) { + SPDLOG_LOGGER_DEBUG(me->_logger, + "fail to receive request from {}: {}", me->_peer, + err.what()); + return; + } + me->answer_to_request(request); + }); +} + +template +void session_test::answer_to_request( + const std::shared_ptr& request) { + response_ptr resp(std::make_shared()); + resp->version(request->version()); + resp->body() = request->body(); + resp->content_length(resp->body().length()); + + connection_class::answer( + resp, [me = shared_from_this(), resp](const boost::beast::error_code& err, + const std::string& detail) { + if (err) { + SPDLOG_LOGGER_ERROR(me->_logger, "fail to answer to client {} {}", + err.message(), detail); + return; + } + me->wait_for_request(); + }); +} + +class http_server_test : public ::testing::TestWithParam { + public: + server::pointer _server; + + static void SetUpTestSuite() { logger->set_level(spdlog::level::debug); }; + void TearDown() override { + if (_server) { + _server->shutdown(); + _server.reset(); + } + // let some time to all connections die + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + + http_config::pointer create_conf() { + if (GetParam()) { + return std::make_shared( + test_endpoint, "localhost", true, std::chrono::seconds(10), + std::chrono::seconds(10), std::chrono::seconds(10), 30, + std::chrono::seconds(10), 5, std::chrono::hours(1), 10); + + } else { + return std::make_shared(test_endpoint, "localhost", false); + } + } + http_config::pointer create_server_conf() { + if (GetParam()) { + return std::make_shared( + listen_endpoint, "localhost", true, std::chrono::seconds(10), + std::chrono::seconds(10), std::chrono::seconds(10), 30, + std::chrono::seconds(10), 5, std::chrono::hours(1), 10, + asio::ssl::context_base::sslv23_server); + + } else { + return std::make_shared( + listen_endpoint, "localhost", false, std::chrono::seconds(10), + std::chrono::seconds(10), std::chrono::seconds(10), 30, + std::chrono::seconds(10), 5, std::chrono::hours(1), 10); + } + } +}; + +TEST_P(http_server_test, many_request_by_connection) { + std::shared_ptr conn; + http_config::pointer client_conf = create_conf(); + http_config::pointer server_conf = create_server_conf(); + + connection_creator server_creator, client_creator; + + if (GetParam()) { // crypted + server_creator = [server_conf]() { + return std::make_shared>( + g_io_context, logger, server_conf, load_server_certificate); + }; + client_creator = [client_conf]() { + return https_connection::load(g_io_context, logger, client_conf); + }; + } else { + server_creator = [server_conf]() { + return std::make_shared>( + g_io_context, logger, server_conf, nullptr); + }; + client_creator = [client_conf]() { + return http_connection::load(g_io_context, logger, client_conf); + }; + } + + _server = server::load(g_io_context, logger, server_conf, + std::move(server_creator)); + + client::pointer client = + client::load(g_io_context, logger, client_conf, client_creator); + + std::condition_variable cond; + std::mutex cond_m; + std::atomic_uint resp_cpt(0); + + for (unsigned send_cpt = 0; send_cpt < 200; ++send_cpt) { + request_ptr req = + std::make_shared(beast::http::verb::get, "", "/"); + req->body() = fmt::format("hello server {}", send_cpt); + req->content_length(req->body().length()); + + client->send(req, + [&cond, req, &resp_cpt](const beast::error_code& err, + const std::string& detail, + const response_ptr& response) mutable { + ASSERT_FALSE(err); + ASSERT_EQ(req->body(), response->body()); + if (resp_cpt.fetch_add(1) == 199) + cond.notify_one(); + }); + } + std::unique_lock l(cond_m); + cond.wait(l); + SPDLOG_LOGGER_INFO(logger, "shutdown client"); + client->shutdown(); +} + +TEST_P(http_server_test, many_request_and_many_connection) { + std::shared_ptr conn; + http_config::pointer client_conf = std::make_shared( + test_endpoint, "localhost", GetParam(), std::chrono::seconds(10), + std::chrono::seconds(10), std::chrono::seconds(10), 30, + std::chrono::seconds(10), 5, std::chrono::hours(1), 200); + + http_config::pointer server_conf = create_server_conf(); + + connection_creator server_creator, client_creator; + + if (GetParam()) { // crypted + server_creator = [server_conf]() { + return std::make_shared>( + g_io_context, logger, server_conf, load_server_certificate); + }; + client_creator = [client_conf]() { + return https_connection::load(g_io_context, logger, client_conf); + }; + } else { + server_creator = [server_conf]() { + return std::make_shared>( + g_io_context, logger, server_conf, nullptr); + }; + client_creator = [client_conf]() { + return http_connection::load(g_io_context, logger, client_conf); + }; + } + + _server = server::load(g_io_context, logger, server_conf, + std::move(server_creator)); + + client::pointer client = + client::load(g_io_context, logger, client_conf, client_creator); + + std::condition_variable cond; + std::mutex cond_m; + + std::atomic_uint resp_cpt(0); + for (unsigned send_cpt = 0; send_cpt < 1000; ++send_cpt) { + request_ptr req = + std::make_shared(beast::http::verb::get, "", "/"); + req->body() = fmt::format("hello server {}", send_cpt); + req->content_length(req->body().length()); + + client->send(req, + [&cond, req, &resp_cpt](const beast::error_code& err, + const std::string& detail, + const response_ptr& response) mutable { + ASSERT_FALSE(err); + ASSERT_EQ(req->body(), response->body()); + if (resp_cpt.fetch_add(1) == 999) + cond.notify_one(); + }); + } + std::unique_lock l(cond_m); + cond.wait(l); + + client->shutdown(); +} + +TEST_P(http_server_test, only_connect_to_timeout) { + std::shared_ptr conn; + http_config::pointer client_conf = std::make_shared( + test_endpoint, "localhost", GetParam(), std::chrono::seconds(10), + std::chrono::seconds(10), std::chrono::seconds(1000), 30, + std::chrono::seconds(10), 5, std::chrono::hours(1), 200); + + http_config::pointer server_conf; + + if (GetParam()) { + server_conf = std::make_shared( + listen_endpoint, "localhost", true, std::chrono::seconds(10), + std::chrono::seconds(10), std::chrono::seconds(1), 30, + std::chrono::seconds(10), 5, std::chrono::hours(1), 10, + asio::ssl::context_base::sslv23_server); + + } else { + server_conf = std::make_shared( + listen_endpoint, "localhost", false, std::chrono::seconds(10), + std::chrono::seconds(10), std::chrono::seconds(1), 30, + std::chrono::seconds(10), 5, std::chrono::hours(1), 10); + } + + connection_creator server_creator, client_creator; + + if (GetParam()) { // crypted + server_creator = [server_conf]() { + return std::make_shared>( + g_io_context, logger, server_conf, load_server_certificate); + }; + client_creator = [client_conf]() { + return https_connection::load(g_io_context, logger, client_conf); + }; + } else { + server_creator = [server_conf]() { + return std::make_shared>( + g_io_context, logger, server_conf, nullptr); + }; + client_creator = [client_conf]() { + return http_connection::load(g_io_context, logger, client_conf); + }; + } + + _server = server::load(g_io_context, logger, server_conf, + std::move(server_creator)); + + auto lazy_connection = client_creator(); + + std::chrono::system_clock::time_point expected_shutdown = + std::chrono::system_clock::now() + server_conf->get_receive_timeout(); + + std::condition_variable cond; + std::mutex cond_m; + lazy_connection->connect( + [lazy_connection, &cond](const boost::beast::error_code& err, + const std::string&) { + ASSERT_FALSE(err); + lazy_connection->receive_request( + [&cond](const boost::beast::error_code& err, const std::string&, + const std::shared_ptr&) { + ASSERT_TRUE(err); + cond.notify_one(); + }); + }); + + std::unique_lock l(cond_m); + cond.wait(l); + std::chrono::system_clock::time_point end = std::chrono::system_clock::now(); + // let some time to session to destroy + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + ASSERT_EQ(session_cpt.load(), 1); + ASSERT_LE(expected_shutdown, end); + ASSERT_GT(expected_shutdown + std::chrono::milliseconds(100), end); +} + +INSTANTIATE_TEST_SUITE_P(http_server_test, + http_server_test, + testing::Values(false, true)); diff --git a/common/precomp_inc/precomp.hh b/common/precomp_inc/precomp.hh index 07853c4edab..2d25e38fab8 100644 --- a/common/precomp_inc/precomp.hh +++ b/common/precomp_inc/precomp.hh @@ -48,9 +48,6 @@ #include "com/centreon/exceptions/msg_fmt.hh" -using system_clock = std::chrono::system_clock; -using time_point = system_clock::time_point; -using duration = system_clock::duration; namespace asio = boost::asio; diff --git a/common/tests/CMakeLists.txt b/common/tests/CMakeLists.txt index 1a4a782fb35..b7ce413dfe9 100644 --- a/common/tests/CMakeLists.txt +++ b/common/tests/CMakeLists.txt @@ -1,5 +1,5 @@ # -# Copyright 2023-2024 Centreon +# Copyright 2024 Centreon # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of @@ -22,7 +22,8 @@ add_executable(ut_common log_v2/log_v2.cc node_allocator_test.cc rapidjson_helper_test.cc -) + test_main.cc + ${TESTS_SOURCES}) set_target_properties( ut_common @@ -41,13 +42,16 @@ endif() add_test(NAME tests COMMAND ut_common) + + target_link_libraries( ut_common PRIVATE centreon_common - crypto - ssl + centreon_http re2::re2 log_v2 + crypto + ssl GTest::gtest GTest::gtest_main GTest::gmock @@ -56,10 +60,9 @@ target_link_libraries( absl::log absl::base absl::bits - fmt::fmt - pthread) + fmt::fmt pthread) -add_dependencies(ut_common centreon_common) +add_dependencies(ut_common centreon_common centreon_http) set_property(TARGET ut_common PROPERTY POSITION_INDEPENDENT_CODE ON) diff --git a/engine/CMakeLists.txt b/engine/CMakeLists.txt index 2415b6ea35d..ab0eedb767b 100644 --- a/engine/CMakeLists.txt +++ b/engine/CMakeLists.txt @@ -527,6 +527,9 @@ target_link_libraries( "-Wl,-whole-archive" enginerpc centreon_grpc + centreon_http + -L${Boost_LIBRARY_DIR_RELEASE} + boost_url cce_core gRPC::grpc++ "-Wl,--no-whole-archive" diff --git a/engine/enginerpc/precomp_inc/precomp.hh b/engine/enginerpc/precomp_inc/precomp.hh index 881d104529a..a09314181b4 100644 --- a/engine/enginerpc/precomp_inc/precomp.hh +++ b/engine/enginerpc/precomp_inc/precomp.hh @@ -1,32 +1,32 @@ -/* -** Copyright 2022 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ +/** + * Copyright 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCE_ENGINE_RPC_PRECOMP_HH #define CCE_ENGINE_RPC_PRECOMP_HH #include #include +#include #include #include -#include +#include #include #include diff --git a/engine/inc/com/centreon/engine/command_manager.hh b/engine/inc/com/centreon/engine/command_manager.hh index cf97f9c6d63..de8b3c31b5a 100644 --- a/engine/inc/com/centreon/engine/command_manager.hh +++ b/engine/inc/com/centreon/engine/command_manager.hh @@ -20,8 +20,6 @@ #ifndef CCE_COMMAND_MANAGER_HH #define CCE_COMMAND_MANAGER_HH -#include - #include "com/centreon/engine/engine_impl.hh" #include "com/centreon/engine/host.hh" @@ -69,6 +67,6 @@ class command_manager { unsigned long duration); }; -} +} // namespace com::centreon::engine #endif /* !CCE_STATISTICS_HH */ diff --git a/engine/inc/com/centreon/engine/commands/command.hh b/engine/inc/com/centreon/engine/commands/command.hh index 9748d289da6..11487afb684 100644 --- a/engine/inc/com/centreon/engine/commands/command.hh +++ b/engine/inc/com/centreon/engine/commands/command.hh @@ -124,8 +124,8 @@ class command { * @param host * @param service_description empty for host command */ - virtual void register_host_serv(const std::string& host, - const std::string& service_description){}; + virtual void register_host_serv(const std::string& /*host*/, + const std::string& /*service_description*/){}; /** * @brief Remove an entry for host serv list shared between this connector and @@ -134,8 +134,9 @@ class command { * @param host * @param service_description empty for host command */ - virtual void unregister_host_serv(const std::string& host, - const std::string& service_description){}; + virtual void unregister_host_serv( + const std::string& /*host*/, + const std::string& /*service_description*/){}; template void add_caller_group(caller_iterator begin, caller_iterator end); diff --git a/engine/inc/com/centreon/engine/commands/forward.hh b/engine/inc/com/centreon/engine/commands/forward.hh index 7e2c5b36b30..1796b585933 100644 --- a/engine/inc/com/centreon/engine/commands/forward.hh +++ b/engine/inc/com/centreon/engine/commands/forward.hh @@ -63,6 +63,6 @@ class forward : public command { }; } // namespace commands -} +} // namespace com::centreon::engine #endif // !CCE_COMMANDS_FORWARD_HH diff --git a/engine/inc/com/centreon/engine/service.hh b/engine/inc/com/centreon/engine/service.hh index 64d96b826f7..b602224dc46 100644 --- a/engine/inc/com/centreon/engine/service.hh +++ b/engine/inc/com/centreon/engine/service.hh @@ -45,8 +45,8 @@ using service_map_unsafe = absl::flat_hash_map, com::centreon::engine::service*>; using service_id_map = - absl::flat_hash_map, - std::shared_ptr>; + absl::btree_map, + std::shared_ptr>; namespace com::centreon::engine { diff --git a/engine/modules/external_commands/precomp_inc/precomp.hh b/engine/modules/external_commands/precomp_inc/precomp.hh index 3d9508bb7aa..da344b16537 100644 --- a/engine/modules/external_commands/precomp_inc/precomp.hh +++ b/engine/modules/external_commands/precomp_inc/precomp.hh @@ -1,21 +1,20 @@ -/* -** Copyright 2022 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ +/** + * Copyright 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCE_EXTERNAL_COMMANDS_PRECOMP_HH #define CCE_EXTERNAL_COMMANDS_PRECOMP_HH @@ -28,10 +27,11 @@ #include #include #include +#include #include #include -#include +#include #include #include diff --git a/engine/modules/opentelemetry/CMakeLists.txt b/engine/modules/opentelemetry/CMakeLists.txt index ea8fabc78d5..fd65ef641d6 100644 --- a/engine/modules/opentelemetry/CMakeLists.txt +++ b/engine/modules/opentelemetry/CMakeLists.txt @@ -55,6 +55,8 @@ ${SRC_DIR}/otl_converter.cc ${SRC_DIR}/otl_data_point.cc ${SRC_DIR}/otl_server.cc ${SRC_DIR}/main.cc +${SRC_DIR}/telegraf/conf_server.cc +${SRC_DIR}/telegraf/nagios_converter.cc ${SRC_DIR}/opentelemetry/proto/collector/metrics/v1/metrics_service.grpc.pb.cc ) diff --git a/engine/modules/opentelemetry/doc/opentelemetry.md b/engine/modules/opentelemetry/doc/opentelemetry.md new file mode 100644 index 00000000000..642e2439a04 --- /dev/null +++ b/engine/modules/opentelemetry/doc/opentelemetry.md @@ -0,0 +1,206 @@ +## Open-telemetry +### Principe +Engine can receive open telemetry data on a grpc server +A new module is added opentelemetry +It works like that: +* metrics are received +* extractors tries to extract host name and service description for each data_point. On success, data_point are pushed on fifos indexed by host, service +* a service that used these datas wants to do a check. The cmd line identifies the otl_converter that will construct check result from host service data_point fifos. If converter achieves to build a result from metrics, it returns right now, if it doesn't, a handler will be called as soon as needed metrics will be available or timeout expires. + +### open telemetry request +The proto is organized like that +```json +{ + "resourceMetrics": [ + { + "resource": { + "attributes": [ + { + "key": "attrib1", + "value": { + "stringValue": "attrib value" + } + } + ] + }, + "scopeMetrics": [ + { + "scope": { + "attributes": [ + { + "key": "attrib1", + "value": { + "stringValue": "attrib value" + } + } + ] + }, + "metrics": [ + { + "name": "check_icmp_warning_gt", + "gauge": { + "dataPoints": [ + { + "timeUnixNano": "1707744430000000000", + "asDouble": 200, + "attributes": [ + { + "key": "host", + "value": { + "stringValue": "localhost" + } + }, + { + "key": "perfdata", + "value": { + "stringValue": "rta" + } + }, + { + "key": "service", + "value": { + "stringValue": "check_icmp" + } + }, + { + "key": "unit", + "value": { + "stringValue": "ms" + } + } + ] + }, + { + "timeUnixNano": "1707744430000000000", + "asDouble": 40, + "attributes": [ + { + "key": "host", + "value": { + "stringValue": "localhost" + } + }, + { + "key": "perfdata", + "value": { + "stringValue": "pl" + } + }, + { + "key": "service", + "value": { + "stringValue": "check_icmp" + } + }, + { + "key": "unit", + "value": { + "stringValue": "%" + } + } + ] + } + ] + } + } + ] + } + ] + } + ] +} + +``` + +### Concepts and classes +* data_point: data_point is the smallest unit of received request, data_point class contains data_point protobuf object and all his parents (resource, scope, metric) +* host serv extractors: When we receive otel metrics, we must extract host and service, this is his job. It can be configurable in order for example to search host name in data_point attribute or in scope. host serv extractors also contains host serv allowed. This list is updated by register_host_serv command method +* data_point fifo: a container that contains data points indexed by timestamp +* data_point fifo container: fifos indexed by host service +* otel_command: a fake connector that is used to make the link between engine and otel module +* otl_server: a grpc server that accept otel collector incoming connections +* otl_converter: This short lived object is created each time engine wants to do a check. His final class as his configuration is done from the command line of the check. His job is to create a check result from data_point fifo container datas. It's destroyed when he achieved to create a check result or when timeout expires. +* host_serv_list: in order to extract host and service, an host_serv extractor must known allowed host service pairs. As otel_command may be notified of host service using it by register_host_serv method while otel module is not yet loaded. This object shared between otel_command and host_serv_extractor is actualized from otel_command::register_host_serv. + +### How engine access to otl object +In otel_interface.hh, otel object interface are defined in engine commands namespace. +Object used by both otel module and engine are inherited from these interfaces. +Engine only knows a singleton of the interface open_telemetry_base. This singleton is initialized at otl module loading. + +### How to configure it +We use a fake connector. When configuration is loaded, if a connector command line begins with "open_telemetry", we create an otel_command. Arguments following "open_telemetry" are used to create an host service extractor. If otel module is loaded, we create extractor, otherwise, the otel_command initialization will be done at otel module loading. +So user has to build one connector by host serv extractor configuration. +Then commands can use these fake connectors (class otel_command) to run checks. + +### How a service do a check +When otel_command::run is called, it calls the check method of open_telemetry singleton. +The check method of open_telemetry object will use command line passed to run to create an otl_converter object that has to convert metrics to check result. +The open_telemetry call sync_build_result_from_metrics, if it can't achieve to build a result, otl_converter is stored in a container. +When a metric of a waiting service is received, async_build_result_from_metrics of otl_converter is called. +In open_telemetry object, a second timer is also used to call async_time_out of otl_converter on timeout expire. + +### other configuration +other configuration parameters are stored in a dedicated json file. The path of this file is passed as argument in centengine.cfg +Example: broker_module=lib/libopentelemetry.so /etc/centreon_engine/otl_server.json +In this file there are grpc server parameters and some other parameters. + +### telegraf +telegraf can start nagios plugins and send results to engine. So centreon opentelemetry library has two classes, one to convert telegraf nagios output to service check, and an http(s) server that gives to telegraf his configuration according to engine configuration. +First telegraf service commands must use opentelemetry fake connector and have a command line like: +``` +nagios_telegraf --cmd_line /usr/lib/nagios/plugins/check_icmp 127.0.0.1 +``` +When telegraf conf server receive an http request with one or several hosts in get parameters `http://localhost:1443/engine?host=host_1`, it searches open telemetry commands in host and service list and returns a configuration file in response body. +The problem of asio http server is that request handler are called by asio thread, so we use command_line_manager to scan hosts and service in a thread safe manner. + +An example of configuration: +- commands.cfg + ``` + define command { + command_name test-notif + command_line /tmp/var/lib/centreon-engine/notif.pl + } + define command { + command_name otel_check_icmp + command_line nagios_telegraf --cmd_line /usr/lib/nagios/plugins/check_icmp 127.0.0.1 + connector OTEL connector + } + ``` +- connector.cfg + ``` + define connector { + connector_name OTEL connector + connector_line open_telemetry attributes --host_attribute=data_point --host_key=host --service_attribute=data_point --service_key=service + } + ``` +- centengine.cfg: + ``` + cfg_file=/tmp/etc/centreon-engine/config0/hosts.cfg + cfg_file=/tmp/etc/centreon-engine/config0/services.cfg + cfg_file=/tmp/etc/centreon-engine/config0/commands.cfg + cfg_file=/tmp/etc/centreon-engine/config0/hostgroups.cfg + cfg_file=/tmp/etc/centreon-engine/config0/timeperiods.cfg + cfg_file=/tmp/etc/centreon-engine/config0/connectors.cfg + broker_module=/usr/lib64/centreon-engine/externalcmd.so + broker_module=/usr/lib64/nagios/cbmod.so /tmp/etc/centreon-broker/central-module0.json + broker_module=/usr/lib64/centreon-engine/libopentelemetry.so /tmp/etc/centreon-engine/config0/otl_server.json + interval_length=60 + use_timezone=:Europe/Paris + ``` +- fichier de conf opentelemetry: + ```json + { + "server": { + "host": "0.0.0.0", + "port": 4317 + }, + "max_length_grpc_log": 0, + "telegraf_conf_server": { + "port": 1443, + "encryption": true, + "engine_otel_endpoint": "172.17.0.1:4317", + "certificate_path": "server.crt", + "key_path": "server.key" + } + } + ``` diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/data_point_fifo.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/data_point_fifo.hh index e6d61249fe6..fefdab041ab 100644 --- a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/data_point_fifo.hh +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/data_point_fifo.hh @@ -71,6 +71,8 @@ class data_point_fifo { void clean(); + void clean_oldest(uint64_t expiry); + static void update_fifo_limit(time_t second_datapoint_expiry, size_t max_size); }; diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/open_telemetry.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/open_telemetry.hh index 90aee07ab4a..1792cc5c402 100644 --- a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/open_telemetry.hh +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/open_telemetry.hh @@ -18,6 +18,8 @@ #ifndef CCE_MOD_OTL_SERVER_OPENTELEMETRY_HH #define CCE_MOD_OTL_SERVER_OPENTELEMETRY_HH +#include "com/centreon/common/http/http_server.hh" + #include "com/centreon/engine/commands/otel_interface.hh" #include "data_point_fifo_container.hh" @@ -28,6 +30,7 @@ namespace com::centreon::engine::modules::opentelemetry { using host_serv_metric = commands::otel::host_serv_metric; +namespace http = com::centreon::common::http; class otl_server; @@ -44,6 +47,7 @@ class otl_server; class open_telemetry : public commands::otel::open_telemetry_base { asio::system_timer _second_timer; std::shared_ptr _otl_server; + std::shared_ptr _telegraf_conf_server; using cmd_line_to_extractor_map = absl::btree_map>; @@ -89,6 +93,9 @@ class open_telemetry : public commands::otel::open_telemetry_base { void _second_timer_handler(); + void _create_telegraf_conf_server( + const telegraf::conf_server_config::pointer& conf); + protected: virtual void _create_otl_server(const grpc_config::pointer& server_conf); void _on_metric(const metric_request_ptr& metric); diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_config.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_config.hh index 63db1e48e63..3d8f3d06966 100644 --- a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_config.hh +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_config.hh @@ -20,10 +20,12 @@ #define CCE_MOD_OTL_SERVER_OTLCONFIG_HH #include "grpc_config.hh" +#include "telegraf/conf_server.hh" namespace com::centreon::engine::modules::opentelemetry { class otl_config { grpc_config::pointer _grpc_conf; + telegraf::conf_server_config::pointer _telegraf_conf_server_config; int _max_length_grpc_log = -1; // all otel are logged if negative bool _json_grpc_log = false; // if true, otel object are logged in json @@ -39,6 +41,10 @@ class otl_config { otl_config(const std::string_view& file_path, asio::io_context& io_context); grpc_config::pointer get_grpc_config() const { return _grpc_conf; } + telegraf::conf_server_config::pointer get_telegraf_conf_server_config() + const { + return _telegraf_conf_server_config; + } int get_max_length_grpc_log() const { return _max_length_grpc_log; } bool get_json_grpc_log() const { return _json_grpc_log; } @@ -54,4 +60,4 @@ class otl_config { }; } // namespace com::centreon::engine::modules::opentelemetry -#endif \ No newline at end of file +#endif diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/telegraf/conf_server.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/telegraf/conf_server.hh new file mode 100644 index 00000000000..cc024e1d5fb --- /dev/null +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/telegraf/conf_server.hh @@ -0,0 +1,110 @@ +/* +** Copyright 2024 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCE_MOD_OTL_TELEGRAF_CONF_SERVER_HH +#define CCE_MOD_OTL_TELEGRAF_CONF_SERVER_HH + +namespace com::centreon::engine::modules::opentelemetry::telegraf { + +namespace http = com::centreon::common::http; + +/** + * @brief telegraf configuration bean given by json config file + * + */ +class conf_server_config { + asio::ip::tcp::endpoint _listen_endpoint; + bool _crypted; + unsigned _second_keep_alive_interval; + std::string _certificate_path; + std::string _key_path; + std::string _engine_otl_endpoint; + unsigned _check_interval; + + public: + using pointer = std::shared_ptr; + + conf_server_config(const rapidjson::Value& json_config_v, + asio::io_context& io_context); + + const asio::ip::tcp::endpoint& get_listen_endpoint() const { + return _listen_endpoint; + } + bool is_crypted() const { return _crypted; } + unsigned get_second_keep_alive_interval() const { + return _second_keep_alive_interval; + } + + unsigned get_check_interval() const { return _check_interval; } + + const std::string& get_certificate_path() const { return _certificate_path; } + const std::string& get_key_path() const { return _key_path; } + const std::string& get_engine_otl_endpoint() const { + return _engine_otl_endpoint; + } + + bool operator==(const conf_server_config& right) const; +}; + +/** + * @brief http(s) session used by telegraf to get his configuration + * + * @tparam connection_class http_connection or https_connection + */ +template +class conf_session : public connection_class { + conf_server_config::pointer _telegraf_conf; + + void wait_for_request(); + + void on_receive_request(const std::shared_ptr& request); + + void answer_to_request(const std::shared_ptr& request, + std::vector&& host_list); + + bool _get_commands(const std::string& host_name, std::string& request_body); + + bool _otel_command_to_stream(const std::string& cmd_name, + const std::string& cmd_line, + const std::string& host, + const std::string& service, + std::string& to_append); + + public: + using my_type = conf_session; + using pointer = std::shared_ptr; + + conf_session(const std::shared_ptr& io_context, + const std::shared_ptr& logger, + const http::http_config::pointer& conf, + const http::ssl_ctx_initializer& ssl_initializer, + const conf_server_config::pointer& telegraf_conf) + : connection_class(io_context, logger, conf, ssl_initializer), + _telegraf_conf(telegraf_conf) {} + + pointer shared_from_this() { + return std::static_pointer_cast( + connection_class::shared_from_this()); + } + + void on_accept() override; +}; + +} // namespace com::centreon::engine::modules::opentelemetry::telegraf + +#endif diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/telegraf/nagios_converter.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/telegraf/nagios_converter.hh new file mode 100644 index 00000000000..af684268f1c --- /dev/null +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/telegraf/nagios_converter.hh @@ -0,0 +1,118 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#ifndef CCE_MOD_OTL_NAGIOS_CONVERTER_HH +#define CCE_MOD_OTL_NAGIOS_CONVERTER_HH + +namespace com::centreon::engine::modules::opentelemetry::telegraf { +/** + * @brief telegraf accept to use nagios plugins + * This converter parse metrics special naming to rebuild original check_result + * an example of output: + * @code {.json} + * { + * "name": "check_icmp_warning_gt", + * "gauge": { + * "dataPoints": [ + * { + * "timeUnixNano": "1707744430000000000", + * "asDouble": 200, + * "attributes": [ + * { + * "key": "host", + * "value": { + * "stringValue": "localhost" + * } + * }, + * { + * "key": "perfdata", + * "value": { + * "stringValue": "rta" + * } + * }, + * { + * "key": "service", + * "value": { + * "stringValue": "check_icmp" + * } + * }, + * { + * "key": "unit", + * "value": { + * "stringValue": "ms" + * } + * } + * ] + * } + * ] + * } + * }, + * { + * "name": "check_icmp_state", + * "gauge": { + * "dataPoints": [ + * { + * "timeUnixNano": "1707744430000000000", + * "asInt": "0", + * "attributes": [ + * { + * "key": "host", + * "value": { + * "stringValue": "localhost" + * } + * }, + * { + * "key": "service", + * "value": { + * "stringValue": "check_icmp" + * } + * } + * ] + * } + * ] + * } + * }, + * @endcode + * + * + */ +class otl_nagios_converter : public otl_converter { + protected: + bool _build_result_from_metrics(metric_name_to_fifo& fifos, + commands::result& res) override; + + public: + otl_nagios_converter(const std::string& cmd_line, + uint64_t command_id, + const host& host, + const service* service, + std::chrono::system_clock::time_point timeout, + commands::otel::result_callback&& handler, + const std::shared_ptr& logger) + : otl_converter(cmd_line, + command_id, + host, + service, + timeout, + std::move(handler), + logger) {} +}; + +} // namespace com::centreon::engine::modules::opentelemetry::telegraf + +#endif diff --git a/engine/modules/opentelemetry/src/data_point_fifo.cc b/engine/modules/opentelemetry/src/data_point_fifo.cc index 778f7ba6c52..8c1827854ac 100644 --- a/engine/modules/opentelemetry/src/data_point_fifo.cc +++ b/engine/modules/opentelemetry/src/data_point_fifo.cc @@ -68,3 +68,14 @@ void data_point_fifo::clean() { } } } + +/** + * @brief erase oldest element + * + * @param expiry data points oldest than this nano timestamp are erased + */ +void data_point_fifo::clean_oldest(uint64_t expiry) { + while (!_fifo.empty() && _fifo.begin()->get_nano_timestamp() <= expiry) { + _fifo.erase(_fifo.begin()); + } +} diff --git a/engine/modules/opentelemetry/src/main.cc b/engine/modules/opentelemetry/src/main.cc index d6a06082306..abd6d08cfc5 100644 --- a/engine/modules/opentelemetry/src/main.cc +++ b/engine/modules/opentelemetry/src/main.cc @@ -108,6 +108,7 @@ extern "C" int nebmodule_init(int flags, char const* args, void* handle) { open_telemetry::load(conf_file_path, g_io_context, log_v2::instance().get(log_v2::OTEL)); + commands::otel_command::init_all(); return 0; } diff --git a/engine/modules/opentelemetry/src/open_telemetry.cc b/engine/modules/opentelemetry/src/open_telemetry.cc index 3c6ea25fcc3..93cc90e18ba 100644 --- a/engine/modules/opentelemetry/src/open_telemetry.cc +++ b/engine/modules/opentelemetry/src/open_telemetry.cc @@ -18,6 +18,7 @@ #include "com/centreon/exceptions/msg_fmt.hh" +#include "com/centreon/common/http/https_connection.hh" #include "com/centreon/engine/modules/opentelemetry/open_telemetry.hh" #include "otl_fmt.hh" @@ -53,6 +54,17 @@ void open_telemetry::_reload() { this->_create_otl_server(new_conf->get_grpc_config()); } + if (!new_conf->get_telegraf_conf_server_config()) { + if (_telegraf_conf_server) { + _telegraf_conf_server->shutdown(); + _telegraf_conf_server.reset(); + } + } else if (!_conf || !_conf->get_telegraf_conf_server_config() || + !(*new_conf->get_telegraf_conf_server_config() == + *_conf->get_telegraf_conf_server_config())) { + _create_telegraf_conf_server(new_conf->get_telegraf_conf_server_config()); + } + if (!_conf || *_conf != *new_conf) { fmt::formatter<::opentelemetry::proto::collector::metrics::v1:: ExportMetricsServiceRequest>::max_length_log = @@ -112,6 +124,50 @@ void open_telemetry::_create_otl_server( } } +/** + * @brief create an http(s) server to give configuration to telegraf + * + * @param telegraf_conf + */ +void open_telemetry::_create_telegraf_conf_server( + const telegraf::conf_server_config::pointer& telegraf_conf) { + try { + http::server::pointer to_shutdown = _telegraf_conf_server; + if (to_shutdown) { + to_shutdown->shutdown(); + } + http::http_config::pointer conf = std::make_shared( + telegraf_conf->get_listen_endpoint(), "", telegraf_conf->is_crypted(), + std::chrono::seconds(10), std::chrono::seconds(30), + std::chrono::seconds(300), 30, std::chrono::seconds(10), 0, + std::chrono::hours(1), 1, asio::ssl::context::tlsv12, + telegraf_conf->get_certificate_path(), telegraf_conf->get_key_path()); + + if (telegraf_conf->is_crypted()) { + _telegraf_conf_server = http::server::load( + _io_context, _logger, conf, + [conf, io_ctx = _io_context, telegraf_conf, logger = _logger]() { + return std::make_shared< + telegraf::conf_session>( + io_ctx, logger, conf, + http::https_connection::load_server_certificate, telegraf_conf); + }); + } else { + _telegraf_conf_server = http::server::load( + _io_context, _logger, conf, + [conf, io_ctx = _io_context, telegraf_conf, logger = _logger]() { + return std::make_shared< + telegraf::conf_session>( + io_ctx, logger, conf, nullptr, telegraf_conf); + }); + } + } catch (const std::exception& e) { + SPDLOG_LOGGER_ERROR( + _logger, "fail to create telegraf http(s) conf server: {}", e.what()); + _telegraf_conf_server.reset(); + } +} + /** * @brief static method used to make singleton reload is configuration * diff --git a/engine/modules/opentelemetry/src/otl_config.cc b/engine/modules/opentelemetry/src/otl_config.cc index b4122d52784..96a5fb024de 100644 --- a/engine/modules/opentelemetry/src/otl_config.cc +++ b/engine/modules/opentelemetry/src/otl_config.cc @@ -57,6 +57,10 @@ static constexpr std::string_view _grpc_config_schema(R"( "server": { "description": "otel grpc config", "type": "object" + }, + "telegraf_conf_server": { + "description": "http(s) telegraf config server", + "type": "object" } }, "required": [ @@ -87,6 +91,11 @@ otl_config::otl_config(const std::string_view& file_path, _second_fifo_expiry = file_content.get_unsigned("second_fifo_expiry", 600); _max_fifo_size = file_content.get_unsigned("max_fifo_size", 5); _grpc_conf = std::make_shared(file_content.get_member("server")); + if (file_content.has_member("telegraf_conf_server")) { + _telegraf_conf_server_config = + std::make_shared( + file_content.get_member("telegraf_conf_server"), io_context); + } } /** @@ -105,5 +114,9 @@ bool otl_config::operator==(const otl_config& right) const { _json_grpc_log == right._json_grpc_log && _second_fifo_expiry == right._second_fifo_expiry && _max_fifo_size == right._max_fifo_size; - return ret; + + if (_telegraf_conf_server_config && right._telegraf_conf_server_config) { + return *_telegraf_conf_server_config == *right._telegraf_conf_server_config; + } + return !_telegraf_conf_server_config && !right._telegraf_conf_server_config; } diff --git a/engine/modules/opentelemetry/src/otl_converter.cc b/engine/modules/opentelemetry/src/otl_converter.cc index 3ae70c6aee8..4b71563244f 100644 --- a/engine/modules/opentelemetry/src/otl_converter.cc +++ b/engine/modules/opentelemetry/src/otl_converter.cc @@ -21,6 +21,7 @@ #include "data_point_fifo_container.hh" #include "otl_converter.hh" +#include "telegraf/nagios_converter.hh" #include "absl/flags/commandlineflag.h" #include "absl/strings/str_split.h" @@ -135,15 +136,14 @@ std::shared_ptr otl_converter::create( std::string conf_type = sep_pos == std::string::npos ? cmd_line : cmd_line.substr(0, sep_pos); boost::trim(conf_type); - // NEXT PR - // if (conf_type == "nagios_telegraf") { - // return std::make_shared( - // cmd_line, command_id, host, service, timeout, std::move(handler), - // logger); - // } else { - SPDLOG_LOGGER_ERROR(config_logger, "unknown converter type:{}", conf_type); - throw exceptions::msg_fmt("unknown converter type:{}", conf_type); - // } + if (conf_type == "nagios_telegraf") { + return std::make_shared( + cmd_line, command_id, host, service, timeout, std::move(handler), + logger); + } else { + SPDLOG_LOGGER_ERROR(config_logger, "unknown converter type:{}", conf_type); + throw exceptions::msg_fmt("unknown converter type:{}", conf_type); + } } /** diff --git a/engine/modules/opentelemetry/src/telegraf/conf_server.cc b/engine/modules/opentelemetry/src/telegraf/conf_server.cc new file mode 100644 index 00000000000..2de14030234 --- /dev/null +++ b/engine/modules/opentelemetry/src/telegraf/conf_server.cc @@ -0,0 +1,435 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#include + +#include "telegraf/conf_server.hh" + +#include "com/centreon/engine/globals.hh" +#include "com/centreon/engine/host.hh" +#include "com/centreon/engine/macros.hh" +#include "com/centreon/engine/service.hh" + +#include "com/centreon/common/http/https_connection.hh" +#include "com/centreon/engine/command_manager.hh" +#include "com/centreon/engine/commands/forward.hh" + +#include "com/centreon/exceptions/msg_fmt.hh" + +using namespace com::centreon::engine::modules::opentelemetry::telegraf; +using namespace com::centreon::engine; + +static constexpr std::string_view _config_schema(R"( +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "title": "grpc config", + "properties": { + "listen_address": { + "description": "IP", + "type": "string", + "minLength": 5 + }, + "port": { + "description": "port to listen", + "type": "integer", + "minimum": 80, + "maximum": 65535 + }, + "check_interval": { + "description": "interval in seconds between two checks (param [agent] interval) ", + "type": "integer", + "minimum": 10 + }, + "encryption": { + "description": "true if https", + "type": "boolean" + }, + "keepalive_interval": { + "description": "delay between 2 keepalive tcp packet, 0 no keepalive packets", + "type": "integer", + "minimum": 0, + "maximum": 3600 + }, + "certificate_path": { + "description": "path of the certificate file", + "type": "string", + "minLength": 5 + }, + "key_path": { + "description": "path of the key file", + "type": "string", + "minLength": 5 + }, + "engine_otel_endpoint": { + "description": "opentelemetry engine grpc server", + "type": "string", + "minLength": 5 + } + }, + "required":[ + "engine_otel_endpoint" + ], + "type": "object" +} +)"); + +conf_server_config::conf_server_config(const rapidjson::Value& json_config_v, + asio::io_context& io_context) { + common::rapidjson_helper json_config(json_config_v); + + static common::json_validator validator(_config_schema); + try { + json_config.validate(validator); + } catch (const std::exception& e) { + SPDLOG_LOGGER_ERROR(config_logger, + "forbidden values in telegraf_conf_server config: {}", + e.what()); + throw; + } + std::string listen_address = + json_config.get_string("listen_address", "0.0.0.0"); + _crypted = json_config.get_bool("encryption", false); + unsigned port = json_config.get_unsigned("port", _crypted ? 443 : 80); + asio::ip::tcp::resolver::query query(listen_address, std::to_string(port)); + asio::ip::tcp::resolver resolver(io_context); + boost::system::error_code ec; + asio::ip::tcp::resolver::iterator it = resolver.resolve(query, ec), end; + if (ec) { + throw exceptions::msg_fmt("unable to resolve {}:{}", listen_address, port); + } + if (it == end) { + throw exceptions::msg_fmt("no ip found for {}:{}", listen_address, port); + } + + _listen_endpoint = it->endpoint(); + + _second_keep_alive_interval = + json_config.get_unsigned("keepalive_interval", 30); + _check_interval = json_config.get_unsigned("check_interval", 60); + _certificate_path = json_config.get_string("certificate_path", ""); + _key_path = json_config.get_string("key_path", ""); + _engine_otl_endpoint = json_config.get_string("engine_otel_endpoint"); + if (_crypted) { + if (_certificate_path.empty()) { + SPDLOG_LOGGER_ERROR( + config_logger, + "telegraf conf server encryption activated and no certificate path " + "provided"); + throw exceptions::msg_fmt( + "telegraf conf server encryption activated and no certificate path " + "provided"); + } + if (_key_path.empty()) { + SPDLOG_LOGGER_ERROR(config_logger, + "telegraf conf server encryption activated and no " + "certificate key path provided"); + + throw exceptions::msg_fmt( + "telegraf conf server encryption activated and no certificate key " + "path provided"); + } + if (::access(_certificate_path.c_str(), R_OK)) { + SPDLOG_LOGGER_ERROR( + config_logger, + "telegraf conf server unable to read certificate file {}", + _certificate_path); + throw exceptions::msg_fmt( + "telegraf conf server unable to read certificate file {}", + _certificate_path); + } + if (::access(_key_path.c_str(), R_OK)) { + SPDLOG_LOGGER_ERROR( + config_logger, + "telegraf conf server unable to read certificate key file {}", + _key_path); + throw exceptions::msg_fmt( + "telegraf conf server unable to read certificate key file {}", + _key_path); + } + } +} + +bool conf_server_config::operator==(const conf_server_config& right) const { + return _listen_endpoint == right._listen_endpoint && + _crypted == right._crypted && + _second_keep_alive_interval == right._second_keep_alive_interval && + _certificate_path == right._certificate_path && + _key_path == right._key_path && + _check_interval == right._check_interval; +} + +/********************************************************************** + * session http(s) + **********************************************************************/ + +/** + * @brief http/https session + * + * @tparam connection_class http_connection or https_connection + */ +template +void conf_session::on_accept() { + connection_class::_on_accept( + [me = shared_from_this()](const boost::beast::error_code& err, + const std::string&) { + if (!err) + me->wait_for_request(); + }); +} + +/** + * @brief after connection or have sent a response, it waits for a new incomming + * request + * + * @tparam connection_class + */ +template +void conf_session::wait_for_request() { + connection_class::receive_request( + [me = shared_from_this()]( + const boost::beast::error_code& err, const std::string&, + const std::shared_ptr& request) { + if (err) { + SPDLOG_LOGGER_DEBUG(me->_logger, + "fail to receive request from {}: {}", me->_peer, + err.what()); + return; + } + me->on_receive_request(request); + }); +} + +/** + * @brief incomming request handler + * handler is passed to the main thread via command_manager::instance().enqueue + * + * @tparam connection_class + * @param request + */ +template +void conf_session::on_receive_request( + const std::shared_ptr& request) { + boost::url_view parsed(request->target()); + std::vector host_list; + + for (const auto& get_param : parsed.params()) { + if (get_param.key == "host") { + host_list.emplace_back(get_param.value); + } + } + auto to_call = std::packaged_task( + [me = shared_from_this(), request, + hosts = std::move(host_list)]() mutable -> int32_t { + // then we are in the main thread + // services, hosts and commands are stable + me->answer_to_request(request, std::move(hosts)); + return 0; + }); + command_manager::instance().enqueue(std::move(to_call)); +} + +/** + * @brief add a nagios paragraph to telegraf configuration + * + * @param cmd_name name of the command + * @param cmd_line command line configured and filled by macr contents + * @param host host name + * @param service service name + * @param to_append response body + * @return true a not empty command line is present after --cmd_line flag + * @return false + */ +template +bool conf_session::_otel_command_to_stream( + const std::string& cmd_name, + const std::string& cmd_line, + const std::string& host, + const std::string& service, + std::string& to_append) { + constexpr std::string_view flag = "--cmd_line"; + std::string plugins_cmdline; + size_t flag_pos = cmd_line.find(flag); + if (flag_pos != std::string::npos) { + plugins_cmdline = cmd_line.substr(flag_pos + flag.length() + 1); + boost::trim(plugins_cmdline); + } else { + SPDLOG_LOGGER_ERROR(this->_logger, + "host: {}, serv: {}, no --cmd_line found in {}", host, + service, cmd_line); + return false; + } + + if (plugins_cmdline.empty()) { + SPDLOG_LOGGER_ERROR(this->_logger, + "host: {}, serv: {}, no plugins cmd_line found in {}", + host, service, cmd_line); + return false; + } + + SPDLOG_LOGGER_DEBUG(this->_logger, + "host: {}, serv: {}, cmd {} plugins cmd_line {}", host, + service, cmd_name, cmd_line); + + fmt::format_to(std::back_inserter(to_append), R"( +[[inputs.exec]] + name_override = "{}" + commands = ["{}"] + data_format = "nagios" + [inputs.exec.tags] + host = "{}" + service = "{}" + +)", + cmd_name, plugins_cmdline, host, service); + return true; +} + +/** + * @brief Get all opentelemetry commands from an host and add its to + * configuration response + * + * @param host + * @param request_body conf to append + * @return true at least one opentelemetry command was found + * @return false + */ +template +bool conf_session::_get_commands(const std::string& host_name, + std::string& request_body) { + auto use_otl_command = [](const checkable& to_test) -> bool { + if (to_test.get_check_command_ptr()->get_type() == + commands::command::e_type::otel) + return true; + if (to_test.get_check_command_ptr()->get_type() == + commands::command::e_type::forward) { + return std::static_pointer_cast( + to_test.get_check_command_ptr()) + ->get_sub_command() + ->get_type() == commands::command::e_type::otel; + } + return false; + }; + + bool ret = false; + auto hst_iter = host::hosts.find(host_name); + if (hst_iter == host::hosts.end()) { + SPDLOG_LOGGER_ERROR(this->_logger, "unknown host:{}", host_name); + return false; + } + std::shared_ptr hst = hst_iter->second; + std::string cmd_line; + // host check use otl? + if (use_otl_command(*hst)) { + nagios_macros* macros(get_global_macros()); + + ret |= _otel_command_to_stream(hst->check_command(), + hst->get_check_command_line(macros), + hst->name(), "", request_body); + clear_volatile_macros_r(macros); + } else { + SPDLOG_LOGGER_DEBUG(this->_logger, + "host {} doesn't use telegraf to do his check", + host_name); + } + + // services of host + auto serv_iter = service::services_by_id.lower_bound({hst->host_id(), 0}); + for (; serv_iter != service::services_by_id.end() && + serv_iter->first.first == hst->host_id(); + ++serv_iter) { + std::shared_ptr serv = serv_iter->second; + if (use_otl_command(*serv)) { + nagios_macros* macros(get_global_macros()); + ret |= _otel_command_to_stream( + serv->check_command(), serv->get_check_command_line(macros), + serv->get_hostname(), serv->name(), request_body); + clear_volatile_macros_r(macros); + } else { + SPDLOG_LOGGER_DEBUG( + this->_logger, + "host {} service {} doesn't use telegraf to do his check", host_name, + serv->name()); + } + } + return ret; +} + +/** + * @brief construct and send conf to telegraf + * As it uses host, services and command list, it must be called in the main + * thread + * host::hosts and service::services must be stable during this call + * + * @tparam connection_class + * @param request incoming request + * @param host_list hosts extracted from get parameters + */ +template +void conf_session::answer_to_request( + const std::shared_ptr& request, + std::vector&& host_list) { + http::response_ptr resp(std::make_shared()); + resp->version(request->version()); + + if (host_list.empty()) { + SPDLOG_LOGGER_ERROR(this->_logger, "no host found in target argument {}", + *request); + } + + resp->body() = fmt::format(R"(# Centreon telegraf configuration +# This telegraf configuration is generated by centreon centengine +[agent] + ## Default data collection interval for all inputs + interval = "{}s" + +[[outputs.opentelemetry]] + service_address = "{}" + +)", + _telegraf_conf->get_check_interval(), + _telegraf_conf->get_engine_otl_endpoint()); + bool at_least_one_found = false; + for (const std::string& host : host_list) { + at_least_one_found |= _get_commands(host, resp->body()); + } + if (at_least_one_found) { + resp->result(boost::beast::http::status::ok); + resp->insert(boost::beast::http::field::content_type, "text/plain"); + } else { + resp->result(boost::beast::http::status::not_found); + resp->body() = + "No host service found from get parameters"; + } + resp->content_length(resp->body().length()); + + connection_class::answer( + resp, [me = shared_from_this()](const boost::beast::error_code& err, + const std::string& detail) { + if (err) { + SPDLOG_LOGGER_ERROR(me->_logger, "fail to answer to telegraf {} {}", + err.message(), detail); + return; + } + me->wait_for_request(); + }); +} + +namespace com::centreon::engine::modules::opentelemetry::telegraf { +template class conf_session; +template class conf_session; +}; // namespace com::centreon::engine::modules::opentelemetry::telegraf \ No newline at end of file diff --git a/engine/modules/opentelemetry/src/telegraf/nagios_converter.cc b/engine/modules/opentelemetry/src/telegraf/nagios_converter.cc new file mode 100644 index 00000000000..53dfc06832c --- /dev/null +++ b/engine/modules/opentelemetry/src/telegraf/nagios_converter.cc @@ -0,0 +1,265 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#include "data_point_fifo_container.hh" +#include "otl_converter.hh" + +#include "telegraf/nagios_converter.hh" + +using namespace com::centreon::engine::modules::opentelemetry::telegraf; + +constexpr std::array state_str{"OK", "WARNING", "CRITICAL", + "UNKNOWN"}; + +/****************************************************************** + * + * nagios telegraf converter + * inspired by +https://github.com/influxdata/telegraf/blob/master/plugins/parsers/nagios/parser.go + * informations at https://nagios-plugins.org/doc/guidelines.html#AEN200 + * example of received data: + * @code {.json} + { + "name": "check_icmp_critical_lt", + "gauge": { + "dataPoints": [ + { + "timeUnixNano": "1707744430000000000", + "asDouble": 0, + "attributes": [ + { + "key": "unit", + "value": { + "stringValue": "ms" + } + }, + { + "key": "host", + "value": { + "stringValue": "localhost" + } + }, + { + "key": "perfdata", + "value": { + "stringValue": "rta" + } + }, + { + "key": "service", + "value": { + "stringValue": "check_icmp" + } + } + ] + } + } + } + * @endcode + * +*******************************************************************/ + +namespace com::centreon::engine::modules::opentelemetry::telegraf::detail { + +struct perf_data { + std::string unit; + std::optional val; + std::optional warning_le, warning_lt, warning_ge, warning_gt; + std::optional critical_le, critical_lt, critical_ge, critical_gt; + std::optional min, max; + + bool fill_from_suffix(const std::string_view& suffix, + double value, + const std::shared_ptr& logger); + + static const absl::flat_hash_map perf_data::*> + _suffix_to_value; +}; + +const absl::flat_hash_map perf_data::*> + perf_data::_suffix_to_value = {{"warning_le", &perf_data::warning_le}, + {"warning_lt", &perf_data::warning_lt}, + {"warning_ge", &perf_data::warning_ge}, + {"warning_gt", &perf_data::warning_gt}, + {"critical_le", &perf_data::critical_le}, + {"critical_lt", &perf_data::critical_lt}, + {"critical_ge", &perf_data::critical_ge}, + {"critical_gt", &perf_data::critical_gt}, + {"min", &perf_data::min}, + {"max", &perf_data::max}, + {"value", &perf_data::val}}; + +/** + * @brief fill field identified by suffix + * + * @param suffix + * @param value + * @return true suffix is known + * @return false suffix is unknown and no value is set + */ +bool perf_data::fill_from_suffix( + const std::string_view& suffix, + double value, + const std::shared_ptr& logger) { + auto search = _suffix_to_value.find(suffix); + if (search != _suffix_to_value.end()) { + this->*search->second = value; + return true; + } + SPDLOG_LOGGER_WARN(logger, "unknown suffix {}", suffix); + return false; +} + +} // namespace com::centreon::engine::modules::opentelemetry::telegraf::detail + +/** + * @brief metric name in nagios telegraf are like check_icmp_min, + * check_icmp_critical_lt, check_icmp_value we extract all after check_icmp + * @param metric_name + * @return std::string_view suffix like min or critical_lt + */ +static std::string_view get_nagios_telegraf_suffix( + const std::string_view metric_name) { + std::size_t sep_pos = metric_name.rfind('_'); + if (sep_pos == std::string::npos) { + return ""; + } + std::string_view last_word = metric_name.substr(sep_pos + 1); + if (last_word == "lt" || last_word == "gt" || last_word == "le" || + last_word == "ge" && sep_pos > 0) { // critical_lt or warning_le + sep_pos = metric_name.rfind('_', sep_pos - 1); + if (sep_pos != std::string_view::npos) { + return metric_name.substr(sep_pos + 1); + } + } + return last_word; +} + +/** + * @brief + * + * @param fifos fifos indexed by metric_name such as check_icmp_critical_gt, + * check_icmp_state + * @return com::centreon::engine::commands::result + */ +bool otl_nagios_converter::_build_result_from_metrics( + metric_name_to_fifo& fifos, + commands::result& res) { + // first we search last state timestamp + uint64_t last_time = 0; + + for (auto& metric_to_fifo : fifos) { + if (get_nagios_telegraf_suffix(metric_to_fifo.first) == "state") { + auto& fifo = metric_to_fifo.second.get_fifo(); + if (!fifo.empty()) { + const auto& last_sample = *fifo.rbegin(); + last_time = last_sample.get_nano_timestamp(); + res.exit_code = last_sample.get_value(); + metric_to_fifo.second.clean_oldest(last_time); + } + break; + } + } + if (!last_time) { + return false; + } + res.command_id = get_command_id(); + res.exit_status = process::normal; + res.end_time = res.start_time = last_time / 1000000000; + + // construct perfdata list by perfdata name + std::map perfs; + + for (auto& metric_to_fifo : fifos) { + std::string_view suffix = get_nagios_telegraf_suffix(metric_to_fifo.first); + const data_point_fifo::container& data_points = + metric_to_fifo.second.get_fifo(); + // we scan all data points for that metric (example check_icmp_critical_gt + // can contain a data point for pl and another for rta) + auto data_pt_search = data_points.equal_range(last_time); + for (; data_pt_search.first != data_pt_search.second; + ++data_pt_search.first) { + const auto attributes = data_pt_search.first->get_data_point_attributes(); + std::string perfdata_name; + std::string unit; + for (const auto& attrib : attributes) { + if (attrib.key() == "perfdata") { + perfdata_name = attrib.value().string_value(); + } else if (attrib.key() == "unit") { + unit = attrib.value().string_value(); + } + if (!perfdata_name.empty() && !unit.empty()) { + break; + } + } + if (!perfdata_name.empty()) { + detail::perf_data& to_fill = perfs[perfdata_name]; + if (!unit.empty()) { + to_fill.unit = unit; + } + to_fill.fill_from_suffix(suffix, data_pt_search.first->get_value(), + _logger); + } + } + metric_to_fifo.second.clean_oldest(last_time); + } + + data_point_fifo_container::clean_empty_fifos(fifos); + + // then format all in a string with format: + // 'label'=value[UOM];[warn];[crit];[min];[max] + if (res.exit_code >= 0 && res.exit_code < 4) { + res.output = state_str[res.exit_code]; + } + res.output.push_back('|'); + for (const auto& perf : perfs) { + if (perf.second.val) { + absl::StrAppend(&res.output, perf.first, "=", *perf.second.val, + perf.second.unit, ";"); + if (perf.second.warning_le) { + absl::StrAppend(&res.output, "@", *perf.second.warning_le, ":", + *perf.second.warning_ge); + + } else if (perf.second.warning_lt) { + absl::StrAppend(&res.output, *perf.second.warning_lt, ":", + *perf.second.warning_gt); + } + res.output.push_back(';'); + if (perf.second.critical_le) { + absl::StrAppend(&res.output, "@", *perf.second.critical_le, ":", + *perf.second.critical_ge); + } else if (perf.second.critical_lt) { + absl::StrAppend(&res.output, *perf.second.critical_lt, ":", + *perf.second.critical_gt); + } + res.output.push_back(';'); + if (perf.second.min) { + absl::StrAppend(&res.output, *perf.second.min); + } + res.output.push_back(';'); + if (perf.second.max) { + absl::StrAppend(&res.output, *perf.second.max); + } + res.output.push_back(' '); + } + } + // remove last space + res.output.pop_back(); + return true; +} diff --git a/engine/precomp_inc/precomp.hh b/engine/precomp_inc/precomp.hh index 28b9f7f30d0..852545a1567 100644 --- a/engine/precomp_inc/precomp.hh +++ b/engine/precomp_inc/precomp.hh @@ -1,21 +1,20 @@ -/* -** Copyright 2022 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ +/** + * Copyright 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCE_PRECOMP_HH #define CCE_PRECOMP_HH @@ -62,6 +61,7 @@ #include #include +#include #include #include #include diff --git a/engine/src/configuration/applier/command.cc b/engine/src/configuration/applier/command.cc index bd875742b73..ee8ae3809a3 100644 --- a/engine/src/configuration/applier/command.cc +++ b/engine/src/configuration/applier/command.cc @@ -131,7 +131,7 @@ void applier::command::modify_object(configuration::command const& obj) { c->set_command_line(obj.command_line()); // Command will be temporarily removed from the command set but - // will be added back right after with _create_command. This does + // will be added back right after. This does // not create dangling pointers since commands::command object are // not referenced anywhere, only ::command objects are. commands::command::commands.erase(obj.command_name()); diff --git a/engine/src/main.cc b/engine/src/main.cc index 3f86a4cecc7..cb7da20c670 100644 --- a/engine/src/main.cc +++ b/engine/src/main.cc @@ -34,6 +34,8 @@ namespace asio = boost::asio; #include #include +#include + #include #include #include diff --git a/engine/tests/CMakeLists.txt b/engine/tests/CMakeLists.txt index f92ab3c35ba..b1abe1fbc20 100755 --- a/engine/tests/CMakeLists.txt +++ b/engine/tests/CMakeLists.txt @@ -196,6 +196,9 @@ if(WITH_TESTING) "-Wl,-no-whole-archive" pb_open_telemetry_lib centreon_grpc + centreon_http + -L${Boost_LIBRARY_DIR_RELEASE} + boost_url pthread ${GCOV} GTest::gtest diff --git a/engine/tests/opentelemetry/opentelemetry_test.cc b/engine/tests/opentelemetry/opentelemetry_test.cc new file mode 100644 index 00000000000..7e26c6a5610 --- /dev/null +++ b/engine/tests/opentelemetry/opentelemetry_test.cc @@ -0,0 +1,240 @@ +/** + * Copyright 2024 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include + +#include "com/centreon/common/http/http_server.hh" +#include "com/centreon/engine/configuration/applier/contact.hh" +#include "com/centreon/engine/configuration/applier/host.hh" +#include "com/centreon/engine/configuration/applier/service.hh" +#include "com/centreon/engine/configuration/host.hh" +#include "com/centreon/engine/configuration/service.hh" + +#include "opentelemetry/proto/collector/metrics/v1/metrics_service.pb.h" +#include "opentelemetry/proto/common/v1/common.pb.h" +#include "opentelemetry/proto/metrics/v1/metrics.pb.h" + +#include "com/centreon/engine/modules/opentelemetry/opentelemetry.hh" + +#include "helper.hh" +#include "test_engine.hh" + +using namespace com::centreon::engine::modules::opentelemetry; +using namespace com::centreon::engine; + +extern const char* telegraf_example; + +extern std::shared_ptr g_io_context; + +class open_telemetry + : public com::centreon::engine::modules::opentelemetry::open_telemetry { + protected: + void _create_otl_server(const grpc_config::pointer& server_conf) override {} + + public: + open_telemetry(const std::string_view config_file_path, + const std::shared_ptr& io_context, + const std::shared_ptr& logger) + : com::centreon::engine::modules::opentelemetry::open_telemetry( + config_file_path, + io_context, + logger) {} + + void on_metric(const metric_request_ptr& metric) { _on_metric(metric); } + void shutdown() { _shutdown(); } + static std::shared_ptr load( + const std::string_view& config_path, + const std::shared_ptr& io_context, + const std::shared_ptr& logger) { + std::shared_ptr ret = + std::make_shared(config_path, io_context, logger); + ret->_reload(); + ret->_start_second_timer(); + return ret; + } +}; + +class open_telemetry_test : public TestEngine { + public: + commands::otel::host_serv_list::pointer _host_serv_list; + + open_telemetry_test(); + static void SetUpTestSuite(); + void SetUp() override; + void TearDown() override; +}; + +open_telemetry_test::open_telemetry_test() + : _host_serv_list(std::make_shared()) { + _host_serv_list->register_host_serv("localhost", "check_icmp"); +} + +void open_telemetry_test::SetUpTestSuite() { + std::ofstream conf_file("/tmp/otel_conf.json"); + conf_file << R"({ + "server": { + "host": "127.0.0.1", + "port": 4317 + } +} +)"; + conf_file.close(); + // spdlog::default_logger()->set_level(spdlog::level::trace); +} + +void open_telemetry_test::SetUp() { + init_config_state(); + config->contacts().clear(); + configuration::applier::contact ct_aply; + configuration::contact ctct{new_configuration_contact("admin", true)}; + ct_aply.add_object(ctct); + ct_aply.expand_objects(*config); + ct_aply.resolve_object(ctct); + + configuration::host hst{new_configuration_host("localhost", "admin")}; + configuration::applier::host hst_aply; + hst_aply.add_object(hst); + + configuration::service svc{ + new_configuration_service("localhost", "check_icmp", "admin")}; + configuration::applier::service svc_aply; + svc_aply.add_object(svc); + + hst_aply.resolve_object(hst); + svc_aply.resolve_object(svc); + data_point_fifo::update_fifo_limit(std::numeric_limits::max(), 10); +} + +void open_telemetry_test::TearDown() { + deinit_config_state(); +} + +TEST_F(open_telemetry_test, data_available) { + auto instance = ::open_telemetry::load("/tmp/otel_conf.json", g_io_context, + spdlog::default_logger()); + + instance->create_extractor( + "", _host_serv_list); // create a defaut attribute extractor + + metric_request_ptr request = + std::make_shared<::opentelemetry::proto::collector::metrics::v1:: + ExportMetricsServiceRequest>(); + ::google::protobuf::util::JsonStringToMessage(telegraf_example, + request.get()); + instance->on_metric(request); + // data are now available + commands::result res; + nagios_macros macros; + macros.host_ptr = host::hosts.begin()->second.get(); + macros.service_ptr = service::services.begin()->second.get(); + ASSERT_TRUE(instance->check("nagios_telegraf", 1, macros, 1, res, + [](const commands::result&) {})); + ASSERT_EQ(res.command_id, 1); + ASSERT_EQ(res.start_time.to_useconds(), 1707744430000000); + ASSERT_EQ(res.end_time.to_useconds(), 1707744430000000); + ASSERT_EQ(res.exit_code, 0); + ASSERT_EQ(res.exit_status, com::centreon::process::normal); + ASSERT_EQ(res.output, + "OK|pl=0%;0:40;0:80;; rta=0.022ms;0:200;0:500;0; rtmax=0.071ms;;;; " + "rtmin=0.008ms;;;;"); +} + +TEST_F(open_telemetry_test, timeout) { + auto instance = ::open_telemetry::load("/tmp/otel_conf.json", g_io_context, + spdlog::default_logger()); + + instance->create_extractor( + "", _host_serv_list); // create a defaut attribute extractor + + commands::result res; + res.exit_status = com::centreon::process::normal; + nagios_macros macros; + macros.host_ptr = host::hosts.begin()->second.get(); + macros.service_ptr = service::services.begin()->second.get(); + std::condition_variable cv; + std::mutex cv_m; + ASSERT_FALSE(instance->check("nagios_telegraf", 1, macros, 1, res, + [&res, &cv](const commands::result& async_res) { + res = async_res; + cv.notify_one(); + })); + + std::unique_lock l(cv_m); + ASSERT_EQ(cv.wait_for(l, std::chrono::seconds(3)), + std::cv_status::no_timeout); + ASSERT_EQ(res.exit_status, com::centreon::process::timeout); +} + +TEST_F(open_telemetry_test, wait_for_data) { + auto instance = ::open_telemetry::load("/tmp/otel_conf.json", g_io_context, + spdlog::default_logger()); + + instance->create_extractor( + "", _host_serv_list); // create a defaut attribute extractor + + commands::result res; + res.exit_status = com::centreon::process::normal; + nagios_macros macros; + macros.host_ptr = host::hosts.begin()->second.get(); + macros.service_ptr = service::services.begin()->second.get(); + std::mutex cv_m; + std::condition_variable cv; + bool data_available = + instance->check("nagios_telegraf", 1, macros, 1, res, + [&res, &cv](const commands::result& async_res) { + res = async_res; + cv.notify_one(); + }); + ASSERT_FALSE(data_available); + + metric_request_ptr request = + std::make_shared<::opentelemetry::proto::collector::metrics::v1:: + ExportMetricsServiceRequest>(); + ::google::protobuf::util::JsonStringToMessage(telegraf_example, + request.get()); + std::thread t([instance, request]() { instance->on_metric(request); }); + + std::unique_lock l(cv_m); + ASSERT_EQ(cv.wait_for(l, std::chrono::seconds(1)), + std::cv_status::no_timeout); + ASSERT_EQ(res.command_id, 1); + ASSERT_EQ(res.start_time.to_useconds(), 1707744430000000); + ASSERT_EQ(res.end_time.to_useconds(), 1707744430000000); + ASSERT_EQ(res.exit_code, 0); + ASSERT_EQ(res.exit_status, com::centreon::process::normal); + ASSERT_EQ(res.output, + "OK|pl=0%;0:40;0:80;; rta=0.022ms;0:200;0:500;0; rtmax=0.071ms;;;; " + "rtmin=0.008ms;;;;"); + t.join(); +} diff --git a/engine/tests/opentelemetry/otl_converter_test.cc b/engine/tests/opentelemetry/otl_converter_test.cc index 900b6f36e55..430ab19f263 100644 --- a/engine/tests/opentelemetry/otl_converter_test.cc +++ b/engine/tests/opentelemetry/otl_converter_test.cc @@ -38,6 +38,7 @@ #include "com/centreon/engine/modules/opentelemetry/data_point_fifo_container.hh" #include "com/centreon/engine/modules/opentelemetry/otl_converter.hh" +#include "com/centreon/engine/modules/opentelemetry/telegraf/nagios_converter.hh" #include "helper.hh" #include "test_engine.hh" @@ -78,6 +79,17 @@ void otl_converter_test::TearDown() { deinit_config_state(); } +TEST_F(otl_converter_test, empty_fifo) { + data_point_fifo_container empty; + telegraf::otl_nagios_converter conv( + "", 1, *host::hosts.begin()->second, + service::services.begin()->second.get(), + std::chrono::system_clock::time_point(), [&](const commands::result&) {}, + spdlog::default_logger()); + commands::result res; + ASSERT_FALSE(conv.sync_build_result_from_metrics(empty, res)); +} + const char* telegraf_example = R"( { "resourceMetrics": [ @@ -561,3 +573,100 @@ const char* telegraf_example = R"( } )"; +TEST_F(otl_converter_test, nagios_telegraf) { + data_point_fifo_container received; + metric_request_ptr request = + std::make_shared< ::opentelemetry::proto::collector::metrics::v1:: + ExportMetricsServiceRequest>(); + ::google::protobuf::util::JsonStringToMessage(telegraf_example, + request.get()); + + data_point::extract_data_points(request, [&](const data_point& data_pt) { + received.add_data_point("localhost", "check_icmp", + data_pt.get_metric().name(), data_pt); + }); + + telegraf::otl_nagios_converter conv( + "", 1, *host::hosts.begin()->second, + service::services.begin()->second.get(), + std::chrono::system_clock::time_point(), [&](const commands::result&) {}, + spdlog::default_logger()); + commands::result res; + ASSERT_TRUE(conv.sync_build_result_from_metrics(received, res)); + ASSERT_EQ(res.command_id, 1); + ASSERT_EQ(res.start_time.to_useconds(), 1707744430000000); + ASSERT_EQ(res.end_time.to_useconds(), 1707744430000000); + ASSERT_EQ(res.exit_code, 0); + ASSERT_EQ(res.exit_status, com::centreon::process::normal); + ASSERT_EQ(res.output, + "OK|pl=0%;0:40;0:80;; rta=0.022ms;0:200;0:500;0; rtmax=0.071ms;;;; " + "rtmin=0.008ms;;;;"); +} + +TEST_F(otl_converter_test, nagios_telegraf_le_ge) { + data_point_fifo_container received; + metric_request_ptr request = + std::make_shared< ::opentelemetry::proto::collector::metrics::v1:: + ExportMetricsServiceRequest>(); + std::string example = telegraf_example; + boost::algorithm::replace_all(example, "check_icmp_critical_gt", + "check_icmp_critical_ge"); + boost::algorithm::replace_all(example, "check_icmp_critical_lt", + "check_icmp_critical_le"); + + ::google::protobuf::util::JsonStringToMessage(example, request.get()); + + data_point::extract_data_points(request, [&](const data_point& data_pt) { + received.add_data_point("localhost", "check_icmp", + data_pt.get_metric().name(), data_pt); + }); + + telegraf::otl_nagios_converter conv( + "", 1, *host::hosts.begin()->second, + service::services.begin()->second.get(), + std::chrono::system_clock::time_point(), [&](const commands::result&) {}, + spdlog::default_logger()); + commands::result res; + ASSERT_TRUE(conv.sync_build_result_from_metrics(received, res)); + ASSERT_EQ(res.command_id, 1); + ASSERT_EQ(res.start_time.to_useconds(), 1707744430000000); + ASSERT_EQ(res.end_time.to_useconds(), 1707744430000000); + ASSERT_EQ(res.exit_code, 0); + ASSERT_EQ(res.exit_status, com::centreon::process::normal); + ASSERT_EQ( + res.output, + "OK|pl=0%;0:40;@0:80;; rta=0.022ms;0:200;@0:500;0; rtmax=0.071ms;;;; " + "rtmin=0.008ms;;;;"); +} + +TEST_F(otl_converter_test, nagios_telegraf_max) { + data_point_fifo_container received; + metric_request_ptr request = + std::make_shared< ::opentelemetry::proto::collector::metrics::v1:: + ExportMetricsServiceRequest>(); + std::string example = telegraf_example; + boost::algorithm::replace_all(example, "check_icmp_min", "check_icmp_max"); + + ::google::protobuf::util::JsonStringToMessage(example, request.get()); + + data_point::extract_data_points(request, [&](const data_point& data_pt) { + received.add_data_point("localhost", "check_icmp", + data_pt.get_metric().name(), data_pt); + }); + + telegraf::otl_nagios_converter conv( + "", 1, *host::hosts.begin()->second, + service::services.begin()->second.get(), + std::chrono::system_clock::time_point(), [&](const commands::result&) {}, + spdlog::default_logger()); + commands::result res; + ASSERT_TRUE(conv.sync_build_result_from_metrics(received, res)); + ASSERT_EQ(res.command_id, 1); + ASSERT_EQ(res.start_time.to_useconds(), 1707744430000000); + ASSERT_EQ(res.end_time.to_useconds(), 1707744430000000); + ASSERT_EQ(res.exit_code, 0); + ASSERT_EQ(res.exit_status, com::centreon::process::normal); + ASSERT_EQ(res.output, + "OK|pl=0%;0:40;0:80;; rta=0.022ms;0:200;0:500;;0 rtmax=0.071ms;;;; " + "rtmin=0.008ms;;;;"); +} diff --git a/packaging/centreon-engine-opentelemetry-debuginfo.yaml b/packaging/centreon-engine-opentelemetry-debuginfo.yaml new file mode 100644 index 00000000000..383627db89c --- /dev/null +++ b/packaging/centreon-engine-opentelemetry-debuginfo.yaml @@ -0,0 +1,42 @@ +name: "centreon-engine-opentelemetry-debuginfo" +arch: "${ARCH}" +platform: "linux" +version_schema: "none" +version: "${VERSION}" +release: "${RELEASE}${DIST}" +section: "default" +priority: "optional" +maintainer: "Centreon " +description: | + Debuginfo package for centreon-engine. + Commit: @COMMIT_HASH@ +vendor: "Centreon" +homepage: "https://www.centreon.com" +license: "Apache-2.0" + +contents: + - src: "../build/engine/modules/opentelemetry/libopentelemetry.so.debug" + dst: "/usr/lib/debug/usr/lib64/centreon-engine/libopentelemetry.so.debug" + file_info: + mode: 0644 + +overrides: + rpm: + depends: + - centreon-engine-opentelemetry = ${VERSION}-${RELEASE}${DIST} + deb: + depends: + - centreon-engine-opentelemetry (= ${VERSION}-${RELEASE}${DIST}) + conflicts: + - centreon-engine-opentelemetry-dbgsym + replaces: + - centreon-engine-opentelemetry-dbgsym + provides: + - centreon-engine-opentelemetry-dbgsym + +rpm: + summary: Debuginfo package for centreon-engine-opentelemetry. + compression: zstd + signature: + key_file: ${RPM_SIGNING_KEY_FILE} + key_id: ${RPM_SIGNING_KEY_ID} diff --git a/packaging/centreon-engine-opentelemetry.yaml b/packaging/centreon-engine-opentelemetry.yaml new file mode 100644 index 00000000000..ef8dccea651 --- /dev/null +++ b/packaging/centreon-engine-opentelemetry.yaml @@ -0,0 +1,34 @@ +name: "centreon-engine-opentelemetry" +arch: "${ARCH}" +platform: "linux" +version_schema: "none" +version: "${VERSION}" +release: "${RELEASE}${DIST}" +section: "default" +priority: "optional" +maintainer: "Centreon " +description: | + Centreon Engine OpenTelemetry listener. + Commit: @COMMIT_HASH@ +vendor: "Centreon" +homepage: "https://www.centreon.com" +license: "Apache-2.0" + +contents: + - src: "../build/engine/modules/opentelemetry/libopentelemetry.so" + dst: "/usr/lib64/centreon-engine/libopentelemetry.so" + +overrides: + rpm: + depends: + - centreon-engine-daemon = ${VERSION}-${RELEASE}${DIST} + deb: + depends: + - centreon-engine-daemon (= ${VERSION}-${RELEASE}${DIST}) + +rpm: + summary: Centreon Engine OpenTelemetry listener. + compression: zstd + signature: + key_file: ${RPM_SIGNING_KEY_FILE} + key_id: ${RPM_SIGNING_KEY_ID} diff --git a/tests/README.md b/tests/README.md index 3a7620c20a4..b009245817b 100644 --- a/tests/README.md +++ b/tests/README.md @@ -40,7 +40,7 @@ git clone https://github.com/open-telemetry/opentelemetry-proto.git opentelemetr On other rpm based distributions, you can try the following commands to initialize your robot tests: ``` -pip3 install -U robotframework robotframework-databaselibrary robotframework-httpctrl robotframework-examples pymysql +pip3 install -U robotframework robotframework-databaselibrary robotframework-httpctrl robotframework-examples pymysql robotframework-requests yum install python3-devel -y diff --git a/tests/broker-engine/notifications.robot b/tests/broker-engine/notifications.robot index 9cde528b806..4507bb646b3 100644 --- a/tests/broker-engine/notifications.robot +++ b/tests/broker-engine/notifications.robot @@ -1041,6 +1041,7 @@ not16 [Tags] broker engine services unified_sql Ctn Clear Commands Status Ctn Config Engine ${1} ${4} ${1} + Ctn Set Services Passive ${0} service_.* Ctn Engine Config Set Value 0 interval_length 1 True Ctn Config Engine Add Cfg File ${0} servicegroups.cfg Ctn Add service Group ${0} ${1} ["host_1","service_1", "host_2","service_2"] @@ -1105,7 +1106,6 @@ not16 ${cmd_service_3} Ctn Get Service Command Id ${3} ${cmd_service_4} Ctn Get Service Command Id ${4} - Ctn Set Command Status ${cmd_service_3} ${0} Ctn Process Service Result Hard host_3 service_3 ${0} The service_3 is OK @@ -1113,7 +1113,7 @@ not16 Should Be True ${result} Service (host_3,service_3) should be OK HARD ##Time to set the service3 to CRITICAL HARD. - Ctn Set Command Status ${cmd_service_3} ${2} + ${start} Ctn Get Round Current Date Ctn Process Service Result Hard host_3 service_3 ${2} The service_3 is CRITICAL @@ -1126,7 +1126,6 @@ not16 ## Time to set the service3 to OK hard ${start} Ctn Get Round Current Date - Ctn Set Command Status ${cmd_service_3} ${0} Ctn Process Service Result Hard host_3 service_3 ${0} The service_3 is OK @@ -1139,7 +1138,6 @@ not16 ## Time to set the service1 to CRITICAL HARD. ${start} Ctn Get Round Current Date - Ctn Set Command Status ${cmd_service_1} ${2} Ctn Process Service Result Hard host_1 service_1 ${2} The service_1 is CRITICAL ${result} Ctn Check Service Resource Status With Timeout host_1 service_1 ${2} 60 HARD @@ -1151,7 +1149,6 @@ not16 ## Time to set the service3 to CRITICAL HARD. ${start} Ctn Get Round Current Date - Ctn Set Command Status ${cmd_service_3} ${2} Ctn Process Service Result Hard host_3 service_3 ${2} The service_3 is CRITICAL @@ -1164,7 +1161,6 @@ not16 ## Time to set the service4 to CRITICAL HARD. ${start} Ctn Get Round Current Date - Ctn Set Command Status ${cmd_service_4} ${2} Ctn Process Service Result Hard host_4 service_4 ${2} The service_4 is CRITICAL @@ -1178,7 +1174,6 @@ not16 ## Time to set the service1 to OK hard ${start} Ctn Get Round Current Date - Ctn Set Command Status ${cmd_service_1} ${0} Ctn Process Service Result Hard host_1 service_1 ${0} The service_1 is OK diff --git a/tests/broker-engine/opentelemetry.robot b/tests/broker-engine/opentelemetry.robot new file mode 100644 index 00000000000..caa5cc518ea --- /dev/null +++ b/tests/broker-engine/opentelemetry.robot @@ -0,0 +1,428 @@ +*** Settings *** +Documentation Engine/Broker tests on opentelemetry engine server + +Resource ../resources/import.resource + +Suite Setup Ctn Clean Before Suite +Suite Teardown Ctn Clean After Suite +Test Setup Ctn Stop Processes +Test Teardown Ctn Stop Engine Broker And Save Logs + + +*** Test Cases *** +# to enable when engine will be able to send unknown metrics to victoria metrics +# BEOTEL1 +# [Documentation] store_in_resources is enabled and store_in_hosts_services is not. Only writes into resources should be done (except hosts/services events that continue to be written in hosts/services tables) +# [Tags] broker engine opentelemetry mon-34074 +# Ctn Config Engine ${1} +# Add Otl ServerModule 0 {"server":{"host": "0.0.0.0","port": 4317}} +# Config Broker central +# Config Broker module +# Config Broker rrd +# Broker Config Source Log central True +# Broker Config Add Lua Output central dump-otl-event ${SCRIPTS}dump-otl-event.lua + +# Ctn ConfigBBDO3 1 +# Config Broker Sql Output central unified_sql +# Ctn Clear Retention + +# Remove File /tmp/lua.log + +# ${start} Get Current Date +# Ctn Start Broker +# Ctn Start Engine + +# # Let's wait for the otel server start +# ${content} Create List unencrypted server listening on 0.0.0.0:4317 +# ${result} Find In Log With Timeout ${engineLog0} ${start} ${content} 10 +# Should Be True ${result} "unencrypted server listening on 0.0.0.0:4317" should be available. + +# Sleep 1s + +# ${all_attributes} Create List +# ${resources_list} Create List +# ${json_resources_list} Create List +# FOR ${resource_index} IN RANGE 2 +# ${scope_metrics_list} Create List +# FOR ${scope_metric_index} IN RANGE 2 +# ${metrics_list} Create List +# FOR ${metric_index} IN RANGE 2 +# ${metric_attrib} Create Random Dictionary 5 +# Append To List ${all_attributes} ${metric_attrib} +# ${metric} Create Otl Metric metric_${metric_index} 5 ${metric_attrib} +# Append To List ${metrics_list} ${metric} +# END +# ${scope_attrib} Create Random Dictionary 5 +# Append To List ${all_attributes} ${scope_attrib} +# ${scope_metric} Create Otl Scope Metrics ${scope_attrib} ${metrics_list} +# Append To List ${scope_metrics_list} ${scope_metric} +# END +# ${resource_attrib} Create Random Dictionary 5 +# Append To List ${all_attributes} ${resource_attrib} +# ${resource_metrics} Create Otl Resource Metrics ${resource_attrib} ${scope_metrics_list} +# Append To List ${resources_list} ${resource_metrics} +# ${json_resource_metrics} Protobuf To Json ${resource_metrics} +# Append To List ${json_resources_list} ${json_resource_metrics} +# END + +# Log To Console export metrics +# Send Otl To Engine 4317 ${resources_list} + +# Sleep 5 + +# ${event} Extract Event From Lua Log /tmp/lua.log resource_metrics + +# ${test_ret} Is List In Other List ${event} ${json_resources_list} + +# Should Be True ${test_ret} protobuf object sent to engine mus be in lua.log + +BEOTEL_TELEGRAF_CHECK_HOST + [Documentation] we send nagios telegraf formated datas and we expect to get it in check result + [Tags] broker engine opentelemetry mon-34004 + Ctn Config Engine ${1} ${2} ${2} + Ctn Add Otl ServerModule + ... 0 + ... {"server":{"host": "0.0.0.0","port": 4317},"max_length_grpc_log":0} + Ctn Config Add Otl Connector + ... 0 + ... OTEL connector + ... open_telemetry attributes --host_attribute=data_point --host_key=host --service_attribute=data_point --service_key=service + Ctn Engine Config Replace Value In Hosts ${0} host_1 check_command otel_check_icmp + Ctn Engine Config Add Command + ... ${0} + ... otel_check_icmp + ... nagios_telegraf --cmd_line /usr/lib/nagios/plugins/check_icmp 127.0.0.1 + ... OTEL connector + + Ctn Engine Config Set Value 0 log_level_checks trace + + Ctn Config Broker central + Ctn Config Broker module + Ctn Config Broker rrd + Ctn Broker Config Log central sql trace + + Ctn ConfigBBDO3 1 + Ctn Clear Retention + + ${start} Get Current Date + Ctn Start Broker + Ctn Start Engine + + # Let's wait for the otel server start + ${content} Create List unencrypted server listening on 0.0.0.0:4317 + ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 10 + Should Be True ${result} "unencrypted server listening on 0.0.0.0:4317" should be available. + Sleep 1 + + ${resources_list} Ctn Create Otl Request ${0} host_1 + + Log To Console export metrics + Ctn Send Otl To Engine 4317 ${resources_list} + + Sleep 5 + + # feed and check + ${start} Ctn Get Round Current Date + Ctn Schedule Forced Host Check host_1 + + ${result} Ctn Check Host Check Status With Timeout host_1 30 ${start} 0 OK + Should Be True ${result} hosts table not updated + + # check without feed + + ${start} Ctn Get Round Current Date + Ctn Schedule Forced Host Check host_1 + ${result} Ctn Check Host Check Status With Timeout + ... host_1 + ... 35 + ... ${start} + ... 0 + ... (No output returned from host check) + Should Be True ${result} hosts table not updated + + # check then feed, three times to modify hard state + ${start} Ctn Get Round Current Date + Ctn Schedule Forced Host Check host_1 + Sleep 2 + ${resources_list} Ctn Create Otl Request ${2} host_1 + Ctn Send Otl To Engine 4317 ${resources_list} + Ctn Schedule Forced Host Check host_1 + Sleep 2 + ${resources_list} Ctn Create Otl Request ${2} host_1 + Ctn Send Otl To Engine 4317 ${resources_list} + Ctn Schedule Forced Host Check host_1 + Sleep 2 + ${resources_list} Ctn Create Otl Request ${2} host_1 + Ctn Send Otl To Engine 4317 ${resources_list} + ${result} Ctn Check Host Check Status With Timeout host_1 30 ${start} 1 CRITICAL + + Should Be True ${result} hosts table not updated + +BEOTEL_TELEGRAF_CHECK_SERVICE + [Documentation] we send nagios telegraf formated datas and we expect to get it in check result + [Tags] broker engine opentelemetry mon-34004 + Ctn Config Engine ${1} ${2} ${2} + Ctn Add Otl ServerModule 0 {"server":{"host": "0.0.0.0","port": 4317},"max_length_grpc_log":0} + Ctn Config Add Otl Connector + ... 0 + ... OTEL connector + ... open_telemetry attributes --host_attribute=data_point --host_key=host --service_attribute=data_point --service_key=service + Ctn Engine Config Replace Value In Services ${0} service_1 check_command otel_check_icmp + Ctn Engine Config Add Command + ... ${0} + ... otel_check_icmp + ... nagios_telegraf + ... OTEL connector + + Ctn Engine Config Set Value 0 log_level_checks trace + + Ctn Config Broker central + Ctn Config Broker module + Ctn Config Broker rrd + + Ctn ConfigBBDO3 1 + Ctn Config Broker Sql Output central unified_sql + Ctn Clear Retention + + ${start} Get Current Date + Ctn Start Broker + Ctn Start Engine + + # Let's wait for the otel server start + ${content} Create List unencrypted server listening on 0.0.0.0:4317 + ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 10 + Should Be True ${result} "unencrypted server listening on 0.0.0.0:4317" should be available. + Sleep 1 + + ${resources_list} Ctn Create Otl Request ${0} host_1 service_1 + + Log To Console export metrics + Ctn Send Otl To Engine 4317 ${resources_list} + + Sleep 5 + + # feed and check + ${start} Ctn Get Round Current Date + Ctn Schedule Forced Svc Check host_1 service_1 + + ${result} Ctn Check Service Check Status With Timeout host_1 service_1 30 ${start} 0 OK + Should Be True ${result} services table not updated + + # check without feed + + ${start} Ctn Get Round Current Date + Ctn Schedule Forced Svc Check host_1 service_1 + ${result} Ctn Check Service Check Status With Timeout + ... host_1 + ... service_1 + ... 35 + ... ${start} + ... 0 + ... (No output returned from plugin) + Should Be True ${result} services table not updated + + # check then feed, three times to modify hard state + ${start} Ctn Get Round Current Date + Ctn Schedule Forced Svc Check host_1 service_1 + Sleep 2 + ${resources_list} Ctn Create Otl Request ${2} host_1 service_1 + Ctn Send Otl To Engine 4317 ${resources_list} + Ctn Schedule Forced Svc Check host_1 service_1 + Sleep 2 + ${resources_list} Ctn Create Otl Request ${2} host_1 service_1 + Ctn Send Otl To Engine 4317 ${resources_list} + Ctn Schedule Forced Svc Check host_1 service_1 + Sleep 2 + ${resources_list} Ctn Create Otl Request ${2} host_1 service_1 + Ctn Send Otl To Engine 4317 ${resources_list} + ${result} Ctn Check Service Check Status With Timeout host_1 service_1 30 ${start} 2 CRITICAL + + Should Be True ${result} services table not updated + +BEOTEL_SERVE_TELEGRAF_CONFIGURATION_CRYPTED + [Documentation] we configure engine with a telegraf conf server and we check telegraf conf file + [Tags] broker engine opentelemetry mon-35539 + Ctn Create Key And Certificate localhost /tmp/otel/server.key /tmp/otel/server.crt + Ctn Config Engine ${1} ${3} ${2} + Ctn Add Otl ServerModule + ... 0 + ... {"server":{"host": "0.0.0.0","port": 4317},"max_length_grpc_log":0, "telegraf_conf_server": {"port": 1443, "encryption": true, "engine_otel_endpoint": "127.0.0.1:4317", "certificate_path": "/tmp/otel/server.crt", "key_path": "/tmp/otel/server.key"}} + Ctn Config Add Otl Connector + ... 0 + ... OTEL connector + ... open_telemetry attributes --host_attribute=data_point --host_key=host --service_attribute=data_point --service_key=service + Ctn Engine Config Replace Value In Services ${0} service_1 check_command otel_check_icmp_serv_1 + Ctn Engine Config Add Command + ... ${0} + ... otel_check_icmp_serv_1 + ... nagios_telegraf --cmd_line /usr/lib/nagios/plugins/check_icmp 127.0.0.1 + ... OTEL connector + + Ctn Engine Config Replace Value In Services ${0} service_2 check_command otel_check_icmp_serv_2 + Ctn Engine Config Add Command + ... ${0} + ... otel_check_icmp_serv_2 + ... nagios_telegraf --cmd_line /usr/lib/nagios/plugins/check_icmp 127.0.0.2 + ... OTEL connector + + Ctn Engine Config Replace Value In Hosts ${0} host_1 check_command otel_check_icmp_host_1 + Ctn Engine Config Add Command + ... ${0} + ... otel_check_icmp_host_1 + ... nagios_telegraf --cmd_line /usr/lib/nagios/plugins/check_icmp 127.0.0.10 + ... OTEL connector + + Ctn Engine Config Replace Value In Hosts ${0} host_2 check_command otel_check_icmp_host_2 + Ctn Engine Config Add Command + ... ${0} + ... otel_check_icmp_host_2 + ... nagios_telegraf --cmd_line /usr/lib/nagios/plugins/check_icmp 127.0.0.20 + ... OTEL connector + + Ctn Engine Config Replace Value In Services ${0} service_5 check_command otel_check_icmp_serv_5 + Ctn Engine Config Add Command + ... ${0} + ... otel_check_icmp_serv_5 + ... nagios_telegraf --cmd_line /usr/lib/nagios/plugins/check_icmp 127.0.0.5 + ... OTEL connector + + Ctn Engine Config Set Value 0 log_level_checks trace + + Ctn Config Broker module + + Ctn Clear Retention + + ${start} Get Current Date + Ctn Start Engine + + # Let's wait for the otel server start + ${content} Create List server listen on 0.0.0.0:1443 + ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 10 + Should Be True ${result} "server listen on 0.0.0.0:1443" should be available. + Sleep 1 + ${telegraf_conf_response} GET + ... verify=${False} + ... url=https://localhost:1443/engine?host=host_1&host=host_2&host=host_3 + + Should Be Equal As Strings ${telegraf_conf_response.reason} OK no response received or error response + ${content_compare_result} Ctn Compare String With File + ... ${telegraf_conf_response.text} + ... resources/opentelemetry/telegraf.conf + + Should Be True + ... ${content_compare_result} + ... unexpected telegraf server response: ${telegraf_conf_response.text} + +BEOTEL_SERVE_TELEGRAF_CONFIGURATION_NO_CRYPTED + [Documentation] we configure engine with a telegraf conf server and we check telegraf conf file + [Tags] broker engine opentelemetry mon-35539 + Ctn Create Key And Certificate localhost /tmp/otel/server.key /tmp/otel/server.crt + Ctn Config Engine ${1} ${3} ${2} + Ctn Add Otl ServerModule + ... 0 + ... {"server":{"host": "0.0.0.0","port": 4317},"max_length_grpc_log":0, "telegraf_conf_server": {"port": 1443, "encryption": false, "engine_otel_endpoint": "127.0.0.1:4317"}} + Ctn Config Add Otl Connector + ... 0 + ... OTEL connector + ... /usr/lib64/centreon-connector/open_telemetry attributes --host_attribute=data_point --host_key=host --service_attribute=data_point --service_key=service + Ctn Engine Config Replace Value In Services ${0} service_1 check_command otel_check_icmp_serv_1 + Ctn Engine Config Add Command + ... ${0} + ... otel_check_icmp_serv_1 + ... nagios_telegraf --cmd_line /usr/lib/nagios/plugins/check_icmp 127.0.0.1 + ... OTEL connector + + Ctn Engine Config Replace Value In Services ${0} service_2 check_command otel_check_icmp_serv_2 + Ctn Engine Config Add Command + ... ${0} + ... otel_check_icmp_serv_2 + ... nagios_telegraf --cmd_line /usr/lib/nagios/plugins/check_icmp 127.0.0.2 + ... OTEL connector + + Ctn Engine Config Replace Value In Hosts ${0} host_1 check_command otel_check_icmp_host_1 + Ctn Engine Config Add Command + ... ${0} + ... otel_check_icmp_host_1 + ... nagios_telegraf --cmd_line /usr/lib/nagios/plugins/check_icmp 127.0.0.10 + ... OTEL connector + + Ctn Engine Config Replace Value In Hosts ${0} host_2 check_command otel_check_icmp_host_2 + Ctn Engine Config Add Command + ... ${0} + ... otel_check_icmp_host_2 + ... nagios_telegraf --cmd_line /usr/lib/nagios/plugins/check_icmp 127.0.0.20 + ... OTEL connector + + Ctn Engine Config Replace Value In Services ${0} service_5 check_command otel_check_icmp_serv_5 + Ctn Engine Config Add Command + ... ${0} + ... otel_check_icmp_serv_5 + ... nagios_telegraf --cmd_line /usr/lib/nagios/plugins/check_icmp 127.0.0.5 + ... OTEL connector + + Ctn Engine Config Set Value 0 log_level_checks trace + + Ctn Config Broker module + + Ctn Clear Retention + + ${start} Get Current Date + Ctn Start Engine + + # Let's wait for the otel server start + ${content} Create List server listen on 0.0.0.0:1443 + ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 10 + Should Be True ${result} "server listen on 0.0.0.0:1443" should be available. + Sleep 1 + ${telegraf_conf_response} GET + ... url=http://localhost:1443/engine?host=host_1&host=host_2&host=host_3 + + Should Be Equal As Strings ${telegraf_conf_response.reason} OK no response received or error response + + Should Be Equal As Strings ${telegraf_conf_response.reason} OK no response received or error response + ${content_compare_result} Ctn Compare String With File + ... ${telegraf_conf_response.text} + ... resources/opentelemetry/telegraf.conf + + Should Be True + ... ${content_compare_result} + ... unexpected telegraf server response: ${telegraf_conf_response.text} + + +*** Keywords *** +Ctn Create Otl Request + [Documentation] create an otl request with nagios telegraf style + [Arguments] ${state} ${host} ${service}= + ${state_attrib} Create Dictionary host=${host} service=${service} + ${rta_attrib} Create Dictionary host=${host} service=${service} perfdata=rta unit=ms + ${rtmax_attrib} Create Dictionary host=${host} service=${service} perfdata=rtmax unit=ms + ${pl_attrib} Create Dictionary host=${host} service=${service} perfdata=pl unit=% + + # state + ${state_metric} Ctn Create Otl Metric check_icmp_state 1 ${state_attrib} ${state} + # value + ${value_metric} Ctn Create Otl Metric check_icmp_value 1 ${rta_attrib} ${0.022} + Ctn Add Data Point To Metric ${value_metric} ${rtmax_attrib} ${0.071} + Ctn Add Data Point To Metric ${value_metric} ${pl_attrib} ${0.001} + + ${critical_gt_metric} Ctn Create Otl Metric check_icmp_critical_gt 1 ${rta_attrib} ${500} + Ctn Add Data Point To Metric ${critical_gt_metric} ${pl_attrib} ${80} + ${critical_lt_metric} Ctn Create Otl Metric check_icmp_critical_lt 1 ${rta_attrib} ${1} + Ctn Add Data Point To Metric ${critical_gt_metric} ${pl_attrib} ${0.00001} + + ${metrics_list} Create List + ... ${state_metric} + ... ${value_metric} + ... ${critical_gt_metric} + ... ${critical_lt_metric} + + ${scope_attrib} Create Dictionary + ${scope_metric} Ctn Create Otl Scope Metrics ${scope_attrib} ${metrics_list} + + ${scope_metrics_list} Create List ${scope_metric} + + ${resource_attrib} Create Dictionary + ${resource_metrics} Ctn Create Otl Resource Metrics ${resource_attrib} ${scope_metrics_list} + ${resources_list} Create List ${resource_metrics} + + RETURN ${resources_list} diff --git a/tests/resources/Common.py b/tests/resources/Common.py index 6db8270fd95..f906646bdfe 100644 --- a/tests/resources/Common.py +++ b/tests/resources/Common.py @@ -24,9 +24,12 @@ import re import os from pwd import getpwnam +from google.protobuf.json_format import MessageToJson import time import json import psutil +import random +import string from dateutil import parser from datetime import datetime import pymysql.cursors @@ -985,6 +988,44 @@ def ctn_check_service_check_with_timeout(hostname: str, service_desc: str, time return False +def ctn_check_service_check_status_with_timeout(hostname: str, service_desc: str, timeout: int, min_last_check: int, state: int, output: str): + """ + check_service_check_status_with_timeout + + check if service checks infos have been updated + + Args: + host_name: + service_desc: + timeout: time to wait expected check in seconds + min_last_check: time point after last_check will be accepted + state: expected service state + output: expected output + """ + limit = time.time() + timeout + while time.time() < limit: + connection = pymysql.connect(host=DB_HOST, + user=DB_USER, + password=DB_PASS, + autocommit=True, + database=DB_NAME_STORAGE, + charset='utf8mb4', + cursorclass=pymysql.cursors.DictCursor) + + with connection: + with connection.cursor() as cursor: + cursor.execute( + f"SELECT s.last_check, s.state, s.output FROM services s LEFT JOIN hosts h ON s.host_id=h.host_id WHERE s.description=\"{service_desc}\" AND h.name=\"{hostname}\"") + result = cursor.fetchall() + if len(result) > 0: + logger.console( + f"last_check={result[0]['last_check']} state={result[0]['state']} output={result[0]['output']} ") + if result[0]['last_check'] is not None and result[0]['last_check'] >= min_last_check and output in result[0]['output'] and result[0]['state'] == state: + return True + time.sleep(1) + return False + + def ctn_check_host_check_with_timeout(hostname: str, timeout: int, command_line: str): limit = time.time() + timeout while time.time() < limit: @@ -1009,6 +1050,42 @@ def ctn_check_host_check_with_timeout(hostname: str, timeout: int, command_line: time.sleep(1) return False +def ctn_check_host_check_status_with_timeout(hostname: str, timeout: int, min_last_check: int, state: int, output: str): + """ + ctn_check_host_check_status_with_timeout + + check if host checks infos have been updated + + Args: + hostname: + timeout: time to wait expected check in seconds + min_last_check: time point after last_check will be accepted + state: expected host state + output: expected output + """ + limit = time.time() + timeout + while time.time() < limit: + connection = pymysql.connect(host=DB_HOST, + user=DB_USER, + password=DB_PASS, + autocommit=True, + database=DB_NAME_STORAGE, + charset='utf8mb4', + cursorclass=pymysql.cursors.DictCursor) + + with connection: + with connection.cursor() as cursor: + cursor.execute( + f"SELECT last_check, state, output FROM hosts WHERE name='{hostname}'") + result = cursor.fetchall() + if len(result) > 0: + logger.console( + f"last_check={result[0]['last_check']} state={result[0]['state']} output={result[0]['output']} ") + if result[0]['last_check'] is not None and result[0]['last_check'] >= min_last_check and output in result[0]['output'] and result[0]['state'] == state: + return True + time.sleep(1) + return False + def ctn_show_downtimes(): connection = pymysql.connect(host=DB_HOST, @@ -1670,3 +1747,108 @@ def exchange(self, request_iterator, context): server.add_secure_port("0.0.0.0:5669", creds) server.start() return server + + +def create_random_string(length:int): + """ + create_random_string + + create a string with random char + Args: + length output string length + Returns: a string + """ + letters = string.ascii_lowercase + return ''.join(random.choice(letters) for i in range(length)) + + +def ctn_create_random_dictionary(nb_entries: int): + """ + create_random_dictionary + + create a dictionary with random keys and random string values + + Args: + nb_entries dictionary size + Returns: a dictionary + """ + dict_ret = {} + for ii in range(nb_entries): + dict_ret[create_random_string(10)] = create_random_string(10) + + return dict_ret; + + +def ctn_extract_event_from_lua_log(file_path:str, field_name: str): + """ + extract_event_from_lua_log + + extract a json object from a lua log file + Example: Wed Feb 7 15:30:11 2024: INFO: {"_type":196621, "category":3, "element":13, "resource_metrics":{} + + Args: + file1: The first file to compare. + file2: The second file to compare. + + Returns: True if they have the same content, False otherwise. + """ + + with open(file1, "r") as f1: + content1 = f1.readlines() + with open(file2, "r") as f2: + content2 = f2.readlines() + r = re.compile(r"(.*) 0x[0-9a-f]+") + + def replace_ptr(line): + m = r.match(line) + if m: + return m.group(1) + else: + return line + + content1 = list(map(replace_ptr, content1)) + content2 = list(map(replace_ptr, content2)) + + if len(content1) != len(content2): + return False + for i in range(len(content1)): + if content1[i] != content2[i]: + logger.console( + f"Files are different at line {i + 1}: first => << {content1[i].strip()} >> and second => << {content2[i].strip()} >>") + return False + return True + + + +def ctn_protobuf_to_json(protobuf_obj): + """ + protobuf_to_json + + Convert a protobuf object to json + it replaces uppercase letters in keys by _ + """ + converted = MessageToJson(protobuf_obj) + return json.loads(converted) + + +def ctn_compare_string_with_file(string_to_compare:str, file_path:str): + """ + ctn_compare_string_with_file + + compare a multiline string with a file content + Args: + string_to_compare: multiline string to compare + file_path: path of the file to compare + + Returns: True if contents are identical + """ + str_lines = string_to_compare.splitlines(keepends=True) + with open(file_path) as f: + file_lines = f.readlines() + if len(str_lines) != len(file_lines): + return False + for str_line, file_line in zip(str_lines, file_lines): + if str_line != file_line: + return False + return True + diff --git a/tests/resources/Engine.py b/tests/resources/Engine.py index 39e63e33ead..b95617aa091 100755 --- a/tests/resources/Engine.py +++ b/tests/resources/Engine.py @@ -26,6 +26,9 @@ from google.protobuf.timestamp_pb2 import Timestamp import engine_pb2 import engine_pb2_grpc +import opentelemetry.proto.collector.metrics.v1.metrics_service_pb2 +import opentelemetry.proto.collector.metrics.v1.metrics_service_pb2_grpc +import opentelemetry.proto.metrics.v1.metrics_pb2 from array import array from dateutil import parser import datetime @@ -173,6 +176,7 @@ def _create_centengine(self, id: int, debug_level=0): "log_level_macros=info\n" "log_level_process=info\n" "log_level_runtime=info\n" + "log_level_otl=trace\n" "log_flush_period=0\n" "soft_state_dependencies=0\n" "obsess_over_services=0\n" @@ -3090,6 +3094,27 @@ def ctn_grep_retention(poller: int, pattern: str): return Common.ctn_grep("{}/log/centreon-engine/config{}/retention.dat".format(VAR_ROOT, poller), pattern) +def ctn_config_add_otl_connector(poller: int, connector_name: str, command_line:str): + """ + ctn_config_add_otl_connector + + add a connector entry to connectors.cfg + + Args: + poller: poller index + connector_name: + command_line: + """ + + with open(f"{CONF_DIR}/config{poller}/connectors.cfg", "a") as f: + f.write(f""" +define connector {{ + connector_name {connector_name} + connector_line {command_line} +}} +""") + + def ctn_modify_retention_dat(poller, host, service, key, value): """ Modify a parameter of a service in the retention.dat file. @@ -3369,3 +3394,206 @@ def ctn_create_single_day_time_period(idx: int, time_period_name: str, date, min {my_date.date().isoformat()} {begin.strftime("%H:%M")}-{end.time().strftime("%H:%M")} }} """) + + +def ctn_add_otl_server_module(idx: int, otl_server_config_json_content: str): + """! + add a new broker_module line to centengine.cfg and create otl_server config file + @param idx index ofthe poller usually 0 + @param otl_server_config_json_content json content of the otl configuration file + """ + filename = f"{ETC_ROOT}/centreon-engine/config{idx}/centengine.cfg" + otl_server_config_path = f"{ETC_ROOT}/centreon-engine/config{idx}/otl_server.json" + with open(filename, "a+") as f: + f.write(f"broker_module=/usr/lib64/centreon-engine/libopentelemetry.so {otl_server_config_path}") + + with open(otl_server_config_path, "w") as f: + f.write(otl_server_config_json_content) + +def ctn_randomword(length): + letters = string.ascii_lowercase + return ''.join(random.choice(letters) for i in range(length)) + + +# Example of open telemetry request +# { +# "resourceMetrics": [ +# { +# "resource": { +# "attributes": [ +# { +# "key": "service.name", +# "value": { +# "stringValue": "demo_telegraf" +# } +# } +# ] +# }, +# "scopeMetrics": [ +# { +# "scope": { +# "attributes": [ +# { +# "key": "host", +# "value": { +# "stringValue": "d4854a00b171" +# } +# } +# ] +# }, +# "metrics": [ +# { +# "name": "swap_used_percent", +# "gauge": { +# "dataPoints": [ +# { +# "timeUnixNano": "1706864500000000000", +# "asDouble": 99.999809264772921, +# "attributes": [ +# { +# "key": "host", +# "value": { +# "stringValue": "d4854a00b171" +# } +# } +# ] +# } +# ] +# } +# }, +# { +# "name": "swap_total", +# "gauge": { +# "dataPoints": [ +# { +# "timeUnixNano": "1706864500000000000", +# "asInt": "2147479552", +# "attributes": [ +# { +# "key": "host", +# "value": { +# "stringValue": "d4854a00b171" +# } +# } +# ] +# } +# ] +# } +# } +# ] +# } +# ] +# } +# ] +# } + + +def ctn_add_data_point_to_metric(metric, attrib:dict, metric_value = None): + """ + + ctn_add_data_point_to_metric + + add a data point to metric + Args: + metric: metric + attrib: key =>values to add in datapoint attributes + metric_value (optional) value of metric, random if not given + + """ + data_point = metric.gauge.data_points.add() + data_point.time_unix_nano = int(time.time()) + if metric_value is not None: + data_point.as_double = metric_value + else: + data_point.as_double = random.random() + for key, value in attrib.items(): + attr = data_point.attributes.add() + attr.key = key + attr.value.string_value = value + + +def ctn_create_otl_metric(name:str, nb_datapoints:int, attrib:dict, metric_value = None): + """ + + create_otl_metric + + create a Metric + Args: + name: metric name + nb_datapoints: number of datapoints added to the metric + attrib: key =>values to add in datapoint attributes + metric_value (optional) value of metric, random if not given + Returns: opentelemetry.proto.metrics.v1.Metric object + """ + metric = opentelemetry.proto.metrics.v1.metrics_pb2.Metric() + metric.name = name + for i in range(nb_datapoints): + ctn_add_data_point_to_metric(metric, attrib, metric_value) + return metric + + +def ctn_create_otl_scope_metrics(scope_attr: dict, metrics: list): + """ + create_otl_scope_metrics + + create a ScopeMetrics + Args: + scope_attr: attributes to add in scope object + metrics: metrics to add in metrics array + Returns: opentelemetry.proto.metrics.v1.metrics_pb2.ScopeMetrics object + """ + scope_metrics = opentelemetry.proto.metrics.v1.metrics_pb2.ScopeMetrics() + for key, value in scope_attr.items(): + attr = scope_metrics.scope.attributes.add() + attr.key = key + attr.value.string_value = value + for metric in metrics: + to_fill = scope_metrics.metrics.add() + to_fill.CopyFrom(metric) + return scope_metrics + +def ctn_create_otl_resource_metrics(resource_attr: dict, scope_metrics: list): + """ + create_otl_resource_metrics + + create a ResourceMetrics + Args: + resource_attr: attributes to add in resource object + scope_metrics: metrics to add in scopeMetrics array + Returns: opentelemetry.proto.metrics.v1.metrics_pb2.ResourceMetrics object + """ + resource_metrics = opentelemetry.proto.metrics.v1.metrics_pb2.ResourceMetrics() + for key, value in resource_attr.items(): + attr = resource_metrics.resource.attributes.add() + attr.key = key + attr.value.string_value = value + for scope_metric in scope_metrics: + to_fill = resource_metrics.scope_metrics.add() + to_fill.CopyFrom(scope_metric) + return resource_metrics + + +def ctn_send_otl_to_engine(port: int, resource_metrics: list): + """ + send_otl_to_engine + + send an otl request to engine otl server + + Args: + port: port to connect to engine + resource_metrics: resource_metrics to add to grpc message + """ + with grpc.insecure_channel(f"127.0.0.1:{port}") as channel: + # same for engine and broker + stub = opentelemetry.proto.collector.metrics.v1.metrics_service_pb2_grpc.MetricsServiceStub(channel) + try: + request = opentelemetry.proto.collector.metrics.v1.metrics_service_pb2.ExportMetricsServiceRequest() + for res_metric in resource_metrics: + to_fill = request.resource_metrics.add() + to_fill.CopyFrom(res_metric) + + return stub.Export(request) + except: + logger.console("gRPC server not ready") + + diff --git a/tests/resources/import.resource b/tests/resources/import.resource index 12cf0daddfd..3114d95ce4a 100644 --- a/tests/resources/import.resource +++ b/tests/resources/import.resource @@ -9,6 +9,7 @@ Library Collections Library DatabaseLibrary Library Examples Library HttpCtrl.Server +Library RequestsLibrary # Creation Resource resources.resource # Python Library diff --git a/tests/resources/opentelemetry/telegraf.conf b/tests/resources/opentelemetry/telegraf.conf new file mode 100644 index 00000000000..2282ce60fab --- /dev/null +++ b/tests/resources/opentelemetry/telegraf.conf @@ -0,0 +1,54 @@ +# Centreon telegraf configuration +# This telegraf configuration is generated by centreon centengine +[agent] + ## Default data collection interval for all inputs + interval = "60s" + +[[outputs.opentelemetry]] + service_address = "127.0.0.1:4317" + + +[[inputs.exec]] + name_override = "otel_check_icmp_host_1" + commands = ["/usr/lib/nagios/plugins/check_icmp 127.0.0.10"] + data_format = "nagios" + [inputs.exec.tags] + host = "host_1" + service = "" + + +[[inputs.exec]] + name_override = "otel_check_icmp_serv_1" + commands = ["/usr/lib/nagios/plugins/check_icmp 127.0.0.1"] + data_format = "nagios" + [inputs.exec.tags] + host = "host_1" + service = "service_1" + + +[[inputs.exec]] + name_override = "otel_check_icmp_serv_2" + commands = ["/usr/lib/nagios/plugins/check_icmp 127.0.0.2"] + data_format = "nagios" + [inputs.exec.tags] + host = "host_1" + service = "service_2" + + +[[inputs.exec]] + name_override = "otel_check_icmp_host_2" + commands = ["/usr/lib/nagios/plugins/check_icmp 127.0.0.20"] + data_format = "nagios" + [inputs.exec.tags] + host = "host_2" + service = "" + + +[[inputs.exec]] + name_override = "otel_check_icmp_serv_5" + commands = ["/usr/lib/nagios/plugins/check_icmp 127.0.0.5"] + data_format = "nagios" + [inputs.exec.tags] + host = "host_3" + service = "service_5" + diff --git a/tests/resources/resources.resource b/tests/resources/resources.resource index 23a25dd7eb1..87575a8ce96 100644 --- a/tests/resources/resources.resource +++ b/tests/resources/resources.resource @@ -298,6 +298,7 @@ Ctn Dump Process ${gdb_output} Catenate SEPARATOR= ${failDir} /core- ${name} .txt # Log To Console Creation of core ${output}.${pid} to debug Run Process gcore -o ${output} ${pid} + Log To Console Creation of core ${gdb_output} Run Process ... gdb ... -batch diff --git a/tests/resources/scripts/dump-otl-event.lua b/tests/resources/scripts/dump-otl-event.lua new file mode 100644 index 00000000000..f7f72d1ecb0 --- /dev/null +++ b/tests/resources/scripts/dump-otl-event.lua @@ -0,0 +1,13 @@ +broker_api_version = 2 + +function init(conf) + broker_log:set_parameters(3, "/tmp/lua.log") + broker_log:info(0, "Starting test.lua") +end + +function write(e) + if e._type == 196621 then + broker_log:info(0, broker.json_encode(e)) + end + return true +end \ No newline at end of file diff --git a/tests/update-doc.py b/tests/update-doc.py index 0e058e83913..21a220a9222 100755 --- a/tests/update-doc.py +++ b/tests/update-doc.py @@ -117,7 +117,7 @@ def parse_dir(d): On other rpm based distributions, you can try the following commands to initialize your robot tests: ``` -pip3 install -U robotframework robotframework-databaselibrary robotframework-httpctrl robotframework-examples pymysql +pip3 install -U robotframework robotframework-databaselibrary robotframework-httpctrl robotframework-examples pymysql robotframework-requests yum install python3-devel -y From 80fed91f9149fd30d99b6435dcd12264bb3b2263 Mon Sep 17 00:00:00 2001 From: David Boucher Date: Thu, 6 Jun 2024 14:40:55 +0200 Subject: [PATCH 28/60] =?UTF-8?q?enh(engine/configuration):=20use=20of=20m?= =?UTF-8?q?isc::string=20removed=20from=20configura=E2=80=A6=20(#1399)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit REFS: MON-85674 --- clib/inc/com/centreon/misc/stringifier.hh | 36 ++++---- .../com/centreon/common/rapidjson_helper.hh | 3 +- .../com/centreon/engine/commands/command.hh | 11 +-- .../engine/configuration/applier/command.hh | 2 +- .../centreon/engine/configuration/object.hh | 77 ++++++++++------- .../centreon/engine/configuration/state.hh | 7 +- .../engine/configuration/timeperiod.hh | 4 +- engine/inc/com/centreon/engine/opt.hh | 77 +++++++++-------- engine/src/configuration/anomalydetection.cc | 72 +++++++--------- engine/src/configuration/contact.cc | 53 ++++++------ engine/src/configuration/group.cc | 78 ++++++++++++++++- engine/src/configuration/host.cc | 79 ++++++++--------- engine/src/configuration/hostdependency.cc | 82 ++++++++---------- engine/src/configuration/hostescalation.cc | 19 ++--- engine/src/configuration/object.cc | 3 +- engine/src/configuration/parser.cc | 85 +++++++++++++------ engine/src/configuration/service.cc | 70 +++++++-------- engine/src/configuration/servicedependency.cc | 52 +++++------- engine/src/configuration/serviceescalation.cc | 71 +++++++--------- engine/src/configuration/state.cc | 60 +++++++++---- engine/src/configuration/timeperiod.cc | 53 ++++++------ engine/src/macros/grab_value.cc | 2 +- .../get_next_valid_time/exceptions_test.cc | 33 +++---- tests/bam/bam_pb.robot | 12 ++- tests/broker-engine/notifications.robot | 2 +- tests/resources/resources.resource | 5 +- 26 files changed, 566 insertions(+), 482 deletions(-) diff --git a/clib/inc/com/centreon/misc/stringifier.hh b/clib/inc/com/centreon/misc/stringifier.hh index 5947d5bff5e..ede3b8bc469 100644 --- a/clib/inc/com/centreon/misc/stringifier.hh +++ b/clib/inc/com/centreon/misc/stringifier.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2011-2013 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2011-2013, 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CC_MISC_STRINGIFIER_HH #define CC_MISC_STRINGIFIER_HH @@ -76,6 +76,6 @@ class stringifier { }; } // namespace misc -} +} // namespace com::centreon #endif // !CC_MISC_STRINGIFIER_HH diff --git a/common/inc/com/centreon/common/rapidjson_helper.hh b/common/inc/com/centreon/common/rapidjson_helper.hh index a7039dfeea5..5cecd1ba14d 100644 --- a/common/inc/com/centreon/common/rapidjson_helper.hh +++ b/common/inc/com/centreon/common/rapidjson_helper.hh @@ -316,7 +316,8 @@ class rapidjson_helper { * @return value_type */ template -inline value_type rapidjson_helper::get(const char* field_name) { +inline value_type rapidjson_helper::get(const char* field_name + [[maybe_unused]]) { class not_convertible {}; static_assert(std::is_convertible::value); } diff --git a/engine/inc/com/centreon/engine/commands/command.hh b/engine/inc/com/centreon/engine/commands/command.hh index 11487afb684..60f39ce058c 100644 --- a/engine/inc/com/centreon/engine/commands/command.hh +++ b/engine/inc/com/centreon/engine/commands/command.hh @@ -124,8 +124,9 @@ class command { * @param host * @param service_description empty for host command */ - virtual void register_host_serv(const std::string& /*host*/, - const std::string& /*service_description*/){}; + virtual void register_host_serv(const std::string& host [[maybe_unused]], + const std::string& service_description + [[maybe_unused]]) {} /** * @brief Remove an entry for host serv list shared between this connector and @@ -134,9 +135,9 @@ class command { * @param host * @param service_description empty for host command */ - virtual void unregister_host_serv( - const std::string& /*host*/, - const std::string& /*service_description*/){}; + virtual void unregister_host_serv(const std::string& host [[maybe_unused]], + const std::string& service_description + [[maybe_unused]]) {} template void add_caller_group(caller_iterator begin, caller_iterator end); diff --git a/engine/inc/com/centreon/engine/configuration/applier/command.hh b/engine/inc/com/centreon/engine/configuration/applier/command.hh index 1f07e67c9fe..9049e571dad 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/command.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/command.hh @@ -40,7 +40,7 @@ class command { command(command const&) = delete; command& operator=(command const&) = delete; - ~command() throw(); + ~command() noexcept; void add_object(configuration::command const& obj); void expand_objects(configuration::state& s); diff --git a/engine/inc/com/centreon/engine/configuration/object.hh b/engine/inc/com/centreon/engine/configuration/object.hh index 4f098d2e457..4f0e00390df 100644 --- a/engine/inc/com/centreon/engine/configuration/object.hh +++ b/engine/inc/com/centreon/engine/configuration/object.hh @@ -1,27 +1,25 @@ -/* -** Copyright 2011-2015 Merethis -** Copyright 2016-2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2011-2015 Merethis + * Copyright 2016-2022 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCE_CONFIGURATION_OBJECT_HH #define CCE_CONFIGURATION_OBJECT_HH -#include "com/centreon/engine/string.hh" - typedef std::list list_string; typedef std::set set_string; @@ -60,7 +58,7 @@ class object { virtual void check_validity() const = 0; static std::shared_ptr create(std::string const& type_name); virtual void merge(object const& obj) = 0; - std::string const& name() const noexcept; + const std::string& name() const noexcept; virtual bool parse(char const* key, char const* value); virtual bool parse(std::string const& line); void resolve_template( @@ -72,24 +70,43 @@ class object { protected: struct setters { char const* name; - bool (*func)(object&, char const*); + bool (*func)(object&, const char*); }; template struct setter { - static bool generic(T& obj, char const* value) { + static bool generic(T& obj, const char* value) { U val(0); - if (!string::to(value, val)) - return (false); - return ((obj.*ptr)(val)); + if constexpr (std::is_same_v) { + if (absl::SimpleAtob(value, &val)) + return (obj.*ptr)(val); + else + return false; + } else if constexpr (std::is_integral::value) { + if (absl::SimpleAtoi(value, &val)) + return (obj.*ptr)(val); + else + return false; + } else if constexpr (std::is_same_v) { + if (absl::SimpleAtof(value, &val)) + return (obj.*ptr)(val); + else + return false; + } else if constexpr (std::is_same_v) { + if (absl::SimpleAtod(value, &val)) + return (obj.*ptr)(val); + else + return false; + } else { + static_assert(std::is_integral_v || std::is_floating_point_v || + std::is_same_v); + } } }; template struct setter { - static bool generic(T& obj, char const* value) { - return ((obj.*ptr)(value)); - } + static bool generic(T& obj, const char* value) { return (obj.*ptr)(value); } }; bool _set_name(std::string const& value); @@ -109,7 +126,7 @@ typedef std::list list_object; typedef std::unordered_map map_object; } // namespace configuration -} +} // namespace com::centreon::engine #define MRG_TAB(prop) \ do { \ diff --git a/engine/inc/com/centreon/engine/configuration/state.hh b/engine/inc/com/centreon/engine/configuration/state.hh index 5c9f8979d27..5fa107fb945 100644 --- a/engine/inc/com/centreon/engine/configuration/state.hh +++ b/engine/inc/com/centreon/engine/configuration/state.hh @@ -16,7 +16,6 @@ * For more information : contact@centreon.com */ - #ifndef CCE_CONFIGURATION_STATE_HH #define CCE_CONFIGURATION_STATE_HH @@ -181,8 +180,8 @@ class state { void date_format(date_type value); std::string const& debug_file() const noexcept; void debug_file(std::string const& value); - uint64_t debug_level() const noexcept; - void debug_level(uint64_t value); + int64_t debug_level() const noexcept; + void debug_level(int64_t value); unsigned int debug_verbosity() const noexcept; void debug_verbosity(unsigned int value); bool enable_environment_macros() const noexcept; @@ -533,7 +532,7 @@ class state { set_contact _contacts; date_type _date_format; std::string _debug_file; - uint64_t _debug_level; + int64_t _debug_level; unsigned int _debug_verbosity; bool _enable_environment_macros; bool _enable_event_handlers; diff --git a/engine/inc/com/centreon/engine/configuration/timeperiod.hh b/engine/inc/com/centreon/engine/configuration/timeperiod.hh index b4aeb6ccfa9..01a73e42bad 100644 --- a/engine/inc/com/centreon/engine/configuration/timeperiod.hh +++ b/engine/inc/com/centreon/engine/configuration/timeperiod.hh @@ -64,7 +64,7 @@ class timeperiod : public object { bool _add_week_day(std::string const& key, std::string const& value); static bool _build_timeranges(std::string const& line, timerange_list& timeranges); - static bool _build_time_t(std::string const& time_str, unsigned long& ret); + static bool _build_time_t(std::string_view time_str, unsigned long& ret); static bool _has_similar_daterange(std::list const& lst, daterange const& range) throw(); static bool _get_month_id(std::string const& name, unsigned int& id); @@ -85,6 +85,6 @@ typedef std::shared_ptr timeperiod_ptr; typedef std::set set_timeperiod; } // namespace configuration -} +} // namespace com::centreon::engine #endif // !CCE_CONFIGURATION_TIMEPERIOD_HH diff --git a/engine/inc/com/centreon/engine/opt.hh b/engine/inc/com/centreon/engine/opt.hh index d9648a220fe..e6504fafdb7 100644 --- a/engine/inc/com/centreon/engine/opt.hh +++ b/engine/inc/com/centreon/engine/opt.hh @@ -1,22 +1,22 @@ -/* -** Copyright 2011-2013 Merethis -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2013 Merethis + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCE_OPT_HH #define CCE_OPT_HH @@ -24,6 +24,9 @@ namespace com::centreon::engine { template class opt { + T _data; + bool _is_set; + public: opt() : _data{}, _is_set(false) {} opt(T const& right) : _data(right), _is_set(false) {} @@ -38,24 +41,24 @@ class opt { _is_set = right._is_set; return *this; } - bool operator==(opt const& right) const throw() { - return (_data == right._data); + bool operator==(opt const& right) const noexcept { + return _data == right._data; } - bool operator!=(opt const& right) const throw() { - return (!operator==(right)); + bool operator!=(opt const& right) const noexcept { + return !operator==(right); } - bool operator<(opt const& right) const throw() { - return (_data < right._data); + bool operator<(opt const& right) const noexcept { + return _data < right._data; } - operator T const &() const throw() { return (_data); } - T& operator*() throw() { return (_data); } - T const& operator*() const throw() { return (_data); } - T* operator->() throw() { return (&_data); } - T const* operator->() const throw() { return (&_data); } - T& get() throw() { return (_data); } - T const& get() const throw() { return (_data); } - bool is_set() const throw() { return (_is_set); } - void reset() throw() { _is_set = false; } + operator T const&() const noexcept { return (_data); } + T& operator*() noexcept { return (_data); } + T const& operator*() const noexcept { return (_data); } + T* operator->() noexcept { return (&_data); } + T const* operator->() const noexcept { return (&_data); } + T& get() noexcept { return (_data); } + T const& get() const noexcept { return (_data); } + bool is_set() const noexcept { return (_is_set); } + void reset() noexcept { _is_set = false; } void set(T const& right) { _data = right; _is_set = true; @@ -64,12 +67,8 @@ class opt { _data = right._data; _is_set = right._is_set; } - - private: - T _data; - bool _is_set; }; -} +} // namespace com::centreon::engine #endif // !CCE_OPT_HH diff --git a/engine/src/configuration/anomalydetection.cc b/engine/src/configuration/anomalydetection.cc index 3079186deb5..660ebcd2cb1 100644 --- a/engine/src/configuration/anomalydetection.cc +++ b/engine/src/configuration/anomalydetection.cc @@ -26,7 +26,6 @@ #include "com/centreon/engine/globals.hh" #include "com/centreon/engine/host.hh" #include "com/centreon/engine/logging/logger.hh" -#include "com/centreon/engine/string.hh" extern int config_warnings; extern int config_errors; @@ -1365,7 +1364,6 @@ unsigned short anomalydetection::notification_options() const noexcept { */ void anomalydetection::notification_period(std::string const& period) { _notification_period = period; - return; } /** @@ -1588,7 +1586,7 @@ bool anomalydetection::set_acknowledgement_timeout(int value) { * * @return True on success, otherwise false. */ -bool anomalydetection::_set_action_url(std::string const& value) { +bool anomalydetection::_set_action_url(const std::string& value) { _action_url = value; return true; } @@ -1813,22 +1811,20 @@ bool anomalydetection::_set_flap_detection_enabled(bool value) { */ bool anomalydetection::_set_flap_detection_options(std::string const& value) { unsigned short options(none); - std::list values; - string::split(value, values, ','); - for (std::list::iterator it(values.begin()), end(values.end()); - it != end; ++it) { - string::trim(*it); - if (*it == "o" || *it == "ok") + auto values = absl::StrSplit(value, ','); + for (auto& val : values) { + auto v = absl::StripAsciiWhitespace(val); + if (v == "o" || v == "ok") options |= ok; - else if (*it == "w" || *it == "warning") + else if (v == "w" || v == "warning") options |= warning; - else if (*it == "u" || *it == "unknown") + else if (v == "u" || v == "unknown") options |= unknown; - else if (*it == "c" || *it == "critical") + else if (v == "c" || v == "critical") options |= critical; - else if (*it == "n" || *it == "none") + else if (v == "n" || v == "none") options = none; - else if (*it == "a" || *it == "all") + else if (v == "a" || v == "all") options = ok | warning | unknown | critical; else return false; @@ -1905,8 +1901,8 @@ bool anomalydetection::_set_icon_image_alt(std::string const& value) { * @return True on success, otherwise false. */ bool anomalydetection::_set_initial_state(std::string const& value) { - std::string data(value); - string::trim(data); + std::string_view data(value); + data = absl::StripAsciiWhitespace(data); if (data == "o" || data == "ok") _initial_state = engine::service::state_ok; else if (data == "w" || data == "warning") @@ -2003,26 +1999,24 @@ bool anomalydetection::_set_notifications_enabled(bool value) { */ bool anomalydetection::_set_notification_options(std::string const& value) { unsigned short options(none); - std::list values; - string::split(value, values, ','); - for (std::list::iterator it(values.begin()), end(values.end()); - it != end; ++it) { - string::trim(*it); - if (*it == "u" || *it == "unknown") + auto values = absl::StrSplit(value, ','); + for (auto& val : values) { + auto v = absl::StripAsciiWhitespace(val); + if (v == "u" || v == "unknown") options |= unknown; - else if (*it == "w" || *it == "warning") + else if (v == "w" || v == "warning") options |= warning; - else if (*it == "c" || *it == "critical") + else if (v == "c" || v == "critical") options |= critical; - else if (*it == "r" || *it == "recovery") + else if (v == "r" || v == "recovery") options |= ok; - else if (*it == "f" || *it == "flapping") + else if (v == "f" || v == "flapping") options |= flapping; - else if (*it == "s" || *it == "downtime") + else if (v == "s" || v == "downtime") options |= downtime; - else if (*it == "n" || *it == "none") + else if (v == "n" || v == "none") options = none; - else if (*it == "a" || *it == "all") + else if (v == "a" || v == "all") options = unknown | warning | critical | ok | flapping | downtime; else return false; @@ -2217,22 +2211,20 @@ bool anomalydetection::set_dependent_service_id(uint64_t value) { */ bool anomalydetection::_set_stalking_options(std::string const& value) { unsigned short options(none); - std::list values; - string::split(value, values, ','); - for (std::list::iterator it(values.begin()), end(values.end()); - it != end; ++it) { - string::trim(*it); - if (*it == "o" || *it == "ok") + auto values = absl::StrSplit(value, ','); + for (auto& val : values) { + auto v = absl::StripAsciiWhitespace(val); + if (v == "o" || v == "ok") options |= ok; - else if (*it == "w" || *it == "warning") + else if (v == "w" || v == "warning") options |= warning; - else if (*it == "u" || *it == "unknown") + else if (v == "u" || v == "unknown") options |= unknown; - else if (*it == "c" || *it == "critical") + else if (v == "c" || v == "critical") options |= critical; - else if (*it == "n" || *it == "none") + else if (v == "n" || v == "none") options = none; - else if (*it == "a" || *it == "all") + else if (v == "a" || v == "all") options = ok | warning | unknown | critical; else return false; diff --git a/engine/src/configuration/contact.cc b/engine/src/configuration/contact.cc index 874e74b4fec..381839ab1e7 100644 --- a/engine/src/configuration/contact.cc +++ b/engine/src/configuration/contact.cc @@ -21,7 +21,6 @@ #include "com/centreon/engine/configuration/host.hh" #include "com/centreon/engine/configuration/service.hh" #include "com/centreon/engine/exceptions/error.hh" -#include "com/centreon/engine/string.hh" using namespace com::centreon; using namespace com::centreon::engine; @@ -504,7 +503,9 @@ std::string const& contact::timezone() const noexcept { */ bool contact::_set_address(const std::string& key, const std::string& value) { unsigned int id; - if (!string::to(key.c_str(), id) || (id < 1) || (id > MAX_ADDRESSES)) + if (!absl::SimpleAtoi(key, &id)) + return false; + if (id < 1 || id > MAX_ADDRESSES) return false; _address[id - 1] = value; return true; @@ -602,25 +603,23 @@ bool contact::_set_host_notification_commands(std::string const& value) { * @return True on success, otherwise false. */ bool contact::_set_host_notification_options(std::string const& value) { - unsigned short options(host::none); - std::list values; - string::split(value, values, ','); - for (std::list::iterator it(values.begin()), end(values.end()); - it != end; ++it) { - string::trim(*it); - if (*it == "d" || *it == "down") + unsigned short options = host::none; + auto values = absl::StrSplit(value, ','); + for (auto it = values.begin(), end = values.end(); it != end; ++it) { + std::string_view v = absl::StripAsciiWhitespace(*it); + if (v == "d" || v == "down") options |= host::down; - else if (*it == "u" || *it == "unreachable") + else if (v == "u" || v == "unreachable") options |= host::unreachable; - else if (*it == "r" || *it == "recovery") + else if (v == "r" || v == "recovery") options |= host::up; - else if (*it == "f" || *it == "flapping") + else if (v == "f" || v == "flapping") options |= host::flapping; - else if (*it == "s" || *it == "downtime") + else if (v == "s" || v == "downtime") options |= host::downtime; - else if (*it == "n" || *it == "none") + else if (v == "n" || v == "none") options = host::none; - else if (*it == "a" || *it == "all") + else if (v == "a" || v == "all") options = host::down | host::unreachable | host::up | host::flapping | host::downtime; else @@ -699,26 +698,24 @@ bool contact::_set_service_notification_commands(std::string const& value) { */ bool contact::_set_service_notification_options(std::string const& value) { unsigned short options(service::none); - std::list values; - string::split(value, values, ','); - for (std::list::iterator it(values.begin()), end(values.end()); - it != end; ++it) { - string::trim(*it); - if (*it == "u" || *it == "unknown") + auto values = absl::StrSplit(value, ','); + for (auto it = values.begin(), end = values.end(); it != end; ++it) { + auto v = absl::StripAsciiWhitespace(*it); + if (v == "u" || v == "unknown") options |= service::unknown; - else if (*it == "w" || *it == "warning") + else if (v == "w" || v == "warning") options |= service::warning; - else if (*it == "c" || *it == "critical") + else if (v == "c" || v == "critical") options |= service::critical; - else if (*it == "r" || *it == "recovery") + else if (v == "r" || v == "recovery") options |= service::ok; - else if (*it == "f" || *it == "flapping") + else if (v == "f" || v == "flapping") options |= service::flapping; - else if (*it == "s" || *it == "downtime") + else if (v == "s" || v == "downtime") options |= service::downtime; - else if (*it == "n" || *it == "none") + else if (v == "n" || v == "none") options = service::none; - else if (*it == "a" || *it == "all") + else if (v == "a" || v == "all") options = service::unknown | service::warning | service::critical | service::ok | service::flapping | service::downtime; else diff --git a/engine/src/configuration/group.cc b/engine/src/configuration/group.cc index 03a19046b06..3f13e1a4f17 100644 --- a/engine/src/configuration/group.cc +++ b/engine/src/configuration/group.cc @@ -17,7 +17,6 @@ * */ #include "com/centreon/engine/configuration/group.hh" -#include "com/centreon/engine/string.hh" using namespace com::centreon::engine::configuration; @@ -72,17 +71,88 @@ group& group::operator=(group const& other) { * @return This object. */ template -group& group::operator=(std::string const& other) { +group& group::operator=(const std::string& other) { _data.clear(); if (!other.empty()) { if (other[0] == '+') { _is_inherit = true; - string::split(other.substr(1), _data, ','); + std::string_view sv = other; + auto split = absl::StrSplit(sv.substr(1), ','); + for (auto& s : split) { + std::string_view str = absl::StripAsciiWhitespace(s); + _data.push_back(std::string(str.data(), str.size())); + } } else if (other == "null") _is_null = true; else { _is_inherit = false; - string::split(other, _data, ','); + auto split = absl::StrSplit(other, ','); + for (auto& s : split) { + std::string_view str = absl::StripAsciiWhitespace(s); + _data.push_back(std::string(str.data(), str.size())); + } + } + } + _is_set = true; + return *this; +} + +template <> +group>& group>::operator=( + const std::string& other) { + _data.clear(); + if (!other.empty()) { + if (other[0] == '+') { + _is_inherit = true; + std::string_view sv = other; + auto split = absl::StrSplit(sv.substr(1), ','); + for (auto& s : split) { + std::string_view str = absl::StripAsciiWhitespace(s); + _data.insert(std::string(str.data(), str.size())); + } + } else if (other == "null") + _is_null = true; + else { + _is_inherit = false; + auto split = absl::StrSplit(other, ','); + for (auto& s : split) { + std::string_view str = absl::StripAsciiWhitespace(s); + _data.insert(std::string(str.data(), str.size())); + } + } + } + _is_set = true; + return *this; +} + +using set_pair_str = std::set>; +template <> +group& group::operator=(const std::string& other) { + _data.clear(); + auto spl = [this](std::string_view sv) { + auto values = absl::StrSplit(sv, ','); + for (auto it = values.begin(); it != values.end(); ++it) { + auto key = *it; + key = absl::StripAsciiWhitespace(key); + ++it; + if (it == values.end()) + break; + auto value = *it; + value = absl::StripAsciiWhitespace(value); + _data.insert({std::string(key.data(), key.size()), + std::string(value.data(), value.size())}); + } + }; + if (!other.empty()) { + if (other[0] == '+') { + _is_inherit = true; + std::string_view sv = other; + spl(sv.substr(1)); + } else if (other == "null") + _is_null = true; + else { + _is_inherit = false; + spl(other); } } _is_set = true; diff --git a/engine/src/configuration/host.cc b/engine/src/configuration/host.cc index 6b514d39037..707d77c0687 100644 --- a/engine/src/configuration/host.cc +++ b/engine/src/configuration/host.cc @@ -26,7 +26,6 @@ #include "com/centreon/engine/globals.hh" #include "com/centreon/engine/host.hh" #include "com/centreon/engine/logging/logger.hh" -#include "com/centreon/engine/string.hh" extern int config_warnings; extern int config_errors; @@ -1178,18 +1177,17 @@ bool host::_set_contacts(std::string const& value) { * @return True on success, otherwise false. */ bool host::_set_coords_2d(std::string const& value) { - std::list coords; - string::split(value, coords, ','); + std::list coords = absl::StrSplit(value, ','); if (coords.size() != 2) return false; int x; - if (!string::to(string::trim(coords.front()).c_str(), x)) + if (!absl::SimpleAtoi(coords.front(), &x)) return false; coords.pop_front(); int y; - if (!string::to(string::trim(coords.front()).c_str(), y)) + if (!absl::SimpleAtoi(coords.front(), &y)) return false; _coords_2d = point_2d(x, y); @@ -1204,23 +1202,22 @@ bool host::_set_coords_2d(std::string const& value) { * @return True on success, otherwise false. */ bool host::_set_coords_3d(std::string const& value) { - std::list coords; - string::split(value, coords, ','); + std::list coords = absl::StrSplit(value, ','); if (coords.size() != 3) return false; double x; - if (!string::to(string::trim(coords.front()).c_str(), x)) + if (!absl::SimpleAtod(coords.front(), &x)) return false; coords.pop_front(); double y; - if (!string::to(string::trim(coords.front()).c_str(), y)) + if (!absl::SimpleAtod(coords.front(), &y)) return false; coords.pop_front(); double z; - if (!string::to(string::trim(coords.front()).c_str(), z)) + if (!absl::SimpleAtod(coords.front(), &z)) return false; _coords_3d = point_3d(x, y, z); @@ -1334,20 +1331,18 @@ bool host::_set_flap_detection_enabled(bool value) { */ bool host::_set_flap_detection_options(std::string const& value) { unsigned short options(none); - std::list values; - string::split(value, values, ','); - for (std::list::iterator it(values.begin()), end(values.end()); - it != end; ++it) { - string::trim(*it); - if (*it == "o" || *it == "up") + auto values = absl::StrSplit(value, ','); + for (auto& val : values) { + auto v = absl::StripAsciiWhitespace(val); + if (v == "o" || v == "up") options |= up; - else if (*it == "d" || *it == "down") + else if (v == "d" || v == "down") options |= down; - else if (*it == "u" || *it == "unreachable") + else if (v == "u" || v == "unreachable") options |= unreachable; - else if (*it == "n" || *it == "none") + else if (v == "n" || v == "none") options = none; - else if (*it == "a" || *it == "all") + else if (v == "a" || v == "all") options = up | down | unreachable; else return false; @@ -1448,8 +1443,8 @@ bool host::_set_icon_image_alt(std::string const& value) { * @return True on success, otherwise false. */ bool host::_set_initial_state(std::string const& value) { - std::string data(value); - string::trim(data); + std::string_view data(value); + data = absl::StripAsciiWhitespace(data); if (data == "o" || data == "up") _initial_state = engine::host::state_up; else if (data == "d" || data == "down") @@ -1544,24 +1539,22 @@ bool host::_set_notification_interval(unsigned int value) { */ bool host::_set_notification_options(std::string const& value) { unsigned short options(none); - std::list values; - string::split(value, values, ','); - for (std::list::iterator it(values.begin()), end(values.end()); - it != end; ++it) { - string::trim(*it); - if (*it == "d" || *it == "down") + auto values = absl::StrSplit(value, ','); + for (auto& val : values) { + auto v = absl::StripAsciiWhitespace(val); + if (v == "d" || v == "down") options |= down; - else if (*it == "u" || *it == "unreachable") + else if (v == "u" || v == "unreachable") options |= unreachable; - else if (*it == "r" || *it == "recovery") + else if (v == "r" || v == "recovery") options |= up; - else if (*it == "f" || *it == "flapping") + else if (v == "f" || v == "flapping") options |= flapping; - else if (*it == "s" || *it == "downtime") + else if (v == "s" || v == "downtime") options |= downtime; - else if (*it == "n" || *it == "none") + else if (v == "n" || v == "none") options = none; - else if (*it == "a" || *it == "all") + else if (v == "a" || v == "all") options = down | unreachable | up | flapping | downtime; else return false; @@ -1675,20 +1668,18 @@ bool host::_set_recovery_notification_delay(unsigned int value) { */ bool host::_set_stalking_options(std::string const& value) { unsigned short options(none); - std::list values; - string::split(value, values, ','); - for (std::list::iterator it(values.begin()), end(values.end()); - it != end; ++it) { - string::trim(*it); - if (*it == "o" || *it == "up") + auto values = absl::StrSplit(value, ','); + for (auto& val : values) { + auto v = absl::StripAsciiWhitespace(val); + if (v == "o" || v == "up") options |= up; - else if (*it == "d" || *it == "down") + else if (v == "d" || v == "down") options |= down; - else if (*it == "u" || *it == "unreachable") + else if (v == "u" || v == "unreachable") options |= unreachable; - else if (*it == "n" || *it == "none") + else if (v == "n" || v == "none") options = none; - else if (*it == "a" || *it == "all") + else if (v == "a" || v == "all") options = up | down | unreachable; else return false; diff --git a/engine/src/configuration/hostdependency.cc b/engine/src/configuration/hostdependency.cc index 158b378384f..1f7110b15ec 100644 --- a/engine/src/configuration/hostdependency.cc +++ b/engine/src/configuration/hostdependency.cc @@ -22,7 +22,6 @@ #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" #include "com/centreon/engine/logging/logger.hh" -#include "com/centreon/engine/string.hh" extern int config_warnings; extern int config_errors; @@ -205,8 +204,6 @@ void hostdependency::check_validity() const { "'{}'.", dependend_host_name, host_name); } - - return; } /** @@ -214,7 +211,7 @@ void hostdependency::check_validity() const { * * @return This object. */ -hostdependency::key_type const& hostdependency::key() const throw() { +hostdependency::key_type const& hostdependency::key() const noexcept { return *this; } @@ -262,7 +259,6 @@ bool hostdependency::parse(char const* key, char const* value) { */ void hostdependency::dependency_period(std::string const& period) { _dependency_period = period; - return; } /** @@ -270,7 +266,7 @@ void hostdependency::dependency_period(std::string const& period) { * * @return The dependency_period. */ -std::string const& hostdependency::dependency_period() const throw() { +std::string const& hostdependency::dependency_period() const noexcept { return _dependency_period; } @@ -280,9 +276,8 @@ std::string const& hostdependency::dependency_period() const throw() { * @param[in] type Dependency type. */ void hostdependency::dependency_type( - hostdependency::dependency_kind type) throw() { + hostdependency::dependency_kind type) noexcept { _dependency_type = type; - return; } /** @@ -290,8 +285,8 @@ void hostdependency::dependency_type( * * @return Dependency type. */ -hostdependency::dependency_kind hostdependency::dependency_type() const - throw() { +hostdependency::dependency_kind hostdependency::dependency_type() + const noexcept { return _dependency_type; } @@ -300,7 +295,7 @@ hostdependency::dependency_kind hostdependency::dependency_type() const * * @return Dependent host groups. */ -set_string& hostdependency::dependent_hostgroups() throw() { +set_string& hostdependency::dependent_hostgroups() noexcept { return *_dependent_hostgroups; } @@ -309,7 +304,7 @@ set_string& hostdependency::dependent_hostgroups() throw() { * * @return The dependent_hostgroups. */ -set_string const& hostdependency::dependent_hostgroups() const throw() { +set_string const& hostdependency::dependent_hostgroups() const noexcept { return *_dependent_hostgroups; } @@ -318,7 +313,7 @@ set_string const& hostdependency::dependent_hostgroups() const throw() { * * @return The dependent hosts. */ -set_string& hostdependency::dependent_hosts() throw() { +set_string& hostdependency::dependent_hosts() noexcept { return *_dependent_hosts; } @@ -327,7 +322,7 @@ set_string& hostdependency::dependent_hosts() throw() { * * @return The dependent_hosts. */ -set_string const& hostdependency::dependent_hosts() const throw() { +set_string const& hostdependency::dependent_hosts() const noexcept { return *_dependent_hosts; } @@ -336,9 +331,8 @@ set_string const& hostdependency::dependent_hosts() const throw() { * * @param[in] options New options. */ -void hostdependency::execution_failure_options(unsigned int options) throw() { +void hostdependency::execution_failure_options(unsigned int options) noexcept { _execution_failure_options.set(options); - return; } /** @@ -346,7 +340,7 @@ void hostdependency::execution_failure_options(unsigned int options) throw() { * * @return The execution_failure_options. */ -unsigned int hostdependency::execution_failure_options() const throw() { +unsigned int hostdependency::execution_failure_options() const noexcept { return _execution_failure_options; } @@ -355,7 +349,7 @@ unsigned int hostdependency::execution_failure_options() const throw() { * * @return The host groups. */ -set_string& hostdependency::hostgroups() throw() { +set_string& hostdependency::hostgroups() noexcept { return *_hostgroups; } @@ -364,7 +358,7 @@ set_string& hostdependency::hostgroups() throw() { * * @return The hostgroups. */ -set_string const& hostdependency::hostgroups() const throw() { +set_string const& hostdependency::hostgroups() const noexcept { return *_hostgroups; } @@ -373,7 +367,7 @@ set_string const& hostdependency::hostgroups() const throw() { * * @return The hosts. */ -set_string& hostdependency::hosts() throw() { +set_string& hostdependency::hosts() noexcept { return *_hosts; } @@ -382,7 +376,7 @@ set_string& hostdependency::hosts() throw() { * * @return The hosts. */ -set_string const& hostdependency::hosts() const throw() { +set_string const& hostdependency::hosts() const noexcept { return *_hosts; } @@ -391,9 +385,8 @@ set_string const& hostdependency::hosts() const throw() { * * @param[in] inherit True if dependency inherits parent. */ -void hostdependency::inherits_parent(bool inherit) throw() { +void hostdependency::inherits_parent(bool inherit) noexcept { _inherits_parent = inherit; - return; } /** @@ -401,7 +394,7 @@ void hostdependency::inherits_parent(bool inherit) throw() { * * @return The inherits_parent. */ -bool hostdependency::inherits_parent() const throw() { +bool hostdependency::inherits_parent() const noexcept { return _inherits_parent; } @@ -413,7 +406,6 @@ bool hostdependency::inherits_parent() const throw() { void hostdependency::notification_failure_options( unsigned int options) throw() { _notification_failure_options.set(options); - return; } /** @@ -470,22 +462,20 @@ bool hostdependency::_set_dependent_hosts(std::string const& value) { */ bool hostdependency::_set_execution_failure_options(std::string const& value) { unsigned short options(none); - std::list values; - string::split(value, values, ','); - for (std::list::iterator it(values.begin()), end(values.end()); - it != end; ++it) { - string::trim(*it); - if (*it == "o" || *it == "up") + auto values = absl::StrSplit(value, ','); + for (auto& val : values) { + auto v = absl::StripAsciiWhitespace(val); + if (v == "o" || v == "up") options |= up; - else if (*it == "d" || *it == "down") + else if (v == "d" || v == "down") options |= down; - else if (*it == "u" || *it == "unreachable") + else if (v == "u" || v == "unreachable") options |= unreachable; - else if (*it == "p" || *it == "pending") + else if (v == "p" || v == "pending") options |= pending; - else if (*it == "n" || *it == "none") + else if (v == "n" || v == "none") options = none; - else if (*it == "a" || *it == "all") + else if (v == "a" || v == "all") options = up | down | unreachable | pending; else return false; @@ -540,22 +530,20 @@ bool hostdependency::_set_inherits_parent(bool value) { bool hostdependency::_set_notification_failure_options( std::string const& value) { unsigned short options(none); - std::list values; - string::split(value, values, ','); - for (std::list::iterator it(values.begin()), end(values.end()); - it != end; ++it) { - string::trim(*it); - if (*it == "o" || *it == "up") + auto values = absl::StrSplit(value, ','); + for (auto& val : values) { + auto v = absl::StripAsciiWhitespace(val); + if (v == "o" || v == "up") options |= up; - else if (*it == "d" || *it == "down") + else if (v == "d" || v == "down") options |= down; - else if (*it == "u" || *it == "unreachable") + else if (v == "u" || v == "unreachable") options |= unreachable; - else if (*it == "p" || *it == "pending") + else if (v == "p" || v == "pending") options |= pending; - else if (*it == "n" || *it == "none") + else if (v == "n" || v == "none") options = none; - else if (*it == "a" || *it == "all") + else if (v == "a" || v == "all") options = up | down | unreachable | pending; else return false; diff --git a/engine/src/configuration/hostescalation.cc b/engine/src/configuration/hostescalation.cc index 602616c8245..09a4ccc9449 100644 --- a/engine/src/configuration/hostescalation.cc +++ b/engine/src/configuration/hostescalation.cc @@ -19,7 +19,6 @@ */ #include "com/centreon/engine/configuration/hostescalation.hh" #include "com/centreon/engine/exceptions/error.hh" -#include "com/centreon/engine/string.hh" using namespace com::centreon; using namespace com::centreon::engine::configuration; @@ -402,20 +401,18 @@ bool hostescalation::_set_contactgroups(std::string const& value) { */ bool hostescalation::_set_escalation_options(std::string const& value) { unsigned short options(none); - std::list values; - string::split(value, values, ','); - for (std::list::iterator it(values.begin()), end(values.end()); - it != end; ++it) { - string::trim(*it); - if (*it == "d" || *it == "down") + auto values = absl::StrSplit(value, ','); + for (auto& val : values) { + auto v = absl::StripAsciiWhitespace(val); + if (v == "d" || v == "down") options |= down; - else if (*it == "u" || *it == "unreachable") + else if (v == "u" || v == "unreachable") options |= unreachable; - else if (*it == "r" || *it == "recovery") + else if (v == "r" || v == "recovery") options |= recovery; - else if (*it == "n" || *it == "none") + else if (v == "n" || v == "none") options = none; - else if (*it == "a" || *it == "all") + else if (v == "a" || v == "all") options = down | unreachable | recovery; else return false; diff --git a/engine/src/configuration/object.cc b/engine/src/configuration/object.cc index ae0db4ec86f..9eafe7d4e22 100644 --- a/engine/src/configuration/object.cc +++ b/engine/src/configuration/object.cc @@ -35,7 +35,6 @@ #include "com/centreon/engine/configuration/tag.hh" #include "com/centreon/engine/configuration/timeperiod.hh" #include "com/centreon/engine/exceptions/error.hh" -#include "com/centreon/engine/string.hh" using namespace com::centreon; using namespace com::centreon::engine::configuration; @@ -299,6 +298,6 @@ bool object::_set_should_register(bool value) { */ bool object::_set_templates(std::string const& value) { _templates.clear(); - string::split(value, _templates, ','); + _templates = absl::StrSplit(value, ','); return true; } diff --git a/engine/src/configuration/parser.cc b/engine/src/configuration/parser.cc index 112ef90061c..96df2e3ad45 100644 --- a/engine/src/configuration/parser.cc +++ b/engine/src/configuration/parser.cc @@ -20,7 +20,6 @@ #include "com/centreon/engine/configuration/parser.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/string.hh" #include "com/centreon/io/directory_entry.hh" using namespace com::centreon; @@ -47,6 +46,30 @@ parser::store parser::_store[] = { &parser::_store_into_list, &parser::_store_into_list}; +/** + * Get the next valid line. + * + * @param[in, out] stream The current stream to read new line. + * @param[out] line The line to fill. + * @param[in, out] pos The current position. + * + * @return True if data is available, false if no data. + */ +static bool get_next_line(std::ifstream& stream, + std::string& line, + uint32_t& pos) { + while (std::getline(stream, line, '\n')) { + ++pos; + line = absl::StripAsciiWhitespace(line); + if (!line.empty()) { + char c = line[0]; + if (c != '#' && c != ';' && c != '\x0') + return true; + } + } + return false; +} + /** * Default constructor. * @@ -285,7 +308,7 @@ void parser::_parse_directory_configuration(std::string const& path) { * * @param[in] path The configuration path. */ -void parser::_parse_global_configuration(std::string const& path) { +void parser::_parse_global_configuration(const std::string& path) { engine_logger(logging::log_info_message, logging::most) << "Reading main configuration file '" << path << "'."; config_logger->info("Reading main configuration file '{}'.", path); @@ -302,14 +325,20 @@ void parser::_parse_global_configuration(std::string const& path) { _current_path = path; std::string input; - while (string::get_next_line(stream, input, _current_line)) { - char const* key; - char const* value; - if (!string::split(input, &key, &value, '=') || !_config->set(key, value)) - throw engine_error() << "Parsing of global " - "configuration failed in file '" - << path << "' on line " << _current_line - << ": Invalid line '" << input << "'"; + while (get_next_line(stream, input, _current_line)) { + std::list values = + absl::StrSplit(input, absl::MaxSplits('=', 1)); + if (values.size() == 2) { + auto it = values.begin(); + char const* key = it->c_str(); + ++it; + char const* value = it->c_str(); + if (_config->set(key, value)) + continue; + } + throw engine_error() << "Parsing of global configuration failed in file '" + << path << "' on line " << _current_line + << ": Invalid line '" << input << "'"; } } @@ -334,12 +363,12 @@ void parser::_parse_object_definitions(std::string const& path) { bool parse_object = false; object_ptr obj; std::string input; - while (string::get_next_line(stream, input, _current_line)) { + while (get_next_line(stream, input, _current_line)) { // Multi-line. while ('\\' == input[input.size() - 1]) { input.resize(input.size() - 1); std::string addendum; - if (!string::get_next_line(stream, addendum, _current_line)) + if (!get_next_line(stream, addendum, _current_line)) break; input.append(addendum); } @@ -351,20 +380,21 @@ void parser::_parse_object_definitions(std::string const& path) { << "Parsing of object definition failed " << "in file '" << _current_path << "' on line " << _current_line << ": Unexpected start definition"; - string::trim_left(input.erase(0, 6)); - std::size_t last(input.size() - 1); + input.erase(0, 6); + absl::StripLeadingAsciiWhitespace(&input); + std::size_t last = input.size() - 1; if (input.empty() || input[last] != '{') throw engine_error() - << "Parsing of object definition failed " - << "in file '" << _current_path << "' on line " << _current_line - << ": Unexpected start definition"; - std::string const& type(string::trim_right(input.erase(last))); - obj = object::create(type); + << "Parsing of object definition failed in file '" << _current_path + << "' on line " << _current_line << ": Unexpected start definition"; + input.erase(last); + absl::StripTrailingAsciiWhitespace(&input); + obj = object::create(input); if (obj == nullptr) throw engine_error() << "Parsing of object definition failed " << "in file '" << _current_path << "' on line " << _current_line - << ": Unknown object type name '" << type << "'"; + << ": Unknown object type name '" << input << "'"; parse_object = (_read_options & (1 << obj->type())); _objects_info[obj.get()] = file_info(path, _current_line); } @@ -410,15 +440,20 @@ void parser::_parse_resource_file(std::string const& path) { _current_path = path; std::string input; - while (string::get_next_line(stream, input, _current_line)) { + while (get_next_line(stream, input, _current_line)) { try { - std::string key; - std::string value; - if (!string::split(input, key, value, '=')) + std::list key_value = + absl::StrSplit(input, absl::MaxSplits('=', 1)); + if (key_value.size() == 2) { + auto it = key_value.begin(); + std::string& key = *it; + ++it; + std::string value = *it; + _config->user(key, value); + } else throw engine_error() << "Parsing of resource file '" << _current_path << "' failed on line " << _current_line << ": Invalid line '" << input << "'"; - _config->user(key, value); } catch (std::exception const& e) { (void)e; throw engine_error() << "Parsing of resource file '" << _current_path diff --git a/engine/src/configuration/service.cc b/engine/src/configuration/service.cc index 7a3f99568b9..49d84efb0d1 100644 --- a/engine/src/configuration/service.cc +++ b/engine/src/configuration/service.cc @@ -21,12 +21,10 @@ #include #include #include -#include "com/centreon/engine/customvariable.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" #include "com/centreon/engine/host.hh" #include "com/centreon/engine/logging/logger.hh" -#include "com/centreon/engine/string.hh" extern int config_warnings; extern int config_errors; @@ -1706,22 +1704,20 @@ bool service::_set_flap_detection_enabled(bool value) { */ bool service::_set_flap_detection_options(std::string const& value) { unsigned short options(none); - std::list values; - string::split(value, values, ','); - for (std::list::iterator it(values.begin()), end(values.end()); - it != end; ++it) { - string::trim(*it); - if (*it == "o" || *it == "ok") + auto values = absl::StrSplit(value, ','); + for (auto& val : values) { + auto v = absl::StripAsciiWhitespace(val); + if (v == "o" || v == "ok") options |= ok; - else if (*it == "w" || *it == "warning") + else if (v == "w" || v == "warning") options |= warning; - else if (*it == "u" || *it == "unknown") + else if (v == "u" || v == "unknown") options |= unknown; - else if (*it == "c" || *it == "critical") + else if (v == "c" || v == "critical") options |= critical; - else if (*it == "n" || *it == "none") + else if (v == "n" || v == "none") options = none; - else if (*it == "a" || *it == "all") + else if (v == "a" || v == "all") options = ok | warning | unknown | critical; else return false; @@ -1810,8 +1806,8 @@ bool service::_set_icon_image_alt(std::string const& value) { * @return True on success, otherwise false. */ bool service::_set_initial_state(std::string const& value) { - std::string data(value); - string::trim(data); + std::string_view data(value); + data = absl::StripAsciiWhitespace(data); if (data == "o" || data == "ok") _initial_state = engine::service::state_ok; else if (data == "w" || data == "warning") @@ -1908,26 +1904,24 @@ bool service::_set_notifications_enabled(bool value) { */ bool service::_set_notification_options(std::string const& value) { unsigned short options(none); - std::list values; - string::split(value, values, ','); - for (std::list::iterator it(values.begin()), end(values.end()); - it != end; ++it) { - string::trim(*it); - if (*it == "u" || *it == "unknown") + auto values = absl::StrSplit(value, ','); + for (auto& val : values) { + auto v = absl::StripAsciiWhitespace(val); + if (v == "u" || v == "unknown") options |= unknown; - else if (*it == "w" || *it == "warning") + else if (v == "w" || v == "warning") options |= warning; - else if (*it == "c" || *it == "critical") + else if (v == "c" || v == "critical") options |= critical; - else if (*it == "r" || *it == "recovery") + else if (v == "r" || v == "recovery") options |= ok; - else if (*it == "f" || *it == "flapping") + else if (v == "f" || v == "flapping") options |= flapping; - else if (*it == "s" || *it == "downtime") + else if (v == "s" || v == "downtime") options |= downtime; - else if (*it == "n" || *it == "none") + else if (v == "n" || v == "none") options = none; - else if (*it == "a" || *it == "all") + else if (v == "a" || v == "all") options = unknown | warning | critical | ok | flapping | downtime; else return false; @@ -2098,22 +2092,20 @@ bool service::set_service_id(uint64_t value) { */ bool service::_set_stalking_options(std::string const& value) { unsigned short options(none); - std::list values; - string::split(value, values, ','); - for (std::list::iterator it(values.begin()), end(values.end()); - it != end; ++it) { - string::trim(*it); - if (*it == "o" || *it == "ok") + auto values = absl::StrSplit(value, ','); + for (auto& val : values) { + auto v = absl::StripAsciiWhitespace(val); + if (v == "o" || v == "ok") options |= ok; - else if (*it == "w" || *it == "warning") + else if (v == "w" || v == "warning") options |= warning; - else if (*it == "u" || *it == "unknown") + else if (v == "u" || v == "unknown") options |= unknown; - else if (*it == "c" || *it == "critical") + else if (v == "c" || v == "critical") options |= critical; - else if (*it == "n" || *it == "none") + else if (v == "n" || v == "none") options = none; - else if (*it == "a" || *it == "all") + else if (v == "a" || v == "all") options = ok | warning | unknown | critical; else return false; diff --git a/engine/src/configuration/servicedependency.cc b/engine/src/configuration/servicedependency.cc index ec5d032bf11..50798ee51c1 100644 --- a/engine/src/configuration/servicedependency.cc +++ b/engine/src/configuration/servicedependency.cc @@ -22,7 +22,6 @@ #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" #include "com/centreon/engine/logging/logger.hh" -#include "com/centreon/engine/string.hh" extern int config_warnings; extern int config_errors; @@ -215,7 +214,7 @@ bool servicedependency::operator<(servicedependency const& right) const { return (_execution_failure_options < right._execution_failure_options); else if (_inherits_parent != right._inherits_parent) return _inherits_parent < right._inherits_parent; - return (_notification_failure_options < right._notification_failure_options); + return _notification_failure_options < right._notification_failure_options; } /** @@ -341,7 +340,6 @@ bool servicedependency::parse(char const* key, char const* value) { */ void servicedependency::dependency_period(std::string const& period) { _dependency_period = period; - return; } /** @@ -361,7 +359,6 @@ std::string const& servicedependency::dependency_period() const throw() { void servicedependency::dependency_type( servicedependency::dependency_kind type) throw() { _dependency_type = type; - return; } /** @@ -455,7 +452,6 @@ list_string const& servicedependency::dependent_service_description() const void servicedependency::execution_failure_options( unsigned int options) throw() { _execution_failure_options = options; - return; } /** @@ -474,7 +470,6 @@ unsigned int servicedependency::execution_failure_options() const throw() { */ void servicedependency::inherits_parent(bool inherit) throw() { _inherits_parent = inherit; - return; } /** @@ -530,7 +525,6 @@ list_string const& servicedependency::hosts() const throw() { void servicedependency::notification_failure_options( unsigned int options) throw() { _notification_failure_options = options; - return; } /** @@ -649,24 +643,22 @@ bool servicedependency::_set_dependent_service_description( bool servicedependency::_set_execution_failure_options( std::string const& value) { unsigned short options(none); - std::list values; - string::split(value, values, ','); - for (std::list::iterator it(values.begin()), end(values.end()); - it != end; ++it) { - string::trim(*it); - if (*it == "o" || *it == "ok") + auto values = absl::StrSplit(value, ','); + for (auto& v : values) { + std::string_view sv = absl::StripAsciiWhitespace(v); + if (sv == "o" || sv == "ok") options |= ok; - else if (*it == "u" || *it == "unknown") + else if (sv == "u" || sv == "unknown") options |= unknown; - else if (*it == "w" || *it == "warning") + else if (sv == "w" || sv == "warning") options |= warning; - else if (*it == "c" || *it == "critical") + else if (sv == "c" || sv == "critical") options |= critical; - else if (*it == "p" || *it == "pending") + else if (sv == "p" || sv == "pending") options |= pending; - else if (*it == "n" || *it == "none") + else if (sv == "n" || sv == "none") options = none; - else if (*it == "a" || *it == "all") + else if (sv == "a" || sv == "all") options = ok | unknown | warning | critical | pending; else return false; @@ -721,24 +713,22 @@ bool servicedependency::_set_hosts(std::string const& value) { bool servicedependency::_set_notification_failure_options( std::string const& value) { unsigned short options(none); - std::list values; - string::split(value, values, ','); - for (std::list::iterator it(values.begin()), end(values.end()); - it != end; ++it) { - string::trim(*it); - if (*it == "o" || *it == "ok") + auto values = absl::StrSplit(value, ','); + for (auto& v : values) { + std::string_view sv = absl::StripAsciiWhitespace(v); + if (sv == "o" || sv == "ok") options |= ok; - else if (*it == "u" || *it == "unknown") + else if (sv == "u" || sv == "unknown") options |= unknown; - else if (*it == "w" || *it == "warning") + else if (sv == "w" || sv == "warning") options |= warning; - else if (*it == "c" || *it == "critical") + else if (sv == "c" || sv == "critical") options |= critical; - else if (*it == "p" || *it == "pending") + else if (sv == "p" || sv == "pending") options |= pending; - else if (*it == "n" || *it == "none") + else if (sv == "n" || sv == "none") options = none; - else if (*it == "a" || *it == "all") + else if (sv == "a" || sv == "all") options = ok | unknown | warning | critical | pending; else return false; diff --git a/engine/src/configuration/serviceescalation.cc b/engine/src/configuration/serviceescalation.cc index 820af49c438..729690709c1 100644 --- a/engine/src/configuration/serviceescalation.cc +++ b/engine/src/configuration/serviceescalation.cc @@ -21,7 +21,6 @@ #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" #include "com/centreon/engine/logging/logger.hh" -#include "com/centreon/engine/string.hh" using namespace com::centreon; using namespace com::centreon::engine::configuration; @@ -280,7 +279,6 @@ void serviceescalation::check_validity() const { << "any host or host group (properties 'host_name' or " << "'hostgroup_name', respectively)"); } - return; } /** @@ -337,7 +335,7 @@ bool serviceescalation::parse(char const* key, char const* value) { * * @return The contact groups. */ -set_string& serviceescalation::contactgroups() throw() { +set_string& serviceescalation::contactgroups() noexcept { return *_contactgroups; } @@ -346,7 +344,7 @@ set_string& serviceescalation::contactgroups() throw() { * * @return The contactgroups. */ -set_string const& serviceescalation::contactgroups() const throw() { +set_string const& serviceescalation::contactgroups() const noexcept { return *_contactgroups; } @@ -355,7 +353,7 @@ set_string const& serviceescalation::contactgroups() const throw() { * * @return True if contact groups were defined. */ -bool serviceescalation::contactgroups_defined() const throw() { +bool serviceescalation::contactgroups_defined() const noexcept { return _contactgroups.is_set(); } @@ -364,9 +362,8 @@ bool serviceescalation::contactgroups_defined() const throw() { * * @param[in] options New escalation options. */ -void serviceescalation::escalation_options(unsigned int options) throw() { +void serviceescalation::escalation_options(unsigned int options) noexcept { _escalation_options = options; - return; } /** @@ -374,7 +371,7 @@ void serviceescalation::escalation_options(unsigned int options) throw() { * * @return The escalation_options. */ -unsigned short serviceescalation::escalation_options() const throw() { +unsigned short serviceescalation::escalation_options() const noexcept { return _escalation_options; } @@ -385,7 +382,6 @@ unsigned short serviceescalation::escalation_options() const throw() { */ void serviceescalation::escalation_period(std::string const& period) { _escalation_period = period; - return; } /** @@ -393,7 +389,7 @@ void serviceescalation::escalation_period(std::string const& period) { * * @return The escalation_period. */ -std::string const& serviceescalation::escalation_period() const throw() { +std::string const& serviceescalation::escalation_period() const noexcept { return _escalation_period; } @@ -402,7 +398,7 @@ std::string const& serviceescalation::escalation_period() const throw() { * * @return True if the escalation period was defined. */ -bool serviceescalation::escalation_period_defined() const throw() { +bool serviceescalation::escalation_period_defined() const noexcept { return _escalation_period.is_set(); } @@ -411,9 +407,8 @@ bool serviceescalation::escalation_period_defined() const throw() { * * @param[in] n First notification number. */ -void serviceescalation::first_notification(unsigned int n) throw() { +void serviceescalation::first_notification(unsigned int n) noexcept { _first_notification = n; - return; } /** @@ -421,7 +416,7 @@ void serviceescalation::first_notification(unsigned int n) throw() { * * @return The first_notification. */ -unsigned int serviceescalation::first_notification() const throw() { +unsigned int serviceescalation::first_notification() const noexcept { return _first_notification; } @@ -430,7 +425,7 @@ unsigned int serviceescalation::first_notification() const throw() { * * @return Host groups. */ -list_string& serviceescalation::hostgroups() throw() { +list_string& serviceescalation::hostgroups() noexcept { return *_hostgroups; } @@ -439,7 +434,7 @@ list_string& serviceescalation::hostgroups() throw() { * * @return The hostgroups. */ -list_string const& serviceescalation::hostgroups() const throw() { +list_string const& serviceescalation::hostgroups() const noexcept { return *_hostgroups; } @@ -448,7 +443,7 @@ list_string const& serviceescalation::hostgroups() const throw() { * * @return The hosts. */ -list_string& serviceescalation::hosts() throw() { +list_string& serviceescalation::hosts() noexcept { return *_hosts; } @@ -457,7 +452,7 @@ list_string& serviceescalation::hosts() throw() { * * @return The hosts. */ -list_string const& serviceescalation::hosts() const throw() { +list_string const& serviceescalation::hosts() const noexcept { return *_hosts; } @@ -466,9 +461,8 @@ list_string const& serviceescalation::hosts() const throw() { * * @param[in] n Last notification number. */ -void serviceescalation::last_notification(unsigned int n) throw() { +void serviceescalation::last_notification(unsigned int n) noexcept { _last_notification = n; - return; } /** @@ -476,7 +470,7 @@ void serviceescalation::last_notification(unsigned int n) throw() { * * @return The last_notification. */ -unsigned int serviceescalation::last_notification() const throw() { +unsigned int serviceescalation::last_notification() const noexcept { return _last_notification; } @@ -485,9 +479,8 @@ unsigned int serviceescalation::last_notification() const throw() { * * @param[in] interval New notification interval. */ -void serviceescalation::notification_interval(unsigned int interval) throw() { +void serviceescalation::notification_interval(unsigned int interval) noexcept { _notification_interval = interval; - return; } /** @@ -495,7 +488,7 @@ void serviceescalation::notification_interval(unsigned int interval) throw() { * * @return The notification_interval. */ -unsigned int serviceescalation::notification_interval() const throw() { +unsigned int serviceescalation::notification_interval() const noexcept { return _notification_interval; } @@ -504,7 +497,7 @@ unsigned int serviceescalation::notification_interval() const throw() { * * @return True if the notification interval was set. */ -bool serviceescalation::notification_interval_defined() const throw() { +bool serviceescalation::notification_interval_defined() const noexcept { return _notification_interval.is_set(); } @@ -513,7 +506,7 @@ bool serviceescalation::notification_interval_defined() const throw() { * * @return The service groups. */ -list_string& serviceescalation::servicegroups() throw() { +list_string& serviceescalation::servicegroups() noexcept { return *_servicegroups; } @@ -522,7 +515,7 @@ list_string& serviceescalation::servicegroups() throw() { * * @return The servicegroups. */ -list_string const& serviceescalation::servicegroups() const throw() { +list_string const& serviceescalation::servicegroups() const noexcept { return *_servicegroups; } @@ -531,7 +524,7 @@ list_string const& serviceescalation::servicegroups() const throw() { * * @return Service description. */ -list_string& serviceescalation::service_description() throw() { +list_string& serviceescalation::service_description() noexcept { return *_service_description; } @@ -540,7 +533,7 @@ list_string& serviceescalation::service_description() throw() { * * @return The service_description. */ -list_string const& serviceescalation::service_description() const throw() { +list_string const& serviceescalation::service_description() const noexcept { return *_service_description; } @@ -565,22 +558,20 @@ bool serviceescalation::_set_contactgroups(std::string const& value) { */ bool serviceescalation::_set_escalation_options(std::string const& value) { unsigned short options(none); - std::list values; - string::split(value, values, ','); - for (std::list::iterator it(values.begin()), end(values.end()); - it != end; ++it) { - string::trim(*it); - if (*it == "w" || *it == "warning") + auto values = absl::StrSplit(value, ','); + for (auto& val : values) { + auto v = absl::StripAsciiWhitespace(val); + if (v == "w" || v == "warning") options |= warning; - else if (*it == "u" || *it == "unknown") + else if (v == "u" || v == "unknown") options |= unknown; - else if (*it == "c" || *it == "critical") + else if (v == "c" || v == "critical") options |= critical; - else if (*it == "r" || *it == "recovery") + else if (v == "r" || v == "recovery") options |= recovery; - else if (*it == "n" || *it == "none") + else if (v == "n" || v == "none") options = none; - else if (*it == "a" || *it == "all") + else if (v == "a" || v == "all") options = warning | unknown | critical | recovery; else return false; diff --git a/engine/src/configuration/state.cc b/engine/src/configuration/state.cc index 69d0159a562..2f74aa66503 100644 --- a/engine/src/configuration/state.cc +++ b/engine/src/configuration/state.cc @@ -21,7 +21,6 @@ #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/string.hh" #include "com/centreon/io/file_entry.hh" #include "compatibility/locations.h" @@ -38,13 +37,38 @@ struct setter : public setter_base { bool apply_from_cfg(state& obj, char const* value) override { try { U val(0); - if (!string::to(value, val)) - return false; - (obj.*ptr)(val); - } catch (std::exception const& e) { - SPDLOG_LOGGER_ERROR(config_logger, "fail to update {} with value {}: {}", - setter_base::_field_name, value, e.what()); - return false; + if constexpr (std::is_same_v) { + if (!absl::SimpleAtob(value, &val)) + return false; + (obj.*ptr)(val); + } else if constexpr (std::is_same_v) { + uint32_t v; + if (!absl::SimpleAtoi(value, &v)) + return false; + if (v > 0xffffu) + return false; + else + val = v; + (obj.*ptr)(val); + } else if constexpr (std::is_integral::value) { + if (!absl::SimpleAtoi(value, &val)) + return false; + (obj.*ptr)(val); + } else if constexpr (std::is_same_v) { + if (!absl::SimpleAtof(value, &val)) + return false; + (obj.*ptr)(val); + } else if constexpr (std::is_same_v) { + if (!absl::SimpleAtod(value, &val)) + return false; + (obj.*ptr)(val); + } else { + static_assert(std::is_integral_v || std::is_floating_point_v || + std::is_same_v); + } + } catch (const std::exception& e) { + config_logger->error("Failed to parse '{}={}': {}", + setter_base::_field_name, value, e.what()); } return true; } @@ -137,7 +161,7 @@ void state::_init_setter() { SETTER(std::string const&, _set_daemon_dumps_core, "daemon_dumps_core"); SETTER(std::string const&, _set_date_format, "date_format"); SETTER(std::string const&, debug_file, "debug_file"); - SETTER(uint64_t, debug_level, "debug_level"); + SETTER(int64_t, debug_level, "debug_level"); SETTER(unsigned int, debug_verbosity, "debug_verbosity"); SETTER(std::string const&, _set_downtime_file, "downtime_file"); SETTER(std::string const&, _set_enable_embedded_perl, "enable_embedded_perl"); @@ -330,7 +354,7 @@ static int const default_command_check_interval(-1); static std::string const default_command_file(DEFAULT_COMMAND_FILE); static state::date_type const default_date_format(state::us); static std::string const default_debug_file(DEFAULT_DEBUG_FILE); -static uint64_t const default_debug_level(0); +static int64_t const default_debug_level(0); static unsigned int const default_debug_verbosity(1); static bool const default_enable_environment_macros(false); static bool const default_enable_event_handlers(true); @@ -1703,7 +1727,7 @@ void state::debug_file(std::string const& value) { * * @return The debug_level value. */ -uint64_t state::debug_level() const noexcept { +int64_t state::debug_level() const noexcept { return _debug_level; } @@ -1712,9 +1736,9 @@ uint64_t state::debug_level() const noexcept { * * @param[in] value The new debug_level value. */ -void state::debug_level(uint64_t value) { - if (value == std::numeric_limits::max()) - _debug_level = static_cast(all); +void state::debug_level(int64_t value) { + if (value == -1) + _debug_level = all; else _debug_level = value; } @@ -3743,7 +3767,7 @@ void state::user(std::string const& key, std::string const& value) { * @param[in] value The user value. */ void state::user(unsigned int key, std::string const& value) { - _users[string::from(key)] = value; + _users[fmt::format("{}", key)] = value; } /** @@ -4524,7 +4548,7 @@ void state::_set_host_inter_check_delay_method(std::string const& value) { _host_inter_check_delay_method = icd_smart; else { _host_inter_check_delay_method = icd_user; - if (!string::to(value.c_str(), scheduling_info.host_inter_check_delay) || + if (!absl::SimpleAtod(value, &scheduling_info.host_inter_check_delay) || scheduling_info.host_inter_check_delay <= 0.0) throw engine_error() << "Invalid value for host_inter_check_delay_method, must " @@ -4724,7 +4748,7 @@ void state::_set_service_inter_check_delay_method(std::string const& value) { _service_inter_check_delay_method = icd_smart; else { _service_inter_check_delay_method = icd_user; - if (!string::to(value.c_str(), scheduling_info.service_inter_check_delay) || + if (!absl::SimpleAtod(value, &scheduling_info.service_inter_check_delay) || scheduling_info.service_inter_check_delay <= 0.0) throw engine_error() << "Invalid value for service_inter_check_delay_method, " @@ -4743,7 +4767,7 @@ void state::_set_service_interleave_factor_method(std::string const& value) { _service_interleave_factor_method = ilf_smart; else { _service_interleave_factor_method = ilf_user; - if (!string::to(value.c_str(), scheduling_info.service_interleave_factor) || + if (!absl::SimpleAtoi(value, &scheduling_info.service_interleave_factor) || scheduling_info.service_interleave_factor < 1) scheduling_info.service_interleave_factor = 1; } diff --git a/engine/src/configuration/timeperiod.cc b/engine/src/configuration/timeperiod.cc index 5d20d96030d..8f8899afdf3 100644 --- a/engine/src/configuration/timeperiod.cc +++ b/engine/src/configuration/timeperiod.cc @@ -21,7 +21,6 @@ #include "com/centreon/engine/common.hh" #include "com/centreon/engine/exceptions/error.hh" -#include "com/centreon/engine/string.hh" #include "com/centreon/engine/timerange.hh" using namespace com::centreon; @@ -57,7 +56,7 @@ timeperiod::timeperiod(timeperiod const& right) : object(right) { /** * Destructor. */ -timeperiod::~timeperiod() throw() {} +timeperiod::~timeperiod() noexcept {} /** * Copy constructor. @@ -86,10 +85,10 @@ timeperiod& timeperiod::operator=(timeperiod const& right) { * @return True if is the same timeperiod, otherwise false. */ bool timeperiod::operator==(timeperiod const& right) const { - return (object::operator==(right) && _alias == right._alias && - _exceptions == right._exceptions && _exclude == right._exclude && - _timeperiod_name == right._timeperiod_name && - _timeranges == right._timeranges); + return object::operator==(right) && _alias == right._alias && + _exceptions == right._exceptions && _exclude == right._exclude && + _timeperiod_name == right._timeperiod_name && + _timeranges == right._timeranges; } /** @@ -139,7 +138,7 @@ void timeperiod::check_validity() const { * * @return The time period name. */ -timeperiod::key_type const& timeperiod::key() const throw() { +timeperiod::key_type const& timeperiod::key() const noexcept { return _timeperiod_name; } @@ -199,12 +198,11 @@ bool timeperiod::parse(std::string const& line) { if (pos == std::string::npos) return false; std::string key(line.substr(0, pos)); - std::string value(line.substr(pos + 1)); - string::trim(value); + std::string value(absl::StripAsciiWhitespace(line.substr(pos + 1))); if (object::parse(key.c_str(), value.c_str()) || - parse(key.c_str(), string::trim(value).c_str()) || - _add_calendar_date(line) || _add_other_date(line)) + parse(key.c_str(), value.c_str()) || _add_calendar_date(line) || + _add_other_date(line)) return true; return false; } @@ -214,7 +212,7 @@ bool timeperiod::parse(std::string const& line) { * * @return The alias value. */ -std::string const& timeperiod::alias() const throw() { +std::string const& timeperiod::alias() const noexcept { return _alias; } @@ -223,7 +221,7 @@ std::string const& timeperiod::alias() const throw() { * * @return The exceptions value. */ -exception_array const& timeperiod::exceptions() const throw() { +exception_array const& timeperiod::exceptions() const noexcept { return _exceptions; } @@ -232,7 +230,7 @@ exception_array const& timeperiod::exceptions() const throw() { * * @return The exclude value. */ -set_string const& timeperiod::exclude() const throw() { +set_string const& timeperiod::exclude() const noexcept { return *_exclude; } @@ -241,7 +239,7 @@ set_string const& timeperiod::exclude() const throw() { * * @return The timeperiod_name value. */ -std::string const& timeperiod::timeperiod_name() const throw() { +std::string const& timeperiod::timeperiod_name() const noexcept { return _timeperiod_name; } @@ -264,19 +262,17 @@ days_array const& timeperiod::timeranges() const { */ bool timeperiod::_build_timeranges(std::string const& line, timerange_list& timeranges) { - list_string timeranges_str; - string::split(line, timeranges_str, ','); - for (list_string::const_iterator it(timeranges_str.begin()), - end(timeranges_str.end()); - it != end; ++it) { - std::size_t pos(it->find('-')); + auto timeranges_str = absl::StrSplit(line, ','); + for (auto tr : timeranges_str) { + tr = absl::StripAsciiWhitespace(tr); + std::size_t pos(tr.find('-')); if (pos == std::string::npos) return false; unsigned long start_time; - if (!_build_time_t(it->substr(0, pos), start_time)) + if (!_build_time_t(tr.substr(0, pos), start_time)) return false; unsigned long end_time; - if (!_build_time_t(it->substr(pos + 1), end_time)) + if (!_build_time_t(tr.substr(pos + 1), end_time)) return false; timeranges.emplace_back(start_time, end_time); } @@ -291,16 +287,15 @@ bool timeperiod::_build_timeranges(std::string const& line, * * @return True on success, otherwise false. */ -bool timeperiod::_build_time_t(std::string const& time_str, - unsigned long& ret) { +bool timeperiod::_build_time_t(std::string_view time_str, unsigned long& ret) { std::size_t pos(time_str.find(':')); if (pos == std::string::npos) return false; unsigned long hours; - if (!string::to(time_str.substr(0, pos).c_str(), hours)) + if (!absl::SimpleAtoi(time_str.substr(0, pos), &hours)) return false; unsigned long minutes; - if (!string::to(time_str.substr(pos + 1).c_str(), minutes)) + if (!absl::SimpleAtoi(time_str.substr(pos + 1), &minutes)) return false; ret = hours * 3600 + minutes * 60; return true; @@ -316,7 +311,7 @@ bool timeperiod::_build_time_t(std::string const& time_str, * @return True on success, otherwise false. */ bool timeperiod::_has_similar_daterange(std::list const& lst, - daterange const& range) throw() { + daterange const& range) noexcept { for (std::list::const_iterator it(lst.begin()), end(lst.end()); it != end; ++it) if (it->is_date_data_equal(range)) @@ -594,7 +589,7 @@ bool timeperiod::_add_week_day(std::string const& key, * @return True on success, otherwise false. */ bool timeperiod::_get_month_id(std::string const& name, unsigned int& id) { - static std::string const months[] = { + static std::string_view const months[] = { "january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"}; for (id = 0; id < sizeof(months) / sizeof(months[0]); ++id) diff --git a/engine/src/macros/grab_value.cc b/engine/src/macros/grab_value.cc index 4db663943a7..e1dfb22a00a 100644 --- a/engine/src/macros/grab_value.cc +++ b/engine/src/macros/grab_value.cc @@ -376,7 +376,7 @@ static int handle_contact_macro(nagios_macros* mac, * * @return OK on success. */ -static int handle_contactgroup_macro(nagios_macros* mac, +static int handle_contactgroup_macro(nagios_macros* mac [[maybe_unused]], int macro_type, const std::string& arg1, const std::string& arg2, diff --git a/engine/tests/timeperiod/get_next_valid_time/exceptions_test.cc b/engine/tests/timeperiod/get_next_valid_time/exceptions_test.cc index a07a7f09956..8f08a0f3276 100644 --- a/engine/tests/timeperiod/get_next_valid_time/exceptions_test.cc +++ b/engine/tests/timeperiod/get_next_valid_time/exceptions_test.cc @@ -1,26 +1,27 @@ /** -* Copyright 2022 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2022 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include #include "../../timeperiod/utils.hh" #include "com/centreon/engine/configuration/applier/timeperiod.hh" #include "com/centreon/engine/configuration/timeperiod.hh" #include "com/centreon/engine/exceptions/error.hh" +#include "com/centreon/engine/string.hh" #include "com/centreon/engine/timeperiod.hh" #include "helper.hh" diff --git a/tests/bam/bam_pb.robot b/tests/bam/bam_pb.robot index cda287efeb2..ff912f90bdf 100644 --- a/tests/bam/bam_pb.robot +++ b/tests/bam/bam_pb.robot @@ -907,14 +907,13 @@ BEPB_BA_DURATION_EVENT Ctn Start engine # KPI set to critical - # as GetCurrent Date floor milliseconds to upper or lower integer, we substract 1s ${start_event} Ctn Get Round Current Date Ctn Process Service Result Hard host_16 service_314 2 output critical for 314 - ${result} Ctn Check Service Status With Timeout host_16 service_314 2 60 HARD + ${result} Ctn Check Service Resource Status With Timeout host_16 service_314 2 60 HARD Should Be True ${result} The service (host_16,service_314) is not CRITICAL as expected Sleep 2s Ctn Process Service Check Result host_16 service_314 0 output ok for 314 - ${result} Ctn Check Service Status With Timeout host_16 service_314 0 60 HARD + ${result} Ctn Check Service Resource Status With Timeout host_16 service_314 0 60 HARD Should Be True ${result} The service (host_16,service_314) is not OK as expected ${end_event} Get Current Date result_format=epoch @@ -926,6 +925,13 @@ BEPB_BA_DURATION_EVENT IF "${output}" != "()" BREAK END + IF "${output}" == "()" + Log To Console "Bad return for this test, the content of the table is" + ${output} Query + ... SELECT start_time, end_time, duration, sla_duration, timeperiod_is_default FROM mod_bam_reporting_ba_events_durations + Log To Console ${output} + END + Should Be True "${output}" != "()" No row recorded in mod_bam_reporting_ba_events_durations with ba_event_id=1 Should Be True ${output[0][2]} == ${output[0][1]} - ${output[0][0]} Should Be True ${output[0][3]} == ${output[0][1]} - ${output[0][0]} Should Be True ${output[0][4]} == 1 diff --git a/tests/broker-engine/notifications.robot b/tests/broker-engine/notifications.robot index 4507bb646b3..6414796b0f7 100644 --- a/tests/broker-engine/notifications.robot +++ b/tests/broker-engine/notifications.robot @@ -1037,7 +1037,7 @@ not15 Ctn Kindly Stop Broker not16 - [Documentation] notification for a dependensies services group + [Documentation] notification for dependencies services group [Tags] broker engine services unified_sql Ctn Clear Commands Status Ctn Config Engine ${1} ${4} ${1} diff --git a/tests/resources/resources.resource b/tests/resources/resources.resource index 87575a8ce96..f53d7f6ff08 100644 --- a/tests/resources/resources.resource +++ b/tests/resources/resources.resource @@ -195,12 +195,11 @@ Ctn Stop Custom Engine ... ${result.rc} == -15 or ${result.rc} == 0 ... Engine badly stopped alias = ${process_alias} - code returned ${result.rc}. -Ctn Stop engine +Ctn Stop Engine Log To Console "stop centengine" ${count} Ctn Get Engines Count FOR ${idx} IN RANGE 0 ${count} - ${alias} Catenate SEPARATOR= e ${idx} - Send Signal To Process SIGTERM ${alias} + Send Signal To Process SIGTERM e${idx} END FOR ${idx} IN RANGE 0 ${count} ${alias} Catenate SEPARATOR= e ${idx} From 0845e3d2fea628532025fe80635c0a141c0fb678 Mon Sep 17 00:00:00 2001 From: jean-christophe81 <98889244+jean-christophe81@users.noreply.github.com> Date: Fri, 7 Jun 2024 10:08:11 +0200 Subject: [PATCH 29/60] cleanup(engine): configuration simplified REFS: MON-59116 --- engine/CMakeLists.txt | 1 + .../centreon/engine/commands/otel_command.hh | 3 +- .../engine/commands/otel_interface.hh | 10 + .../opentelemetry/doc/opentelemetry.md | 17 +- .../modules/opentelemetry/open_telemetry.hh | 4 + .../modules/opentelemetry/otl_converter.hh | 24 ++- .../modules/opentelemetry/otl_data_point.hh | 24 +++ .../telegraf/nagios_converter.hh | 16 +- .../opentelemetry/precomp_inc/precomp.hh | 4 + .../opentelemetry/src/host_serv_extractor.cc | 165 +++++++-------- .../opentelemetry/src/open_telemetry.cc | 31 ++- .../modules/opentelemetry/src/otl_config.cc | 18 +- .../opentelemetry/src/otl_converter.cc | 92 ++++---- .../opentelemetry/src/telegraf/conf_server.cc | 200 +++++++++--------- .../src/telegraf/nagios_converter.cc | 5 +- engine/src/commands/otel_command.cc | 71 ++++--- engine/src/configuration/applier/connector.cc | 6 +- engine/tests/CMakeLists.txt | 5 +- .../opentelemetry/host_serv_extractor_test.cc | 62 ++---- .../tests/opentelemetry/opentelemetry_test.cc | 57 +++-- .../tests/opentelemetry/otl_converter_test.cc | 8 +- tests/README.md | 2 +- tests/broker-engine/opentelemetry.robot | 40 ++-- tests/resources/opentelemetry/telegraf1.conf | 36 ++++ tests/resources/opentelemetry/telegraf2.conf | 27 +++ tests/update-doc.py | 2 +- vcpkg.json | 1 + 27 files changed, 553 insertions(+), 378 deletions(-) create mode 100644 tests/resources/opentelemetry/telegraf1.conf create mode 100644 tests/resources/opentelemetry/telegraf2.conf diff --git a/engine/CMakeLists.txt b/engine/CMakeLists.txt index ab0eedb767b..6b10ba0401a 100644 --- a/engine/CMakeLists.txt +++ b/engine/CMakeLists.txt @@ -532,6 +532,7 @@ target_link_libraries( boost_url cce_core gRPC::grpc++ + boost_program_options "-Wl,--no-whole-archive" gRPC::gpr gRPC::grpc diff --git a/engine/inc/com/centreon/engine/commands/otel_command.hh b/engine/inc/com/centreon/engine/commands/otel_command.hh index 4f73152e7db..bc566328bb8 100644 --- a/engine/inc/com/centreon/engine/commands/otel_command.hh +++ b/engine/inc/com/centreon/engine/commands/otel_command.hh @@ -43,11 +43,11 @@ class otel_command : public command, static otel_command_container _commands; std::shared_ptr _extractor; + std::shared_ptr _conv_conf; std::shared_ptr _logger; void init(); - void reset_extractor(); public: static void create(const std::string& connector_name, @@ -65,7 +65,6 @@ class otel_command : public command, static void clear(); static void init_all(); - static void reset_all_extractor(); static const otel_command_container& get_otel_commands() { return _commands; } diff --git a/engine/inc/com/centreon/engine/commands/otel_interface.hh b/engine/inc/com/centreon/engine/commands/otel_interface.hh index 1f5801d51e4..8a208e6fb82 100644 --- a/engine/inc/com/centreon/engine/commands/otel_interface.hh +++ b/engine/inc/com/centreon/engine/commands/otel_interface.hh @@ -110,6 +110,12 @@ host_serv_metric host_serv_list::is_allowed(const host_set& hosts, class host_serv_extractor { public: virtual ~host_serv_extractor() = default; + +}; + +class converter_config { + public: + virtual ~converter_config() = default; }; using result_callback = std::function; @@ -135,7 +141,11 @@ class open_telemetry_base const std::string& cmdline, const host_serv_list::pointer& host_serv_list) = 0; + virtual std::shared_ptr create_converter_config( + const std::string& cmd_line) = 0; + virtual bool check(const std::string& processed_cmd, + const std::shared_ptr& conv_conf, uint64_t command_id, nagios_macros& macros, uint32_t timeout, diff --git a/engine/modules/opentelemetry/doc/opentelemetry.md b/engine/modules/opentelemetry/doc/opentelemetry.md index 642e2439a04..0fab609effc 100644 --- a/engine/modules/opentelemetry/doc/opentelemetry.md +++ b/engine/modules/opentelemetry/doc/opentelemetry.md @@ -148,7 +148,7 @@ In this file there are grpc server parameters and some other parameters. telegraf can start nagios plugins and send results to engine. So centreon opentelemetry library has two classes, one to convert telegraf nagios output to service check, and an http(s) server that gives to telegraf his configuration according to engine configuration. First telegraf service commands must use opentelemetry fake connector and have a command line like: ``` -nagios_telegraf --cmd_line /usr/lib/nagios/plugins/check_icmp 127.0.0.1 +/usr/lib/nagios/plugins/check_icmp 127.0.0.1 ``` When telegraf conf server receive an http request with one or several hosts in get parameters `http://localhost:1443/engine?host=host_1`, it searches open telemetry commands in host and service list and returns a configuration file in response body. The problem of asio http server is that request handler are called by asio thread, so we use command_line_manager to scan hosts and service in a thread safe manner. @@ -162,7 +162,7 @@ An example of configuration: } define command { command_name otel_check_icmp - command_line nagios_telegraf --cmd_line /usr/lib/nagios/plugins/check_icmp 127.0.0.1 + command_line /usr/lib/nagios/plugins/check_icmp 127.0.0.1 connector OTEL connector } ``` @@ -170,7 +170,7 @@ An example of configuration: ``` define connector { connector_name OTEL connector - connector_line open_telemetry attributes --host_attribute=data_point --host_key=host --service_attribute=data_point --service_key=service + connector_line open_telemetry --processor=nagios_telegraf --extractor=attributes --host_path=resourceMetrics.scopeMetrics.metrics.dataPoints.attributes.host --service_path=resourceMetrics.scopeMetrics.metrics.dataPoints.attributes.service } ``` - centengine.cfg: @@ -196,11 +196,14 @@ An example of configuration: }, "max_length_grpc_log": 0, "telegraf_conf_server": { - "port": 1443, - "encryption": true, + "http_server" : { + "port": 1443, + "encryption": true, + "certificate_path": "server.crt", + "key_path": "server.key" + }, "engine_otel_endpoint": "172.17.0.1:4317", - "certificate_path": "server.crt", - "key_path": "server.key" + "check_interval":60 } } ``` diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/open_telemetry.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/open_telemetry.hh index 1792cc5c402..fe3f928fdc6 100644 --- a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/open_telemetry.hh +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/open_telemetry.hh @@ -127,6 +127,7 @@ class open_telemetry : public commands::otel::open_telemetry_base { static void unload(const std::shared_ptr& logger); bool check(const std::string& processed_cmd, + const std::shared_ptr& conv_conf, uint64_t command_id, nagios_macros& macros, uint32_t timeout, @@ -136,6 +137,9 @@ class open_telemetry : public commands::otel::open_telemetry_base { std::shared_ptr create_extractor( const std::string& cmdline, const commands::otel::host_serv_list::pointer& host_serv_list) override; + + std::shared_ptr create_converter_config( + const std::string& cmd_line) override; }; } // namespace com::centreon::engine::modules::opentelemetry diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_converter.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_converter.hh index 7a7065ce1ef..0152ba75ef1 100644 --- a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_converter.hh +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_converter.hh @@ -26,6 +26,24 @@ namespace com::centreon::engine::modules::opentelemetry { class data_point_fifo_container; +/** + * @brief converter are asynchronous object created on each check + * In order to not parse command line on each check, we parse it once and then + * create a converter config that will be used to create converter + * + */ +class converter_config : public commands::otel::converter_config { + public: + enum class converter_type { nagios_converter }; + + private: + const converter_type _type; + + public: + converter_config(converter_type conv_type) : _type(conv_type) {} + converter_type get_type() const { return _type; } +}; + /** * @brief The goal of this converter is to convert otel metrics in result * This object is synchronous and asynchronous @@ -58,8 +76,6 @@ class otl_converter : public std::enable_shared_from_this { virtual ~otl_converter() = default; - static std::string remove_converter_type(const std::string& cmd_line); - const std::string& get_cmd_line() const { return _cmd_line; } uint64_t get_command_id() const { return _command_id; } @@ -87,12 +103,16 @@ class otl_converter : public std::enable_shared_from_this { static std::shared_ptr create( const std::string& cmd_line, + const std::shared_ptr& conf, uint64_t command_id, const host& host, const service* service, std::chrono::system_clock::time_point timeout, commands::otel::result_callback&& handler, const std::shared_ptr& logger); + + static std::shared_ptr create_converter_config( + const std::string& cmd_line); }; } // namespace com::centreon::engine::modules::opentelemetry diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_data_point.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_data_point.hh index 0011fc1617a..205a3acf625 100644 --- a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_data_point.hh +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_data_point.hh @@ -21,6 +21,30 @@ namespace com::centreon::engine::modules::opentelemetry { +/** + * @brief the goal of this little template is to pass an initializer at object + * construction + * Example: + * @code {.c++} + * static initialized_data_class desc( + * [](po::options_description& desc) { + * desc.add_options()("extractor", po::value(), + * "extractor type"); + * }); + * + * @endcode + * + * + * @tparam data_class + */ +template +struct initialized_data_class : public data_class { + template + initialized_data_class(initializer_type&& initializer) { + initializer(*this); + } +}; + /** * @brief pair with host_name in first and serv in second * diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/telegraf/nagios_converter.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/telegraf/nagios_converter.hh index af684268f1c..dc3b36fcbc9 100644 --- a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/telegraf/nagios_converter.hh +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/telegraf/nagios_converter.hh @@ -91,19 +91,19 @@ namespace com::centreon::engine::modules::opentelemetry::telegraf { * * */ -class otl_nagios_converter : public otl_converter { +class nagios_converter : public otl_converter { protected: bool _build_result_from_metrics(metric_name_to_fifo& fifos, commands::result& res) override; public: - otl_nagios_converter(const std::string& cmd_line, - uint64_t command_id, - const host& host, - const service* service, - std::chrono::system_clock::time_point timeout, - commands::otel::result_callback&& handler, - const std::shared_ptr& logger) + nagios_converter(const std::string& cmd_line, + uint64_t command_id, + const host& host, + const service* service, + std::chrono::system_clock::time_point timeout, + commands::otel::result_callback&& handler, + const std::shared_ptr& logger) : otl_converter(cmd_line, command_id, host, diff --git a/engine/modules/opentelemetry/precomp_inc/precomp.hh b/engine/modules/opentelemetry/precomp_inc/precomp.hh index 1a2550abd95..67a56f7e324 100644 --- a/engine/modules/opentelemetry/precomp_inc/precomp.hh +++ b/engine/modules/opentelemetry/precomp_inc/precomp.hh @@ -30,6 +30,8 @@ #include #include +#include + #include #include #include @@ -41,6 +43,8 @@ namespace asio = boost::asio; #include #include #include +#include +namespace po = boost::program_options; #include #include diff --git a/engine/modules/opentelemetry/src/host_serv_extractor.cc b/engine/modules/opentelemetry/src/host_serv_extractor.cc index 5ac15502e42..1912a84971e 100644 --- a/engine/modules/opentelemetry/src/host_serv_extractor.cc +++ b/engine/modules/opentelemetry/src/host_serv_extractor.cc @@ -38,68 +38,36 @@ bool host_serv_extractor::is_allowed( return _host_serv_list->is_allowed(host, service_description); } -namespace com::centreon::engine::modules::opentelemetry::options { - -/** - * @brief command line parser for host_serv_attributes_extractor_config - * - */ -class host_serv_attributes_extractor_config_options - : public com::centreon::misc::get_options { - public: - host_serv_attributes_extractor_config_options(); - void parse(const std::string& cmd_line) { _parse_arguments(cmd_line); } -}; - -host_serv_attributes_extractor_config_options:: - host_serv_attributes_extractor_config_options() { - _add_argument("host_attribute", 'h', - "Where to find host attribute allowed values: resource, scope, " - "data_point", - true, true, "data_point"); - _add_argument("host_key", 'i', - "the key of attributes where we can find host name", true, true, - "host"); - _add_argument( - "service_attribute", 's', - "Where to find service attribute allowed values: resource, scope, " - "data_point", - true, true, "data_point"); - _add_argument("service_key", 't', - "the key of attributes where we can find the name of service", - true, true, "service"); -} - -}; // namespace com::centreon::engine::modules::opentelemetry::options - -/** - * @brief create host_serv_extractor according to command_line - * - * @param command_line - * @param host_serv_list list that will be shared bu host_serv_extractor and - * otel_command - * @return std::shared_ptr - */ std::shared_ptr host_serv_extractor::create( const std::string& command_line, const commands::otel::host_serv_list::pointer& host_serv_list) { - // type of the converter is the first field - size_t sep_pos = command_line.find(' '); - std::string conf_type = sep_pos == std::string::npos - ? command_line - : command_line.substr(0, sep_pos); - boost::trim(conf_type); - std::string params = - sep_pos == std::string::npos ? "" : command_line.substr(sep_pos + 1); + static initialized_data_class desc( + [](po::options_description& desc) { + desc.add_options()("extractor", po::value(), + "extractor type"); + }); - boost::trim(params); - - if (conf_type.empty() || conf_type == "attributes") { - return std::make_shared(params, - host_serv_list); - } else { - SPDLOG_LOGGER_ERROR(config_logger, "unknown converter type:{}", conf_type); - throw exceptions::msg_fmt("unknown converter type:{}", conf_type); + try { + po::variables_map vm; + po::store(po::command_line_parser(po::split_unix(command_line)) + .options(desc) + .allow_unregistered() + .run(), + vm); + if (!vm.count("extractor")) { + throw exceptions::msg_fmt("extractor flag not found in {}", command_line); + } + std::string extractor_type = vm["extractor"].as(); + if (extractor_type == "attributes") { + return std::make_shared(command_line, + host_serv_list); + } else { + throw exceptions::msg_fmt("unknown extractor in {}", command_line); + } + } catch (const std::exception& e) { + SPDLOG_LOGGER_ERROR(config_logger, "fail to parse {}: {}", command_line, + e.what()); + throw; } } @@ -115,39 +83,66 @@ host_serv_attributes_extractor::host_serv_attributes_extractor( const std::string& command_line, const commands::otel::host_serv_list::pointer& host_serv_list) : host_serv_extractor(command_line, host_serv_list) { - options::host_serv_attributes_extractor_config_options args; - args.parse(command_line); + static initialized_data_class desc( + [](po::options_description& desc) { + desc.add_options()( + "host_path", po::value(), + "where to find host name. Example: " + "resourceMetrics.scopeMetrics.metrics.dataPoints.attributes.host"); + desc.add_options()("service_path", po::value(), + "where to find service description. Example: " + "resourceMetrics.scopeMetrics.metrics.dataPoints." + "attributes.service"); + }); + + static auto parse_path = [](const std::string& path, attribute_owner& attr, + std::string& key) { + static re2::RE2 path_extractor("\\.(\\w+)\\.attributes\\.(\\w+)"); + std::string sz_attr; + if (!RE2::PartialMatch(path, path_extractor, &sz_attr, &key)) { + throw exceptions::msg_fmt( + "we expect a path like " + "resource_metrics.scope_metrics.data.data_points.attributes.host not " + "{}", + path); + } - auto parse_param = - [&args]( - const std::string& attribute, - const std::string& key) -> std::pair { - const std::string& path = args.get_argument(attribute).get_value(); - attribute_owner owner; - if (path == "resource") { - owner = attribute_owner::resource; - } else if (path == "scope") { - owner = attribute_owner::scope; + boost::to_lower(sz_attr); + if (sz_attr == "resource") { + attr = attribute_owner::resource; + } else if (sz_attr == "scope") { + attr = attribute_owner::scope; } else { - owner = attribute_owner::data_point; + attr = attribute_owner::data_point; } - - std::string ret_key = args.get_argument(key).get_value(); - return std::make_pair(owner, ret_key); }; try { - std::tie(_host_path, _host_key) = parse_param("host_attribute", "host_key"); - } catch (const std::exception&) { // default configuration - _host_path = attribute_owner::data_point; - _host_key = "host"; - } - try { - std::tie(_serv_path, _serv_key) = - parse_param("service_attribute", "service_key"); - } catch (const std::exception&) { // default configuration - _serv_path = attribute_owner::data_point; - _serv_key = "service"; + po::variables_map vm; + po::store(po::command_line_parser(po::split_unix(command_line)) + .options(desc) + .allow_unregistered() + .run(), + vm); + if (!vm.count("host_path")) { + _host_path = attribute_owner::data_point; + _host_key = "host"; + } else { + parse_path(vm["host_path"].as(), _host_path, _host_key); + } + if (!vm.count("service_path")) { + _serv_path = attribute_owner::data_point; + _serv_key = "service"; + } else { + parse_path(vm["service_path"].as(), _serv_path, _serv_key); + } + } catch (const std::exception& e) { + std::ostringstream options_allowed; + options_allowed << desc; + SPDLOG_LOGGER_ERROR(config_logger, + "fail to parse {}: {}\nallowed options: {}", + command_line, e.what(), options_allowed.str()); + throw; } } diff --git a/engine/modules/opentelemetry/src/open_telemetry.cc b/engine/modules/opentelemetry/src/open_telemetry.cc index 93cc90e18ba..478564393bd 100644 --- a/engine/modules/opentelemetry/src/open_telemetry.cc +++ b/engine/modules/opentelemetry/src/open_telemetry.cc @@ -262,6 +262,20 @@ open_telemetry::create_extractor( } } +/** + * @brief converter is created for each check, so in order to not parse otel + * connector command line on each check , we create a converter_config + * object that is used to create converter it search the flag extractor + * + * @param cmd_line + * @return + * std::shared_ptr + */ +std::shared_ptr +open_telemetry::create_converter_config(const std::string& cmd_line) { + return otl_converter::create_converter_config(cmd_line); +} + /** * @brief simulate a check by reading in metrics fifos * It creates an otel_converter, the first word of processed_cmd is the name @@ -279,16 +293,19 @@ open_telemetry::create_extractor( * timeout * @throw if converter type is unknown */ -bool open_telemetry::check(const std::string& processed_cmd, - uint64_t command_id, - nagios_macros& macros, - uint32_t timeout, - commands::result& res, - commands::otel::result_callback&& handler) { +bool open_telemetry::check( + const std::string& processed_cmd, + const std::shared_ptr& conv_config, + uint64_t command_id, + nagios_macros& macros, + uint32_t timeout, + commands::result& res, + commands::otel::result_callback&& handler) { std::shared_ptr to_use; try { to_use = otl_converter::create( - processed_cmd, command_id, *macros.host_ptr, macros.service_ptr, + processed_cmd, std::static_pointer_cast(conv_config), + command_id, *macros.host_ptr, macros.service_ptr, std::chrono::system_clock::now() + std::chrono::seconds(timeout), std::move(handler), _logger); } catch (const std::exception& e) { diff --git a/engine/modules/opentelemetry/src/otl_config.cc b/engine/modules/opentelemetry/src/otl_config.cc index 96a5fb024de..f75d0c9ab28 100644 --- a/engine/modules/opentelemetry/src/otl_config.cc +++ b/engine/modules/opentelemetry/src/otl_config.cc @@ -17,6 +17,7 @@ */ #include "com/centreon/common/rapidjson_helper.hh" +#include "com/centreon/engine/globals.hh" #include "otl_config.hh" #include "otl_fmt.hh" @@ -54,7 +55,7 @@ static constexpr std::string_view _grpc_config_schema(R"( "type": "integer", "min": 1 }, - "server": { + "otel_server": { "description": "otel grpc config", "type": "object" }, @@ -64,7 +65,7 @@ static constexpr std::string_view _grpc_config_schema(R"( } }, "required": [ - "server" + "otel_server" ], "type": "object" } @@ -80,8 +81,14 @@ static constexpr std::string_view _grpc_config_schema(R"( otl_config::otl_config(const std::string_view& file_path, asio::io_context& io_context) { static json_validator validator(_grpc_config_schema); - rapidjson::Document file_content_d = - rapidjson_helper::read_from_file(file_path); + rapidjson::Document file_content_d; + try { + file_content_d = rapidjson_helper::read_from_file(file_path); + } catch (const std::exception& e) { + SPDLOG_LOGGER_ERROR(config_logger, "incorrect json file {}: {}", file_path, + e.what()); + throw; + } rapidjson_helper file_content(file_content_d); @@ -90,7 +97,8 @@ otl_config::otl_config(const std::string_view& file_path, _json_grpc_log = file_content.get_bool("grpc_json_log", false); _second_fifo_expiry = file_content.get_unsigned("second_fifo_expiry", 600); _max_fifo_size = file_content.get_unsigned("max_fifo_size", 5); - _grpc_conf = std::make_shared(file_content.get_member("server")); + _grpc_conf = + std::make_shared(file_content.get_member("otel_server")); if (file_content.has_member("telegraf_conf_server")) { _telegraf_conf_server_config = std::make_shared( diff --git a/engine/modules/opentelemetry/src/otl_converter.cc b/engine/modules/opentelemetry/src/otl_converter.cc index 4b71563244f..9f45e962b12 100644 --- a/engine/modules/opentelemetry/src/otl_converter.cc +++ b/engine/modules/opentelemetry/src/otl_converter.cc @@ -28,22 +28,6 @@ using namespace com::centreon::engine::modules::opentelemetry; -/** - * @brief create a otl_converter_config from a command line - * first field identify type of config - * Example: - * @code {.c++} - * std::shared_ptr conf = - * otl_converter_config::load("nagios_telegraf"); - * @endcode - * - * @param cmd_line - * @return std::shared_ptr - * @throw if cmd_line can't be parsed - */ -/****************************************************************** - * otl_converter base - ******************************************************************/ otl_converter::otl_converter(const std::string& cmd_line, uint64_t command_id, const host& host, @@ -111,38 +95,37 @@ void otl_converter::async_time_out() { * Example: * @code {.c++} * std::shared_ptr converter = - * otl_converter::create("nagios_telegraf --fifo_depth=5", 5, *host, serv, + * otl_converter::create("--processor=nagios_telegraf --fifo_depth=5", conf, 5, *host, serv, * timeout_point, [](const commads::result &res){}, _logger); * @endcode * * @param cmd_line + * @param conf bean configuration object created by create_converter_config * @param command_id * @param host * @param service * @param timeout - * @param handler + * @param handler handler that will be called once we have all metrics mandatory + * to create a check_result * @return std::shared_ptr */ std::shared_ptr otl_converter::create( const std::string& cmd_line, + const std::shared_ptr& conf, uint64_t command_id, const host& host, const service* service, std::chrono::system_clock::time_point timeout, commands::otel::result_callback&& handler, const std::shared_ptr& logger) { - // type of the converter is the first field - size_t sep_pos = cmd_line.find(' '); - std::string conf_type = - sep_pos == std::string::npos ? cmd_line : cmd_line.substr(0, sep_pos); - boost::trim(conf_type); - if (conf_type == "nagios_telegraf") { - return std::make_shared( - cmd_line, command_id, host, service, timeout, std::move(handler), - logger); - } else { - SPDLOG_LOGGER_ERROR(config_logger, "unknown converter type:{}", conf_type); - throw exceptions::msg_fmt("unknown converter type:{}", conf_type); + switch (conf->get_type()) { + case converter_config::converter_type::nagios_converter: + return std::make_shared( + cmd_line, command_id, host, service, timeout, std::move(handler), + logger); + default: + SPDLOG_LOGGER_ERROR(logger, "unknown converter type:{}", cmd_line); + throw exceptions::msg_fmt("unknown converter type:{}", cmd_line); } } @@ -158,16 +141,47 @@ void otl_converter::dump(std::string& output) const { } /** - * @brief remove converter_type from command_line + * @brief create a otl_converter_config from a command line + * --processor flag identifies type of converter + * Example: + * @code {.c++} + * std::shared_ptr converter = + * otl_converter::create("--processor=nagios_telegraf --fifo_depth=5"); + * @endcode * - * @param cmd_line exemple nagios_telegraf - * @return std::string + * @param cmd_line + * @return std::shared_ptr */ -std::string otl_converter::remove_converter_type(const std::string& cmd_line) { - size_t sep_pos = cmd_line.find(' '); - std::string params = - sep_pos == std::string::npos ? "" : cmd_line.substr(sep_pos + 1); +std::shared_ptr otl_converter::create_converter_config( + const std::string& cmd_line) { + static initialized_data_class desc( + [](po::options_description& desc) { + desc.add_options()("processor", po::value(), + "processor type"); + }); - boost::trim(params); - return params; + try { + po::variables_map vm; + po::store(po::command_line_parser(po::split_unix(cmd_line)) + .options(desc) + .allow_unregistered() + .run(), + vm); + if (!vm.count("processor")) { + throw exceptions::msg_fmt("processor flag not found in {}", cmd_line); + } + std::string extractor_type = vm["processor"].as(); + if (extractor_type == "nagios_telegraf") { + return std::make_shared( + converter_config::converter_type::nagios_converter); + } else { + throw exceptions::msg_fmt("unknown processor in {}", cmd_line); + } + } catch (const std::exception& e) { + SPDLOG_LOGGER_ERROR( + config_logger, + "fail to get opentelemetry converter configuration from {}: {}", + cmd_line, e.what()); + throw; + } } diff --git a/engine/modules/opentelemetry/src/telegraf/conf_server.cc b/engine/modules/opentelemetry/src/telegraf/conf_server.cc index 2de14030234..48646b4b1ee 100644 --- a/engine/modules/opentelemetry/src/telegraf/conf_server.cc +++ b/engine/modules/opentelemetry/src/telegraf/conf_server.cc @@ -39,42 +39,44 @@ static constexpr std::string_view _config_schema(R"( "$schema": "http://json-schema.org/draft-04/schema#", "title": "grpc config", "properties": { - "listen_address": { - "description": "IP", - "type": "string", - "minLength": 5 - }, - "port": { - "description": "port to listen", - "type": "integer", - "minimum": 80, - "maximum": 65535 + "http_server" : { + "listen_address": { + "description": "IP", + "type": "string", + "minLength": 5 + }, + "port": { + "description": "port to listen", + "type": "integer", + "minimum": 80, + "maximum": 65535 + }, + "encryption": { + "description": "true if https", + "type": "boolean" + }, + "keepalive_interval": { + "description": "delay between 2 keepalive tcp packet, 0 no keepalive packets", + "type": "integer", + "minimum": 0, + "maximum": 3600 + }, + "certificate_path": { + "description": "path of the certificate file of the server", + "type": "string", + "minLength": 5 + }, + "key_path": { + "description": "path of the key file", + "type": "string", + "minLength": 5 + } }, "check_interval": { "description": "interval in seconds between two checks (param [agent] interval) ", "type": "integer", "minimum": 10 }, - "encryption": { - "description": "true if https", - "type": "boolean" - }, - "keepalive_interval": { - "description": "delay between 2 keepalive tcp packet, 0 no keepalive packets", - "type": "integer", - "minimum": 0, - "maximum": 3600 - }, - "certificate_path": { - "description": "path of the certificate file", - "type": "string", - "minLength": 5 - }, - "key_path": { - "description": "path of the key file", - "type": "string", - "minLength": 5 - }, "engine_otel_endpoint": { "description": "opentelemetry engine grpc server", "type": "string", @@ -101,66 +103,79 @@ conf_server_config::conf_server_config(const rapidjson::Value& json_config_v, e.what()); throw; } - std::string listen_address = - json_config.get_string("listen_address", "0.0.0.0"); - _crypted = json_config.get_bool("encryption", false); - unsigned port = json_config.get_unsigned("port", _crypted ? 443 : 80); - asio::ip::tcp::resolver::query query(listen_address, std::to_string(port)); - asio::ip::tcp::resolver resolver(io_context); - boost::system::error_code ec; - asio::ip::tcp::resolver::iterator it = resolver.resolve(query, ec), end; - if (ec) { - throw exceptions::msg_fmt("unable to resolve {}:{}", listen_address, port); - } - if (it == end) { - throw exceptions::msg_fmt("no ip found for {}:{}", listen_address, port); - } - _listen_endpoint = it->endpoint(); - - _second_keep_alive_interval = - json_config.get_unsigned("keepalive_interval", 30); - _check_interval = json_config.get_unsigned("check_interval", 60); - _certificate_path = json_config.get_string("certificate_path", ""); - _key_path = json_config.get_string("key_path", ""); _engine_otl_endpoint = json_config.get_string("engine_otel_endpoint"); - if (_crypted) { - if (_certificate_path.empty()) { - SPDLOG_LOGGER_ERROR( - config_logger, - "telegraf conf server encryption activated and no certificate path " - "provided"); - throw exceptions::msg_fmt( - "telegraf conf server encryption activated and no certificate path " - "provided"); - } - if (_key_path.empty()) { - SPDLOG_LOGGER_ERROR(config_logger, - "telegraf conf server encryption activated and no " - "certificate key path provided"); - - throw exceptions::msg_fmt( - "telegraf conf server encryption activated and no certificate key " - "path provided"); + _check_interval = json_config.get_unsigned("check_interval", 60); + + if (json_config_v.HasMember("http_server")) { + common::rapidjson_helper http_json_config( + json_config.get_member("http_server")); + std::string listen_address = + http_json_config.get_string("listen_address", "0.0.0.0"); + _crypted = http_json_config.get_bool("encryption", false); + unsigned port = http_json_config.get_unsigned("port", _crypted ? 443 : 80); + asio::ip::tcp::resolver::query query(listen_address, std::to_string(port)); + asio::ip::tcp::resolver resolver(io_context); + boost::system::error_code ec; + asio::ip::tcp::resolver::iterator it = resolver.resolve(query, ec), end; + if (ec) { + throw exceptions::msg_fmt("unable to resolve {}:{}", listen_address, + port); } - if (::access(_certificate_path.c_str(), R_OK)) { - SPDLOG_LOGGER_ERROR( - config_logger, - "telegraf conf server unable to read certificate file {}", - _certificate_path); - throw exceptions::msg_fmt( - "telegraf conf server unable to read certificate file {}", - _certificate_path); + if (it == end) { + throw exceptions::msg_fmt("no ip found for {}:{}", listen_address, port); } - if (::access(_key_path.c_str(), R_OK)) { - SPDLOG_LOGGER_ERROR( - config_logger, - "telegraf conf server unable to read certificate key file {}", - _key_path); - throw exceptions::msg_fmt( - "telegraf conf server unable to read certificate key file {}", - _key_path); + + _listen_endpoint = it->endpoint(); + + _second_keep_alive_interval = + http_json_config.get_unsigned("keepalive_interval", 30); + _certificate_path = http_json_config.get_string("certificate_path", ""); + _key_path = http_json_config.get_string("key_path", ""); + if (_crypted) { + if (_certificate_path.empty()) { + SPDLOG_LOGGER_ERROR(config_logger, + "telegraf conf server encryption activated and no " + "certificate path " + "provided"); + throw exceptions::msg_fmt( + "telegraf conf server encryption activated and no certificate " + "path " + "provided"); + } + if (_key_path.empty()) { + SPDLOG_LOGGER_ERROR(config_logger, + "telegraf conf server encryption activated and no " + "certificate key path provided"); + + throw exceptions::msg_fmt( + "telegraf conf server encryption activated and no certificate key " + "path provided"); + } + if (::access(_certificate_path.c_str(), R_OK)) { + SPDLOG_LOGGER_ERROR( + config_logger, + "telegraf conf server unable to read certificate file {}", + _certificate_path); + throw exceptions::msg_fmt( + "telegraf conf server unable to read certificate file {}", + _certificate_path); + } + if (::access(_key_path.c_str(), R_OK)) { + SPDLOG_LOGGER_ERROR( + config_logger, + "telegraf conf server unable to read certificate key file {}", + _key_path); + throw exceptions::msg_fmt( + "telegraf conf server unable to read certificate key file {}", + _key_path); + } } + } else { + _listen_endpoint = asio::ip::tcp::endpoint(asio::ip::address_v4::any(), 80); + _second_keep_alive_interval = 30; + _check_interval = 60; + _crypted = false; } } @@ -261,18 +276,7 @@ bool conf_session::_otel_command_to_stream( const std::string& host, const std::string& service, std::string& to_append) { - constexpr std::string_view flag = "--cmd_line"; - std::string plugins_cmdline; - size_t flag_pos = cmd_line.find(flag); - if (flag_pos != std::string::npos) { - plugins_cmdline = cmd_line.substr(flag_pos + flag.length() + 1); - boost::trim(plugins_cmdline); - } else { - SPDLOG_LOGGER_ERROR(this->_logger, - "host: {}, serv: {}, no --cmd_line found in {}", host, - service, cmd_line); - return false; - } + std::string plugins_cmdline = boost::trim_copy(cmd_line); if (plugins_cmdline.empty()) { SPDLOG_LOGGER_ERROR(this->_logger, @@ -432,4 +436,4 @@ void conf_session::answer_to_request( namespace com::centreon::engine::modules::opentelemetry::telegraf { template class conf_session; template class conf_session; -}; // namespace com::centreon::engine::modules::opentelemetry::telegraf \ No newline at end of file +}; // namespace com::centreon::engine::modules::opentelemetry::telegraf diff --git a/engine/modules/opentelemetry/src/telegraf/nagios_converter.cc b/engine/modules/opentelemetry/src/telegraf/nagios_converter.cc index 53dfc06832c..1078ee3e8e3 100644 --- a/engine/modules/opentelemetry/src/telegraf/nagios_converter.cc +++ b/engine/modules/opentelemetry/src/telegraf/nagios_converter.cc @@ -158,9 +158,8 @@ static std::string_view get_nagios_telegraf_suffix( * check_icmp_state * @return com::centreon::engine::commands::result */ -bool otl_nagios_converter::_build_result_from_metrics( - metric_name_to_fifo& fifos, - commands::result& res) { +bool nagios_converter::_build_result_from_metrics(metric_name_to_fifo& fifos, + commands::result& res) { // first we search last state timestamp uint64_t last_time = 0; diff --git a/engine/src/commands/otel_command.cc b/engine/src/commands/otel_command.cc index ae0e70b94f2..bab48809b64 100644 --- a/engine/src/commands/otel_command.cc +++ b/engine/src/commands/otel_command.cc @@ -108,16 +108,6 @@ void otel_command::init_all() { } } -/** - * @brief to call after otel module unload - * - */ -void otel_command::reset_all_extractor() { - for (auto& to_init : _commands) { - to_init.second->reset_extractor(); - } -} - /** * @brief Construct a new otel command::otel command object * at engine startup, otel module is not yet loaded @@ -182,6 +172,14 @@ uint64_t otel_command::run(const std::string& processed_cmd, return command_id; } + if (!_conv_conf) { + SPDLOG_LOGGER_ERROR( + _logger, "{} unable to do a check without a converter configuration", + get_name()); + throw exceptions::msg_fmt( + "{} unable to do a check without a converter configuration", + get_name()); + } SPDLOG_LOGGER_TRACE(_logger, "otel_command::async_run: connector='{}', command_id={}, " "cmd='{}', timeout={}", @@ -189,7 +187,7 @@ uint64_t otel_command::run(const std::string& processed_cmd, result res; bool res_available = otel->check( - processed_cmd, command_id, macros, timeout, res, + processed_cmd, _conv_conf, command_id, macros, timeout, res, [me = shared_from_this(), command_id](const result& async_res) { SPDLOG_LOGGER_TRACE( me->_logger, "otel_command async_run callback: connector='{}' {}", @@ -248,11 +246,12 @@ void otel_command::run(const std::string& processed_cmd, std::condition_variable cv; std::mutex cv_m; - bool res_available = otel->check(processed_cmd, command_id, macros, timeout, - res, [&res, &cv](const result& async_res) { - res = async_res; - cv.notify_one(); - }); + bool res_available = + otel->check(processed_cmd, _conv_conf, command_id, macros, timeout, res, + [&res, &cv](const result& async_res) { + res = async_res; + cv.notify_one(); + }); // no data_point available => wait util available or timeout if (!res_available) { @@ -272,21 +271,35 @@ void otel_command::run(const std::string& processed_cmd, * */ void otel_command::init() { - if (!_extractor) { - std::shared_ptr otel = - otel::open_telemetry_base::instance(); - if (otel) { - _extractor = otel->create_extractor(get_command_line(), _host_serv_list); + try { + if (!_extractor) { + std::shared_ptr otel = + otel::open_telemetry_base::instance(); + if (otel) { + _extractor = + otel->create_extractor(get_command_line(), _host_serv_list); + } } + } catch (const std::exception& e) { + SPDLOG_LOGGER_TRACE(_logger, + "fail to parse host serv extractor configuration for " + "open-telemetry connector {} command line:{}", + get_name(), get_command_line()); + } + try { + if (!_conv_conf) { + std::shared_ptr otel = + otel::open_telemetry_base::instance(); + if (otel) { + _conv_conf = otel->create_converter_config(get_command_line()); + } + } + } catch (const std::exception& e) { + SPDLOG_LOGGER_TRACE(_logger, + "fail to parse converter configuration for " + "open-telemetry connector {} command line:{}", + get_name(), get_command_line()); } -} - -/** - * @brief reset _extractor attribute, called when otel module is unloaded - * - */ -void otel_command::reset_extractor() { - _extractor.reset(); } /** diff --git a/engine/src/configuration/applier/connector.cc b/engine/src/configuration/applier/connector.cc index 5c965919c4e..a5fcfd47d77 100644 --- a/engine/src/configuration/applier/connector.cc +++ b/engine/src/configuration/applier/connector.cc @@ -29,7 +29,7 @@ using namespace com::centreon::engine::configuration; -constexpr std::string_view _otel_fake_exe("open_telemetry"); +constexpr std::string_view _otel_fake_exe("opentelemetry"); /** * Add new connector. @@ -54,7 +54,7 @@ void applier::connector::add_object(configuration::connector const& obj) { // Create connector. boost::trim(processed_cmd); - // if executable connector path ends with open_telemetry, it's a fake + // if executable connector path ends with opentelemetry, it's a fake // opentelemetry connector size_t end_path = processed_cmd.find(' '); size_t otel_pos = processed_cmd.find(_otel_fake_exe); @@ -109,7 +109,7 @@ void applier::connector::modify_object(configuration::connector const& obj) { boost::trim(processed_cmd); - // if executable connector path ends with open_telemetry, it's a fake + // if executable connector path ends with opentelemetry, it's a fake // opentelemetry connector size_t end_path = processed_cmd.find(' '); size_t otel_pos = processed_cmd.find(_otel_fake_exe); diff --git a/engine/tests/CMakeLists.txt b/engine/tests/CMakeLists.txt index b1abe1fbc20..651c5ae6ef0 100755 --- a/engine/tests/CMakeLists.txt +++ b/engine/tests/CMakeLists.txt @@ -197,8 +197,9 @@ if(WITH_TESTING) pb_open_telemetry_lib centreon_grpc centreon_http - -L${Boost_LIBRARY_DIR_RELEASE} - boost_url + -L${Boost_LIBRARY_DIR_RELEASE} + boost_url + boost_program_options pthread ${GCOV} GTest::gtest diff --git a/engine/tests/opentelemetry/host_serv_extractor_test.cc b/engine/tests/opentelemetry/host_serv_extractor_test.cc index 6d3c59e8f44..4090ccca5f8 100644 --- a/engine/tests/opentelemetry/host_serv_extractor_test.cc +++ b/engine/tests/opentelemetry/host_serv_extractor_test.cc @@ -39,17 +39,26 @@ TEST(otl_host_serv_extractor_test, empty_request) { class otl_host_serv_attributes_extractor_test : public ::testing::Test { public: - const std::string _conf1; - const std::string _conf3 = - "attributes --host_attribute=resource --service_attribute=resource"; + "--extractor=attributes " + "--host_path=resource_metrics.resource.attributes.host " + "--service_path=resource_metrics.resource.attributes.service"; const std::string _conf4 = - "attributes --host_attribute=scope --service_attribute=scope"; + "--extractor=attributes " + "--host_path=resource_metrics.scope_metrics.scope.attributes.host " + "--service_path=resource_metrics.scope_metrics.scope.attributes.service"; const std::string _conf5 = - "attributes --host_attribute=data_point --service_attribute=data_point"; + "--extractor=attributes " + "--host_path=resource_metrics.scope_metrics.data.data_points.attributes." + "host " + "--service_path=resource_metrics.scope_metrics.data.data_points." + "attributes.service"; const std::string _conf6 = - "attributes --host_attribute=data_point --host_key=bad_host " - "--service_attribute=data_point"; + "--extractor=attributes " + "--host_path=resource_metrics.scope_metrics.data.data_points.attributes." + "bad_host " + "--service_path=resource_metrics.scope_metrics.data.data_points." + "attributes.service"; }; TEST_F(otl_host_serv_attributes_extractor_test, resource_attrib) { @@ -90,17 +99,6 @@ TEST_F(otl_host_serv_attributes_extractor_test, resource_attrib) { ASSERT_EQ(data_point_extracted_cpt, 1); - data_point::extract_data_points( - request, [this, &data_point_extracted_cpt](const data_point& data_pt) { - ++data_point_extracted_cpt; - commands::otel::host_serv_list::pointer host_srv_list = - std::make_shared(); - auto extractor = host_serv_extractor::create(_conf1, host_srv_list); - host_srv_list->register_host_serv("my_host", ""); - host_serv_metric to_test = extractor->extract_host_serv_metric(data_pt); - ASSERT_TRUE(to_test.host.empty()); - }); - data_point::extract_data_points( request, [this, &data_point_extracted_cpt](const data_point& data_pt) { ++data_point_extracted_cpt; @@ -219,17 +217,6 @@ TEST_F(otl_host_serv_attributes_extractor_test, scope_attrib) { ASSERT_EQ(data_point_extracted_cpt, 1); - data_point::extract_data_points( - request, [this, &data_point_extracted_cpt](const data_point& data_pt) { - ++data_point_extracted_cpt; - commands::otel::host_serv_list::pointer host_srv_list = - std::make_shared(); - auto extractor = host_serv_extractor::create(_conf1, host_srv_list); - host_srv_list->register_host_serv("my_host", ""); - host_serv_metric to_test = extractor->extract_host_serv_metric(data_pt); - ASSERT_TRUE(to_test.host.empty()); - }); - data_point::extract_data_points( request, [this, &data_point_extracted_cpt](const data_point& data_pt) { ++data_point_extracted_cpt; @@ -289,19 +276,6 @@ TEST_F(otl_host_serv_attributes_extractor_test, data_point_attrib) { unsigned data_point_extracted_cpt = 0; - data_point::extract_data_points( - request, [this, &data_point_extracted_cpt](const data_point& data_pt) { - ++data_point_extracted_cpt; - commands::otel::host_serv_list::pointer host_srv_list = - std::make_shared(); - auto extractor = host_serv_extractor::create(_conf1, host_srv_list); - host_srv_list->register_host_serv("my_host", ""); - host_serv_metric to_test = extractor->extract_host_serv_metric(data_pt); - ASSERT_EQ(to_test.host, "my_host"); - ASSERT_EQ(to_test.service, ""); - ASSERT_EQ(to_test.metric, "metric cpu"); - }); - data_point::extract_data_points( request, [this, &data_point_extracted_cpt](const data_point& data_pt) { ++data_point_extracted_cpt; @@ -315,7 +289,7 @@ TEST_F(otl_host_serv_attributes_extractor_test, data_point_attrib) { ASSERT_EQ(to_test.metric, "metric cpu"); }); - ASSERT_EQ(data_point_extracted_cpt, 2); + ASSERT_EQ(data_point_extracted_cpt, 1); data_point::extract_data_points( request, [this, &data_point_extracted_cpt](const data_point& data_pt) { @@ -358,7 +332,7 @@ TEST_F(otl_host_serv_attributes_extractor_test, data_point_attrib) { ++data_point_extracted_cpt; commands::otel::host_serv_list::pointer host_srv_list = std::make_shared(); - auto extractor = host_serv_extractor::create(_conf1, host_srv_list); + auto extractor = host_serv_extractor::create(_conf5, host_srv_list); host_srv_list->register_host_serv("my_host", "my_serv"); host_serv_metric to_test = extractor->extract_host_serv_metric(data_pt); ASSERT_EQ(to_test.host, "my_host"); diff --git a/engine/tests/opentelemetry/opentelemetry_test.cc b/engine/tests/opentelemetry/opentelemetry_test.cc index 7e26c6a5610..c06aa5579dc 100644 --- a/engine/tests/opentelemetry/opentelemetry_test.cc +++ b/engine/tests/opentelemetry/opentelemetry_test.cc @@ -103,7 +103,7 @@ open_telemetry_test::open_telemetry_test() void open_telemetry_test::SetUpTestSuite() { std::ofstream conf_file("/tmp/otel_conf.json"); conf_file << R"({ - "server": { + "otel_server": { "host": "127.0.0.1", "port": 4317 } @@ -145,7 +145,12 @@ TEST_F(open_telemetry_test, data_available) { spdlog::default_logger()); instance->create_extractor( - "", _host_serv_list); // create a defaut attribute extractor + "--extractor=attributes " + "--host_path=resource_metrics.scope_metrics.data.data_points.attributes." + "host " + "--service_path=resource_metrics.scope_metrics.data.data_points." + "attributes.service", + _host_serv_list); metric_request_ptr request = std::make_shared<::opentelemetry::proto::collector::metrics::v1:: @@ -158,8 +163,10 @@ TEST_F(open_telemetry_test, data_available) { nagios_macros macros; macros.host_ptr = host::hosts.begin()->second.get(); macros.service_ptr = service::services.begin()->second.get(); - ASSERT_TRUE(instance->check("nagios_telegraf", 1, macros, 1, res, - [](const commands::result&) {})); + ASSERT_TRUE(instance->check( + "nagios_telegraf", + instance->create_converter_config("--processor=nagios_telegraf"), 1, + macros, 1, res, [](const commands::result&) {})); ASSERT_EQ(res.command_id, 1); ASSERT_EQ(res.start_time.to_useconds(), 1707744430000000); ASSERT_EQ(res.end_time.to_useconds(), 1707744430000000); @@ -175,7 +182,12 @@ TEST_F(open_telemetry_test, timeout) { spdlog::default_logger()); instance->create_extractor( - "", _host_serv_list); // create a defaut attribute extractor + "--extractor=attributes " + "--host_path=resource_metrics.scope_metrics.data.data_points.attributes." + "host " + "--service_path=resource_metrics.scope_metrics.data.data_points." + "attributes.service", + _host_serv_list); commands::result res; res.exit_status = com::centreon::process::normal; @@ -184,11 +196,13 @@ TEST_F(open_telemetry_test, timeout) { macros.service_ptr = service::services.begin()->second.get(); std::condition_variable cv; std::mutex cv_m; - ASSERT_FALSE(instance->check("nagios_telegraf", 1, macros, 1, res, - [&res, &cv](const commands::result& async_res) { - res = async_res; - cv.notify_one(); - })); + ASSERT_FALSE(instance->check( + "nagios_telegraf", + instance->create_converter_config("--processor=nagios_telegraf"), 1, + macros, 1, res, [&res, &cv](const commands::result& async_res) { + res = async_res; + cv.notify_one(); + })); std::unique_lock l(cv_m); ASSERT_EQ(cv.wait_for(l, std::chrono::seconds(3)), @@ -200,8 +214,15 @@ TEST_F(open_telemetry_test, wait_for_data) { auto instance = ::open_telemetry::load("/tmp/otel_conf.json", g_io_context, spdlog::default_logger()); - instance->create_extractor( - "", _host_serv_list); // create a defaut attribute extractor + static const std::string otl_conf = + "--processor=nagios_telegraf " + "--extractor=attributes " + "--host_path=resource_metrics.scope_metrics.data.data_points.attributes." + "host " + "--service_path=resource_metrics.scope_metrics.data.data_points." + "attributes.service"; + + instance->create_extractor(otl_conf, _host_serv_list); commands::result res; res.exit_status = com::centreon::process::normal; @@ -210,12 +231,12 @@ TEST_F(open_telemetry_test, wait_for_data) { macros.service_ptr = service::services.begin()->second.get(); std::mutex cv_m; std::condition_variable cv; - bool data_available = - instance->check("nagios_telegraf", 1, macros, 1, res, - [&res, &cv](const commands::result& async_res) { - res = async_res; - cv.notify_one(); - }); + bool data_available = instance->check( + "nagios_telegraf", instance->create_converter_config(otl_conf), 1, macros, + 1, res, [&res, &cv](const commands::result& async_res) { + res = async_res; + cv.notify_one(); + }); ASSERT_FALSE(data_available); metric_request_ptr request = diff --git a/engine/tests/opentelemetry/otl_converter_test.cc b/engine/tests/opentelemetry/otl_converter_test.cc index 430ab19f263..65b3ea539b6 100644 --- a/engine/tests/opentelemetry/otl_converter_test.cc +++ b/engine/tests/opentelemetry/otl_converter_test.cc @@ -81,7 +81,7 @@ void otl_converter_test::TearDown() { TEST_F(otl_converter_test, empty_fifo) { data_point_fifo_container empty; - telegraf::otl_nagios_converter conv( + telegraf::nagios_converter conv( "", 1, *host::hosts.begin()->second, service::services.begin()->second.get(), std::chrono::system_clock::time_point(), [&](const commands::result&) {}, @@ -586,7 +586,7 @@ TEST_F(otl_converter_test, nagios_telegraf) { data_pt.get_metric().name(), data_pt); }); - telegraf::otl_nagios_converter conv( + telegraf::nagios_converter conv( "", 1, *host::hosts.begin()->second, service::services.begin()->second.get(), std::chrono::system_clock::time_point(), [&](const commands::result&) {}, @@ -621,7 +621,7 @@ TEST_F(otl_converter_test, nagios_telegraf_le_ge) { data_pt.get_metric().name(), data_pt); }); - telegraf::otl_nagios_converter conv( + telegraf::nagios_converter conv( "", 1, *host::hosts.begin()->second, service::services.begin()->second.get(), std::chrono::system_clock::time_point(), [&](const commands::result&) {}, @@ -654,7 +654,7 @@ TEST_F(otl_converter_test, nagios_telegraf_max) { data_pt.get_metric().name(), data_pt); }); - telegraf::otl_nagios_converter conv( + telegraf::nagios_converter conv( "", 1, *host::hosts.begin()->second, service::services.begin()->second.get(), std::chrono::system_clock::time_point(), [&](const commands::result&) {}, diff --git a/tests/README.md b/tests/README.md index b009245817b..0a6775c6ec9 100644 --- a/tests/README.md +++ b/tests/README.md @@ -16,7 +16,7 @@ From a Centreon host, you need to install Robot Framework On CentOS 7, the following commands should work to initialize your robot tests: ``` -pip3 install -U robotframework robotframework-databaselibrary robotframework-examples pymysql +pip3 install -U robotframework robotframework-databaselibrary robotframework-examples pymysql robotframework-requests yum install "Development Tools" python3-devel -y diff --git a/tests/broker-engine/opentelemetry.robot b/tests/broker-engine/opentelemetry.robot index caa5cc518ea..b9050880ad3 100644 --- a/tests/broker-engine/opentelemetry.robot +++ b/tests/broker-engine/opentelemetry.robot @@ -82,16 +82,16 @@ BEOTEL_TELEGRAF_CHECK_HOST Ctn Config Engine ${1} ${2} ${2} Ctn Add Otl ServerModule ... 0 - ... {"server":{"host": "0.0.0.0","port": 4317},"max_length_grpc_log":0} + ... {"otel_server":{"host": "0.0.0.0","port": 4317},"max_length_grpc_log":0} Ctn Config Add Otl Connector ... 0 ... OTEL connector - ... open_telemetry attributes --host_attribute=data_point --host_key=host --service_attribute=data_point --service_key=service + ... opentelemetry --processor=nagios_telegraf --extractor=attributes --host_path=resource_metrics.scope_metrics.data.data_points.attributes.host --service_path=resource_metrics.scope_metrics.data.data_points.attributes.service Ctn Engine Config Replace Value In Hosts ${0} host_1 check_command otel_check_icmp Ctn Engine Config Add Command ... ${0} ... otel_check_icmp - ... nagios_telegraf --cmd_line /usr/lib/nagios/plugins/check_icmp 127.0.0.1 + ... /usr/lib/nagios/plugins/check_icmp 127.0.0.1 ... OTEL connector Ctn Engine Config Set Value 0 log_level_checks trace @@ -162,16 +162,16 @@ BEOTEL_TELEGRAF_CHECK_SERVICE [Documentation] we send nagios telegraf formated datas and we expect to get it in check result [Tags] broker engine opentelemetry mon-34004 Ctn Config Engine ${1} ${2} ${2} - Ctn Add Otl ServerModule 0 {"server":{"host": "0.0.0.0","port": 4317},"max_length_grpc_log":0} + Ctn Add Otl ServerModule 0 {"otel_server":{"host": "0.0.0.0","port": 4317},"max_length_grpc_log":0} Ctn Config Add Otl Connector ... 0 ... OTEL connector - ... open_telemetry attributes --host_attribute=data_point --host_key=host --service_attribute=data_point --service_key=service + ... opentelemetry --processor=nagios_telegraf --extractor=attributes --host_path=resource_metrics.scope_metrics.data.data_points.attributes.host --service_path=resource_metrics.scope_metrics.data.data_points.attributes.service Ctn Engine Config Replace Value In Services ${0} service_1 check_command otel_check_icmp Ctn Engine Config Add Command ... ${0} ... otel_check_icmp - ... nagios_telegraf + ... /usr/lib/nagios/plugins/check_icmp 127.0.0.1 ... OTEL connector Ctn Engine Config Set Value 0 log_level_checks trace @@ -246,44 +246,44 @@ BEOTEL_SERVE_TELEGRAF_CONFIGURATION_CRYPTED Ctn Config Engine ${1} ${3} ${2} Ctn Add Otl ServerModule ... 0 - ... {"server":{"host": "0.0.0.0","port": 4317},"max_length_grpc_log":0, "telegraf_conf_server": {"port": 1443, "encryption": true, "engine_otel_endpoint": "127.0.0.1:4317", "certificate_path": "/tmp/otel/server.crt", "key_path": "/tmp/otel/server.key"}} + ... {"otel_server":{"host": "0.0.0.0","port": 4317},"max_length_grpc_log":0, "telegraf_conf_server": {"http_server":{"port": 1443, "encryption": true, "certificate_path": "/tmp/otel/server.crt", "key_path": "/tmp/otel/server.key"}, "cehck_interval":60, "engine_otel_endpoint": "127.0.0.1:4317"}} Ctn Config Add Otl Connector ... 0 ... OTEL connector - ... open_telemetry attributes --host_attribute=data_point --host_key=host --service_attribute=data_point --service_key=service + ... opentelemetry --processor=nagios_telegraf --extractor=attributes --host_path=resource_metrics.scope_metrics.data.data_points.attributes.host --service_path=resource_metrics.scope_metrics.data.data_points.attributes.service Ctn Engine Config Replace Value In Services ${0} service_1 check_command otel_check_icmp_serv_1 Ctn Engine Config Add Command ... ${0} ... otel_check_icmp_serv_1 - ... nagios_telegraf --cmd_line /usr/lib/nagios/plugins/check_icmp 127.0.0.1 + ... /usr/lib/nagios/plugins/check_icmp 127.0.0.1 ... OTEL connector Ctn Engine Config Replace Value In Services ${0} service_2 check_command otel_check_icmp_serv_2 Ctn Engine Config Add Command ... ${0} ... otel_check_icmp_serv_2 - ... nagios_telegraf --cmd_line /usr/lib/nagios/plugins/check_icmp 127.0.0.2 + ... /usr/lib/nagios/plugins/check_icmp 127.0.0.2 ... OTEL connector Ctn Engine Config Replace Value In Hosts ${0} host_1 check_command otel_check_icmp_host_1 Ctn Engine Config Add Command ... ${0} ... otel_check_icmp_host_1 - ... nagios_telegraf --cmd_line /usr/lib/nagios/plugins/check_icmp 127.0.0.10 + ... /usr/lib/nagios/plugins/check_icmp 127.0.0.10 ... OTEL connector Ctn Engine Config Replace Value In Hosts ${0} host_2 check_command otel_check_icmp_host_2 Ctn Engine Config Add Command ... ${0} ... otel_check_icmp_host_2 - ... nagios_telegraf --cmd_line /usr/lib/nagios/plugins/check_icmp 127.0.0.20 + ... /usr/lib/nagios/plugins/check_icmp 127.0.0.20 ... OTEL connector Ctn Engine Config Replace Value In Services ${0} service_5 check_command otel_check_icmp_serv_5 Ctn Engine Config Add Command ... ${0} ... otel_check_icmp_serv_5 - ... nagios_telegraf --cmd_line /usr/lib/nagios/plugins/check_icmp 127.0.0.5 + ... /usr/lib/nagios/plugins/check_icmp 127.0.0.5 ... OTEL connector Ctn Engine Config Set Value 0 log_level_checks trace @@ -320,44 +320,44 @@ BEOTEL_SERVE_TELEGRAF_CONFIGURATION_NO_CRYPTED Ctn Config Engine ${1} ${3} ${2} Ctn Add Otl ServerModule ... 0 - ... {"server":{"host": "0.0.0.0","port": 4317},"max_length_grpc_log":0, "telegraf_conf_server": {"port": 1443, "encryption": false, "engine_otel_endpoint": "127.0.0.1:4317"}} + ... {"otel_server":{"host": "0.0.0.0","port": 4317},"max_length_grpc_log":0, "telegraf_conf_server": {"http_server": {"port": 1443, "encryption": false}, "engine_otel_endpoint": "127.0.0.1:4317"}} Ctn Config Add Otl Connector ... 0 ... OTEL connector - ... /usr/lib64/centreon-connector/open_telemetry attributes --host_attribute=data_point --host_key=host --service_attribute=data_point --service_key=service + ... opentelemetry --processor=nagios_telegraf --extractor=attributes --host_path=resource_metrics.scope_metrics.data.data_points.attributes.host --service_path=resource_metrics.scope_metrics.data.data_points.attributes.service Ctn Engine Config Replace Value In Services ${0} service_1 check_command otel_check_icmp_serv_1 Ctn Engine Config Add Command ... ${0} ... otel_check_icmp_serv_1 - ... nagios_telegraf --cmd_line /usr/lib/nagios/plugins/check_icmp 127.0.0.1 + ... /usr/lib/nagios/plugins/check_icmp 127.0.0.1 ... OTEL connector Ctn Engine Config Replace Value In Services ${0} service_2 check_command otel_check_icmp_serv_2 Ctn Engine Config Add Command ... ${0} ... otel_check_icmp_serv_2 - ... nagios_telegraf --cmd_line /usr/lib/nagios/plugins/check_icmp 127.0.0.2 + ... /usr/lib/nagios/plugins/check_icmp 127.0.0.2 ... OTEL connector Ctn Engine Config Replace Value In Hosts ${0} host_1 check_command otel_check_icmp_host_1 Ctn Engine Config Add Command ... ${0} ... otel_check_icmp_host_1 - ... nagios_telegraf --cmd_line /usr/lib/nagios/plugins/check_icmp 127.0.0.10 + ... /usr/lib/nagios/plugins/check_icmp 127.0.0.10 ... OTEL connector Ctn Engine Config Replace Value In Hosts ${0} host_2 check_command otel_check_icmp_host_2 Ctn Engine Config Add Command ... ${0} ... otel_check_icmp_host_2 - ... nagios_telegraf --cmd_line /usr/lib/nagios/plugins/check_icmp 127.0.0.20 + ... /usr/lib/nagios/plugins/check_icmp 127.0.0.20 ... OTEL connector Ctn Engine Config Replace Value In Services ${0} service_5 check_command otel_check_icmp_serv_5 Ctn Engine Config Add Command ... ${0} ... otel_check_icmp_serv_5 - ... nagios_telegraf --cmd_line /usr/lib/nagios/plugins/check_icmp 127.0.0.5 + ... /usr/lib/nagios/plugins/check_icmp 127.0.0.5 ... OTEL connector Ctn Engine Config Set Value 0 log_level_checks trace diff --git a/tests/resources/opentelemetry/telegraf1.conf b/tests/resources/opentelemetry/telegraf1.conf new file mode 100644 index 00000000000..413e25eeb85 --- /dev/null +++ b/tests/resources/opentelemetry/telegraf1.conf @@ -0,0 +1,36 @@ +# Centreon telegraf configuration +# This telegraf configuration is generated by centreon centengine +[agent] + ## Default data collection interval for all inputs + interval = "60s" + +[[outputs.opentelemetry]] + service_address = "127.0.0.1:4317" + + +[[inputs.exec]] + name_override = "host_1__service_2" + commands = ["/usr/lib/nagios/plugins/check_icmp 127.0.0.2"] + data_format = "nagios" + [inputs.exec.tags] + host = "host_1" + service = "service_2" + + +[[inputs.exec]] + name_override = "host_1__service_1" + commands = ["/usr/lib/nagios/plugins/check_icmp 127.0.0.1"] + data_format = "nagios" + [inputs.exec.tags] + host = "host_1" + service = "service_1" + + +[[inputs.exec]] + name_override = "host_1__" + commands = ["/usr/lib/nagios/plugins/check_icmp 127.0.0.10"] + data_format = "nagios" + [inputs.exec.tags] + host = "host_1" + service = "" + diff --git a/tests/resources/opentelemetry/telegraf2.conf b/tests/resources/opentelemetry/telegraf2.conf new file mode 100644 index 00000000000..17f0d8a7f6f --- /dev/null +++ b/tests/resources/opentelemetry/telegraf2.conf @@ -0,0 +1,27 @@ +# Centreon telegraf configuration +# This telegraf configuration is generated by centreon centengine +[agent] + ## Default data collection interval for all inputs + interval = "60s" + +[[outputs.opentelemetry]] + service_address = "127.0.0.1:4317" + + +[[inputs.exec]] + name_override = "host_3__service_5" + commands = ["/usr/lib/nagios/plugins/check_icmp 127.0.0.5"] + data_format = "nagios" + [inputs.exec.tags] + host = "host_3" + service = "service_5" + + +[[inputs.exec]] + name_override = "host_2__" + commands = ["/usr/lib/nagios/plugins/check_icmp 127.0.0.20"] + data_format = "nagios" + [inputs.exec.tags] + host = "host_2" + service = "" + diff --git a/tests/update-doc.py b/tests/update-doc.py index 21a220a9222..20698ac075d 100755 --- a/tests/update-doc.py +++ b/tests/update-doc.py @@ -93,7 +93,7 @@ def parse_dir(d): On CentOS 7, the following commands should work to initialize your robot tests: ``` -pip3 install -U robotframework robotframework-databaselibrary robotframework-examples pymysql +pip3 install -U robotframework robotframework-databaselibrary robotframework-examples pymysql robotframework-requests yum install "Development Tools" python3-devel -y diff --git a/vcpkg.json b/vcpkg.json index dc44f161886..04388ffde31 100644 --- a/vcpkg.json +++ b/vcpkg.json @@ -20,6 +20,7 @@ "boost-multi-index", "boost-interprocess", "boost-exception", + "boost-program-options", "boost-serialization", "boost-url", "nlohmann-json", From f442b02a1ecd871d85ffc06c25879a5995cf20ad Mon Sep 17 00:00:00 2001 From: jean-christophe81 <98889244+jean-christophe81@users.noreply.github.com> Date: Fri, 7 Jun 2024 17:31:13 +0200 Subject: [PATCH 30/60] Mon 59116 previous otel pr comments (#1407) REFS:MON-59116 * otel_command => otel_connector data_point => otl_data_point host_list.is_allowed => host_list.contains otl_converter => otl_check_result_builder * nagios_converter => nagios_check_result_builder --- engine/doc/engine-doc.md | 32 ++--- .../{otel_command.hh => otel_connector.hh} | 28 +++-- .../engine/commands/otel_interface.hh | 45 ++++--- engine/modules/opentelemetry/CMakeLists.txt | 4 +- .../opentelemetry/doc/opentelemetry.md | 32 ++--- .../modules/opentelemetry/data_point_fifo.hh | 14 ++- .../data_point_fifo_container.hh | 2 +- .../opentelemetry/host_serv_extractor.hh | 10 +- .../modules/opentelemetry/open_telemetry.hh | 18 +-- ...nverter.hh => otl_check_result_builder.hh} | 47 +++---- .../modules/opentelemetry/otl_config.hh | 2 +- .../modules/opentelemetry/otl_data_point.hh | 39 +++--- .../opentelemetry/telegraf/conf_server.hh | 10 +- ...rter.hh => nagios_check_result_builder.hh} | 30 ++--- .../opentelemetry/src/data_point_fifo.cc | 2 +- .../src/data_point_fifo_container.cc | 4 +- .../opentelemetry/src/host_serv_extractor.cc | 16 +-- engine/modules/opentelemetry/src/main.cc | 4 +- .../opentelemetry/src/open_telemetry.cc | 119 +++++++++--------- ...nverter.cc => otl_check_result_builder.cc} | 84 ++++++++----- .../opentelemetry/src/otl_data_point.cc | 8 +- .../opentelemetry/src/telegraf/conf_server.cc | 10 +- ...rter.cc => nagios_check_result_builder.cc} | 9 +- engine/src/commands/CMakeLists.txt | 2 +- .../{otel_command.cc => otel_connector.cc} | 95 +++++++------- engine/src/commands/otel_interface.cc | 9 +- engine/src/configuration/applier/command.cc | 12 +- engine/src/configuration/applier/connector.cc | 16 +-- engine/src/configuration/applier/state.cc | 6 +- .../opentelemetry/host_serv_extractor_test.cc | 84 ++++++++----- .../tests/opentelemetry/opentelemetry_test.cc | 28 +++-- .../tests/opentelemetry/otl_converter_test.cc | 39 +++--- tests/resources/opentelemetry/telegraf1.conf | 36 ------ tests/resources/opentelemetry/telegraf2.conf | 27 ---- 34 files changed, 465 insertions(+), 458 deletions(-) rename engine/inc/com/centreon/engine/commands/{otel_command.hh => otel_connector.hh} (77%) rename engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/{otl_converter.hh => otl_check_result_builder.hh} (69%) rename engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/telegraf/{nagios_converter.hh => nagios_check_result_builder.hh} (79%) rename engine/modules/opentelemetry/src/{otl_converter.cc => otl_check_result_builder.cc} (66%) rename engine/modules/opentelemetry/src/telegraf/{nagios_converter.cc => nagios_check_result_builder.cc} (97%) rename engine/src/commands/{otel_command.cc => otel_connector.cc} (73%) delete mode 100644 tests/resources/opentelemetry/telegraf1.conf delete mode 100644 tests/resources/opentelemetry/telegraf2.conf diff --git a/engine/doc/engine-doc.md b/engine/doc/engine-doc.md index dbcd93a6432..cfcd167a151 100644 --- a/engine/doc/engine-doc.md +++ b/engine/doc/engine-doc.md @@ -64,8 +64,8 @@ Engine can receive open telemetry data on a grpc server A new module is added opentelemetry It works like that: * metrics are received -* extractors tries to extract host name and service description for each data_point. On success, data_point are pushed on fifos indexed by host, service -* a service that used these datas wants to do a check. The cmd line identifies the otl_converter that will construct check result from host service data_point fifos. If converter achieves to build a result from metrics, it returns right now, if it doesn't, a handler will be called as soon as needed metrics will be available or timeout expires. +* extractors tries to extract host name and service description for each otl_data_point. On success, otl_data_point are pushed on fifos indexed by host, service +* a service that used these datas wants to do a check. The cmd line identifies the otl_check_result_builder that will construct check result from host service otl_data_point fifos. If converter achieves to build a result from metrics, it returns right now, if it doesn't, a handler will be called as soon as needed metrics will be available or timeout expires. ### open telemetry request The proto is organized like that @@ -173,14 +173,14 @@ The proto is organized like that ``` ### Concepts and classes -* data_point: data_point is the smallest unit of received request, data_point class contains data_point protobuf object and all his parents (resource, scope, metric) -* host serv extractors: When we receive otel metrics, we must extract host and service, this is his job. It can be configurable in order for example to search host name in data_point attribute or in scope. host serv extractors also contains host serv allowed. This list is updated by register_host_serv command method -* data_point fifo: a container that contains data points indexed by timestamp -* data_point fifo container: fifos indexed by host service -* otel_command: a fake connector that is used to make the link between engine and otel module +* otl_data_point: otl_data_point is the smallest unit of received request, otl_data_point class contains otl_data_point protobuf object and all his parents (resource, scope, metric) +* host serv extractors: When we receive otel metrics, we must extract host and service, this is his job. It can be configurable in order for example to search host name in otl_data_point attribute or in scope. host serv extractors also contains host serv allowed. This list is updated by register_host_serv command method +* otl_data_point fifo: a container that contains data points indexed by timestamp +* otl_data_point fifo container: fifos indexed by host service +* otel_connector: a fake connector that is used to make the link between engine and otel module * otl_server: a grpc server that accept otel collector incoming connections -* otl_converter: This short lived object is created each time engine wants to do a check. His final class as his configuration is done from the command line of the check. His job is to create a check result from data_point fifo container datas. It's destroyed when he achieved to create a check result or when timeout expires. -* host_serv_list: in order to extract host and service, an host_serv extractor must known allowed host service pairs. As otel_command may be notified of host service using it by register_host_serv method while otel module is not yet loaded. This object shared between otel_command and host_serv_extractor is actualized from otel_command::register_host_serv. +* otl_check_result_builder: This short lived object is created each time engine wants to do a check. His final class as his configuration is done from the command line of the check. His job is to create a check result from otl_data_point fifo container datas. It's destroyed when he achieved to create a check result or when timeout expires. +* host_serv_list: in order to extract host and service, an host_serv extractor must known allowed host service pairs. As otel_connector may be notified of host service using it by register_host_serv method while otel module is not yet loaded. This object shared between otel_connector and host_serv_extractor is actualized from otel_connector::register_host_serv. ### How engine access to otl object In otel_interface.hh, otel object interface are defined in engine commands namespace. @@ -188,16 +188,16 @@ Object used by both otel module and engine are inherited from these interfaces. Engine only knows a singleton of the interface open_telemetry_base. This singleton is initialized at otl module loading. ### How to configure it -We use a fake connector. When configuration is loaded, if a connector command line begins with "open_telemetry", we create an otel_command. Arguments following "open_telemetry" are used to create an host service extractor. If otel module is loaded, we create extractor, otherwise, the otel_command initialization will be done at otel module loading. +We use a fake connector. When configuration is loaded, if a connector command line begins with "open_telemetry", we create an otel_connector. Arguments following "open_telemetry" are used to create an host service extractor. If otel module is loaded, we create extractor, otherwise, the otel_connector initialization will be done at otel module loading. So user has to build one connector by host serv extractor configuration. -Then commands can use these fake connectors (class otel_command) to run checks. +Then commands can use these fake connectors (class otel_connector) to run checks. ### How a service do a check -When otel_command::run is called, it calls the check method of open_telemetry singleton. -The check method of open_telemetry object will use command line passed to run to create an otl_converter object that has to convert metrics to check result. -The open_telemetry call sync_build_result_from_metrics, if it can't achieve to build a result, otl_converter is stored in a container. -When a metric of a waiting service is received, async_build_result_from_metrics of otl_converter is called. -In open_telemetry object, a second timer is also used to call async_time_out of otl_converter on timeout expire. +When otel_connector::run is called, it calls the check method of open_telemetry singleton. +The check method of open_telemetry object will use command line passed to run to create an otl_check_result_builder object that has to convert metrics to check result. +The open_telemetry call sync_build_result_from_metrics, if it can't achieve to build a result, otl_check_result_builder is stored in a container. +When a metric of a waiting service is received, async_build_result_from_metrics of otl_check_result_builder is called. +In open_telemetry object, a second timer is also used to call async_time_out of otl_check_result_builder on timeout expire. ### other configuration other configuration parameters are stored in a dedicated json file. The path of this file is passed as argument in centengine.cfg diff --git a/engine/inc/com/centreon/engine/commands/otel_command.hh b/engine/inc/com/centreon/engine/commands/otel_connector.hh similarity index 77% rename from engine/inc/com/centreon/engine/commands/otel_command.hh rename to engine/inc/com/centreon/engine/commands/otel_connector.hh index bc566328bb8..7a21e4c4589 100644 --- a/engine/inc/com/centreon/engine/commands/otel_command.hh +++ b/engine/inc/com/centreon/engine/commands/otel_connector.hh @@ -16,8 +16,8 @@ * For more information : contact@centreon.com */ -#ifndef CCE_COMMANDS_OTEL_COMMAND_HH -#define CCE_COMMANDS_OTEL_COMMAND_HH +#ifndef CCE_COMMANDS_OTEL_CONNECTOR_HH +#define CCE_COMMANDS_OTEL_CONNECTOR_HH #include "com/centreon/engine/commands/command.hh" #include "com/centreon/engine/commands/otel_interface.hh" @@ -31,19 +31,19 @@ namespace com::centreon::engine::commands { * open telemetry request run command line configure converter who converts * data_points to result */ -class otel_command : public command, - public std::enable_shared_from_this { +class otel_connector : public command, + public std::enable_shared_from_this { otel::host_serv_list::pointer _host_serv_list; public: - using otel_command_container = - absl::flat_hash_map>; + using otel_connector_container = + absl::flat_hash_map>; private: - static otel_command_container _commands; + static otel_connector_container _commands; std::shared_ptr _extractor; - std::shared_ptr _conv_conf; + std::shared_ptr _conv_conf; std::shared_ptr _logger; @@ -59,18 +59,20 @@ class otel_command : public command, static bool update(const std::string& connector_name, const std::string& cmd_line); - static std::shared_ptr get_otel_command( + static std::shared_ptr get_otel_connector( const std::string& connector_name); static void clear(); static void init_all(); - static const otel_command_container& get_otel_commands() { return _commands; } + static const otel_connector_container& get_otel_connectors() { + return _commands; + } - otel_command(const std::string& connector_name, - const std::string& cmd_line, - commands::command_listener* listener); + otel_connector(const std::string& connector_name, + const std::string& cmd_line, + commands::command_listener* listener); void update(const std::string& cmd_line); diff --git a/engine/inc/com/centreon/engine/commands/otel_interface.hh b/engine/inc/com/centreon/engine/commands/otel_interface.hh index 8a208e6fb82..7c26706c86e 100644 --- a/engine/inc/com/centreon/engine/commands/otel_interface.hh +++ b/engine/inc/com/centreon/engine/commands/otel_interface.hh @@ -25,7 +25,7 @@ namespace com::centreon::engine::commands::otel { /** - * @brief struct returned by otl_converter::extract_host_serv_metric + * @brief struct returned by otl_check_result_builder::extract_host_serv_metric * success if host not empty * service may be empty if it's a host check * @@ -52,7 +52,7 @@ struct host_serv_metric { /** * @brief this list is the list of host service(may be empty) pairs - * This list is shared between otel_command and his extractor + * This list is shared between otel_connector and his extractor * */ class host_serv_list { @@ -64,20 +64,19 @@ class host_serv_list { void register_host_serv(const std::string& host, const std::string& service_description); - void unregister_host_serv(const std::string& host, - const std::string& service_description); + void remove(const std::string& host, const std::string& service_description); - bool is_allowed(const std::string& host, - const std::string& service_description) const; + bool contains(const std::string& host, + const std::string& service_description) const; template - host_serv_metric is_allowed(const host_set& hosts, - const service_set& services) const; + host_serv_metric match(const host_set& hosts, + const service_set& services) const; }; template -host_serv_metric host_serv_list::is_allowed(const host_set& hosts, - const service_set& services) const { +host_serv_metric host_serv_list::match(const host_set& hosts, + const service_set& services) const { host_serv_metric ret; absl::ReaderMutexLock l(&_data_m); for (const auto& host : hosts) { @@ -110,12 +109,11 @@ host_serv_metric host_serv_list::is_allowed(const host_set& hosts, class host_serv_extractor { public: virtual ~host_serv_extractor() = default; - }; -class converter_config { +class check_result_builder_config { public: - virtual ~converter_config() = default; + virtual ~check_result_builder_config() = default; }; using result_callback = std::function; @@ -141,16 +139,17 @@ class open_telemetry_base const std::string& cmdline, const host_serv_list::pointer& host_serv_list) = 0; - virtual std::shared_ptr create_converter_config( - const std::string& cmd_line) = 0; - - virtual bool check(const std::string& processed_cmd, - const std::shared_ptr& conv_conf, - uint64_t command_id, - nagios_macros& macros, - uint32_t timeout, - commands::result& res, - result_callback&& handler) = 0; + virtual std::shared_ptr + create_check_result_builder_config(const std::string& cmd_line) = 0; + + virtual bool check( + const std::string& processed_cmd, + const std::shared_ptr& conv_conf, + uint64_t command_id, + nagios_macros& macros, + uint32_t timeout, + commands::result& res, + result_callback&& handler) = 0; }; }; // namespace com::centreon::engine::commands::otel diff --git a/engine/modules/opentelemetry/CMakeLists.txt b/engine/modules/opentelemetry/CMakeLists.txt index fd65ef641d6..0146d3f81de 100644 --- a/engine/modules/opentelemetry/CMakeLists.txt +++ b/engine/modules/opentelemetry/CMakeLists.txt @@ -51,12 +51,12 @@ ${SRC_DIR}/grpc_config.cc ${SRC_DIR}/host_serv_extractor.cc ${SRC_DIR}/open_telemetry.cc ${SRC_DIR}/otl_config.cc -${SRC_DIR}/otl_converter.cc +${SRC_DIR}/otl_check_result_builder.cc ${SRC_DIR}/otl_data_point.cc ${SRC_DIR}/otl_server.cc ${SRC_DIR}/main.cc ${SRC_DIR}/telegraf/conf_server.cc -${SRC_DIR}/telegraf/nagios_converter.cc +${SRC_DIR}/telegraf/nagios_check_result_builder.cc ${SRC_DIR}/opentelemetry/proto/collector/metrics/v1/metrics_service.grpc.pb.cc ) diff --git a/engine/modules/opentelemetry/doc/opentelemetry.md b/engine/modules/opentelemetry/doc/opentelemetry.md index 0fab609effc..3ad030d9e8a 100644 --- a/engine/modules/opentelemetry/doc/opentelemetry.md +++ b/engine/modules/opentelemetry/doc/opentelemetry.md @@ -4,8 +4,8 @@ Engine can receive open telemetry data on a grpc server A new module is added opentelemetry It works like that: * metrics are received -* extractors tries to extract host name and service description for each data_point. On success, data_point are pushed on fifos indexed by host, service -* a service that used these datas wants to do a check. The cmd line identifies the otl_converter that will construct check result from host service data_point fifos. If converter achieves to build a result from metrics, it returns right now, if it doesn't, a handler will be called as soon as needed metrics will be available or timeout expires. +* extractors tries to extract host name and service description for each otl_data_point. On success, otl_data_point are pushed on fifos indexed by host, service +* a service that used these datas wants to do a check. The cmd line identifies the otl_check_result_builder that will construct check result from host service otl_data_point fifos. If converter achieves to build a result from metrics, it returns right now, if it doesn't, a handler will be called as soon as needed metrics will be available or timeout expires. ### open telemetry request The proto is organized like that @@ -113,14 +113,14 @@ The proto is organized like that ``` ### Concepts and classes -* data_point: data_point is the smallest unit of received request, data_point class contains data_point protobuf object and all his parents (resource, scope, metric) -* host serv extractors: When we receive otel metrics, we must extract host and service, this is his job. It can be configurable in order for example to search host name in data_point attribute or in scope. host serv extractors also contains host serv allowed. This list is updated by register_host_serv command method -* data_point fifo: a container that contains data points indexed by timestamp -* data_point fifo container: fifos indexed by host service -* otel_command: a fake connector that is used to make the link between engine and otel module +* otl_data_point: otl_data_point is the smallest unit of received request, otl_data_point class contains otl_data_point protobuf object and all his parents (resource, scope, metric) +* host serv extractors: When we receive otel metrics, we must extract host and service, this is his job. It can be configurable in order for example to search host name in otl_data_point attribute or in scope. host serv extractors also contains host serv allowed. This list is updated by register_host_serv command method +* otl_data_point fifo: a container that contains data points indexed by timestamp +* otl_data_point fifo container: fifos indexed by host service +* otel_connector: a fake connector that is used to make the link between engine and otel module * otl_server: a grpc server that accept otel collector incoming connections -* otl_converter: This short lived object is created each time engine wants to do a check. His final class as his configuration is done from the command line of the check. His job is to create a check result from data_point fifo container datas. It's destroyed when he achieved to create a check result or when timeout expires. -* host_serv_list: in order to extract host and service, an host_serv extractor must known allowed host service pairs. As otel_command may be notified of host service using it by register_host_serv method while otel module is not yet loaded. This object shared between otel_command and host_serv_extractor is actualized from otel_command::register_host_serv. +* otl_check_result_builder: This short lived object is created each time engine wants to do a check. His final class as his configuration is done from the command line of the check. His job is to create a check result from otl_data_point fifo container datas. It's destroyed when he achieved to create a check result or when timeout expires. +* host_serv_list: in order to extract host and service, an host_serv extractor must known allowed host service pairs. As otel_connector may be notified of host service using it by register_host_serv method while otel module is not yet loaded. This object shared between otel_connector and host_serv_extractor is actualized from otel_connector::register_host_serv. ### How engine access to otl object In otel_interface.hh, otel object interface are defined in engine commands namespace. @@ -128,16 +128,16 @@ Object used by both otel module and engine are inherited from these interfaces. Engine only knows a singleton of the interface open_telemetry_base. This singleton is initialized at otl module loading. ### How to configure it -We use a fake connector. When configuration is loaded, if a connector command line begins with "open_telemetry", we create an otel_command. Arguments following "open_telemetry" are used to create an host service extractor. If otel module is loaded, we create extractor, otherwise, the otel_command initialization will be done at otel module loading. +We use a fake connector. When configuration is loaded, if a connector command line begins with "open_telemetry", we create an otel_connector. Arguments following "open_telemetry" are used to create an host service extractor. If otel module is loaded, we create extractor, otherwise, the otel_connector initialization will be done at otel module loading. So user has to build one connector by host serv extractor configuration. -Then commands can use these fake connectors (class otel_command) to run checks. +Then commands can use these fake connectors (class otel_connector) to run checks. ### How a service do a check -When otel_command::run is called, it calls the check method of open_telemetry singleton. -The check method of open_telemetry object will use command line passed to run to create an otl_converter object that has to convert metrics to check result. -The open_telemetry call sync_build_result_from_metrics, if it can't achieve to build a result, otl_converter is stored in a container. -When a metric of a waiting service is received, async_build_result_from_metrics of otl_converter is called. -In open_telemetry object, a second timer is also used to call async_time_out of otl_converter on timeout expire. +When otel_connector::run is called, it calls the check method of open_telemetry singleton. +The check method of open_telemetry object will use command line passed to run to create an otl_check_result_builder object that has to convert metrics to check result. +The open_telemetry call sync_build_result_from_metrics, if it can't achieve to build a result, otl_check_result_builder is stored in a container. +When a metric of a waiting service is received, async_build_result_from_metrics of otl_check_result_builder is called. +In open_telemetry object, a second timer is also used to call async_time_out of otl_check_result_builder on timeout expire. ### other configuration other configuration parameters are stored in a dedicated json file. The path of this file is passed as argument in centengine.cfg diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/data_point_fifo.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/data_point_fifo.hh index fefdab041ab..bf78b223b7b 100644 --- a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/data_point_fifo.hh +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/data_point_fifo.hh @@ -23,7 +23,7 @@ namespace com::centreon::engine::modules::opentelemetry { /** - * @brief This class is a multiset of opentelemetry data_point ordered by + * @brief This class is a multiset of opentelemetry otl_data_point ordered by * nano_timestamp * */ @@ -36,21 +36,23 @@ class data_point_fifo { * */ using is_transparent = void; - bool operator()(const data_point& left, const data_point& right) const { + bool operator()(const otl_data_point& left, + const otl_data_point& right) const { return left.get_nano_timestamp() < right.get_nano_timestamp(); } - bool operator()(const data_point& left, + bool operator()(const otl_data_point& left, uint64_t nano_timestamp_right) const { return left.get_nano_timestamp() < nano_timestamp_right; } bool operator()(uint64_t nano_timestamp_left, - const data_point& right) const { + const otl_data_point& right) const { return nano_timestamp_left < right.get_nano_timestamp(); } }; public: - using container = absl::btree_multiset; + using container = + absl::btree_multiset; private: static time_t _second_datapoint_expiry; @@ -67,7 +69,7 @@ class data_point_fifo { size_t size() const { return _fifo.size(); } - void add_data_point(const data_point& data_pt); + void add_data_point(const otl_data_point& data_pt); void clean(); diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/data_point_fifo_container.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/data_point_fifo_container.hh index 043417b0d6e..7406ea65648 100644 --- a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/data_point_fifo_container.hh +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/data_point_fifo_container.hh @@ -57,7 +57,7 @@ class data_point_fifo_container { void add_data_point(const std::string_view& host, const std::string_view& service, const std::string_view& metric, - const data_point& data_pt); + const otl_data_point& data_pt); const metric_name_to_fifo& get_fifos(const std::string& host, const std::string& service) const; diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/host_serv_extractor.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/host_serv_extractor.hh index 78ceed5b436..143c8bca621 100644 --- a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/host_serv_extractor.hh +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/host_serv_extractor.hh @@ -50,7 +50,7 @@ class host_serv_extractor : public commands::otel::host_serv_extractor { const commands::otel::host_serv_list::pointer& host_serv_list); virtual host_serv_metric extract_host_serv_metric( - const data_point&) const = 0; + const otl_data_point&) const = 0; bool is_allowed(const std::string& host, const std::string& service_description) const; @@ -64,12 +64,12 @@ template host_serv_metric host_serv_extractor::is_allowed( const host_set& hosts, const service_set& services) const { - return _host_serv_list->is_allowed(hosts, services); + return _host_serv_list->match(hosts, services); } /** * @brief this class try to find host service in opentelemetry attributes object - * It may search in data resource attributes, scope attributes or data_point + * It may search in data resource attributes, scope attributes or otl_data_point * attributes * An example of telegraf otel data: * @code {.json} @@ -108,7 +108,7 @@ host_serv_metric host_serv_extractor::is_allowed( * */ class host_serv_attributes_extractor : public host_serv_extractor { - enum class attribute_owner { resource, scope, data_point }; + enum class attribute_owner { resource, scope, otl_data_point }; attribute_owner _host_path; std::string _host_key; attribute_owner _serv_path; @@ -120,7 +120,7 @@ class host_serv_attributes_extractor : public host_serv_extractor { const commands::otel::host_serv_list::pointer& host_serv_list); host_serv_metric extract_host_serv_metric( - const data_point& data_pt) const override; + const otl_data_point& data_pt) const override; }; } // namespace com::centreon::engine::modules::opentelemetry diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/open_telemetry.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/open_telemetry.hh index fe3f928fdc6..b558b07c4e4 100644 --- a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/open_telemetry.hh +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/open_telemetry.hh @@ -24,8 +24,8 @@ #include "data_point_fifo_container.hh" #include "host_serv_extractor.hh" +#include "otl_check_result_builder.hh" #include "otl_config.hh" -#include "otl_converter.hh" namespace com::centreon::engine::modules::opentelemetry { @@ -60,14 +60,15 @@ class open_telemetry : public commands::otel::open_telemetry_base { struct host_serv_getter { using result_type = host_serv; const result_type& operator()( - const std::shared_ptr& node) const { + const std::shared_ptr& node) const { return node->get_host_serv(); } }; struct time_out_getter { using result_type = std::chrono::system_clock::time_point; - result_type operator()(const std::shared_ptr& node) const { + result_type operator()( + const std::shared_ptr& node) const { return node->get_time_out(); } }; @@ -79,7 +80,7 @@ class open_telemetry : public commands::otel::open_telemetry_base { * */ using waiting_converter = boost::multi_index::multi_index_container< - std::shared_ptr, + std::shared_ptr, boost::multi_index::indexed_by< boost::multi_index::hashed_non_unique, boost::multi_index::ordered_non_unique>>; @@ -89,7 +90,7 @@ class open_telemetry : public commands::otel::open_telemetry_base { std::shared_ptr _io_context; mutable std::mutex _protect; - void _forward_to_broker(const std::vector& unknown); + void _forward_to_broker(const std::vector& unknown); void _second_timer_handler(); @@ -127,7 +128,8 @@ class open_telemetry : public commands::otel::open_telemetry_base { static void unload(const std::shared_ptr& logger); bool check(const std::string& processed_cmd, - const std::shared_ptr& conv_conf, + const std::shared_ptr& + conv_conf, uint64_t command_id, nagios_macros& macros, uint32_t timeout, @@ -138,8 +140,8 @@ class open_telemetry : public commands::otel::open_telemetry_base { const std::string& cmdline, const commands::otel::host_serv_list::pointer& host_serv_list) override; - std::shared_ptr create_converter_config( - const std::string& cmd_line) override; + std::shared_ptr + create_check_result_builder_config(const std::string& cmd_line) override; }; } // namespace com::centreon::engine::modules::opentelemetry diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_converter.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_check_result_builder.hh similarity index 69% rename from engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_converter.hh rename to engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_check_result_builder.hh index 0152ba75ef1..2c1d3526819 100644 --- a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_converter.hh +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_check_result_builder.hh @@ -16,8 +16,8 @@ ** For more information : contact@centreon.com */ -#ifndef CCE_MOD_OTL_CONVERTER_HH -#define CCE_MOD_OTL_CONVERTER_HH +#ifndef CCE_MOD_OTL_CHECK_RESULT_BUILDER_HH +#define CCE_MOD_OTL_CHECK_RESULT_BUILDER_HH #include "com/centreon/engine/commands/otel_interface.hh" #include "data_point_fifo.hh" @@ -32,15 +32,16 @@ class data_point_fifo_container; * create a converter config that will be used to create converter * */ -class converter_config : public commands::otel::converter_config { +class check_result_builder_config + : public commands::otel::check_result_builder_config { public: - enum class converter_type { nagios_converter }; + enum class converter_type { nagios_check_result_builder }; private: const converter_type _type; public: - converter_config(converter_type conv_type) : _type(conv_type) {} + check_result_builder_config(converter_type conv_type) : _type(conv_type) {} converter_type get_type() const { return _type; } }; @@ -52,7 +53,8 @@ class converter_config : public commands::otel::converter_config { * These objects are oneshot, their lifetime is the check duration * */ -class otl_converter : public std::enable_shared_from_this { +class otl_check_result_builder + : public std::enable_shared_from_this { const std::string _cmd_line; const uint64_t _command_id; const std::pair _host_serv; @@ -66,15 +68,15 @@ class otl_converter : public std::enable_shared_from_this { commands::result& res) = 0; public: - otl_converter(const std::string& cmd_line, - uint64_t command_id, - const host& host, - const service* service, - std::chrono::system_clock::time_point timeout, - commands::otel::result_callback&& handler, - const std::shared_ptr& logger); + otl_check_result_builder(const std::string& cmd_line, + uint64_t command_id, + const host& host, + const service* service, + std::chrono::system_clock::time_point timeout, + commands::otel::result_callback&& handler, + const std::shared_ptr& logger); - virtual ~otl_converter() = default; + virtual ~otl_check_result_builder() = default; const std::string& get_cmd_line() const { return _cmd_line; } @@ -101,9 +103,9 @@ class otl_converter : public std::enable_shared_from_this { virtual void dump(std::string& output) const; - static std::shared_ptr create( + static std::shared_ptr create( const std::string& cmd_line, - const std::shared_ptr& conf, + const std::shared_ptr& conf, uint64_t command_id, const host& host, const service* service, @@ -111,8 +113,8 @@ class otl_converter : public std::enable_shared_from_this { commands::otel::result_callback&& handler, const std::shared_ptr& logger); - static std::shared_ptr create_converter_config( - const std::string& cmd_line); + static std::shared_ptr + create_check_result_builder_config(const std::string& cmd_line); }; } // namespace com::centreon::engine::modules::opentelemetry @@ -120,12 +122,13 @@ class otl_converter : public std::enable_shared_from_this { namespace fmt { template <> -struct formatter +struct formatter< + com::centreon::engine::modules::opentelemetry::otl_check_result_builder> : formatter { template - auto format( - const com::centreon::engine::modules::opentelemetry::otl_converter& cont, - FormatContext& ctx) const -> decltype(ctx.out()) { + auto format(const com::centreon::engine::modules::opentelemetry:: + otl_check_result_builder& cont, + FormatContext& ctx) const -> decltype(ctx.out()) { std::string output; (&cont)->dump(output); return formatter::format(output, ctx); diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_config.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_config.hh index 3d8f3d06966..16276151653 100644 --- a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_config.hh +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_config.hh @@ -31,7 +31,7 @@ class otl_config { bool _json_grpc_log = false; // if true, otel object are logged in json // format instead of protobuf debug format - // this two attributes are limits used by otel data_point fifos + // this two attributes are limits used by otel otl_data_point fifos // if fifo size exceed _max_fifo_size, oldest data_points are removed // Also, data_points older than _second_fifo_expiry are removed from fifos unsigned _second_fifo_expiry; diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_data_point.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_data_point.hh index 205a3acf625..1e0ca128278 100644 --- a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_data_point.hh +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_data_point.hh @@ -16,8 +16,8 @@ * For more information : contact@centreon.com */ -#ifndef CCE_MOD_OTL_SERVER_METRIC_HH -#define CCE_MOD_OTL_SERVER_METRIC_HH +#ifndef CCE_MOD_OTL_DATA_POINT_HH +#define CCE_MOD_OTL_DATA_POINT_HH namespace com::centreon::engine::modules::opentelemetry { @@ -93,10 +93,10 @@ using metric_request_ptr = * This bean represents a DataPoint, it embeds all ExportMetricsServiceRequest * (_parent attribute) in order to avoid useless copies. Many attributes are * references to _parent attribute - * As we can receive several types of data_point, we tries to expose common data - * by unique getters + * As we can receive several types of otl_data_point, we tries to expose common + * data by unique getters */ -class data_point { +class otl_data_point { public: enum class data_point_type { number, @@ -117,21 +117,21 @@ class data_point { data_point_type _type; double _value; - data_point( + otl_data_point( const metric_request_ptr& parent, const ::opentelemetry::proto::resource::v1::Resource& resource, const ::opentelemetry::proto::common::v1::InstrumentationScope& scope, const ::opentelemetry::proto::metrics::v1::Metric& metric, const ::opentelemetry::proto::metrics::v1::NumberDataPoint& data_pt); - data_point( + otl_data_point( const metric_request_ptr& parent, const ::opentelemetry::proto::resource::v1::Resource& resource, const ::opentelemetry::proto::common::v1::InstrumentationScope& scope, const ::opentelemetry::proto::metrics::v1::Metric& metric, const ::opentelemetry::proto::metrics::v1::HistogramDataPoint& data_pt); - data_point( + otl_data_point( const metric_request_ptr& parent, const ::opentelemetry::proto::resource::v1::Resource& resource, const ::opentelemetry::proto::common::v1::InstrumentationScope& scope, @@ -139,7 +139,7 @@ class data_point { const ::opentelemetry::proto::metrics::v1::ExponentialHistogramDataPoint& data_pt); - data_point( + otl_data_point( const metric_request_ptr& parent, const ::opentelemetry::proto::resource::v1::Resource& resource, const ::opentelemetry::proto::common::v1::InstrumentationScope& scope, @@ -189,8 +189,8 @@ class data_point { * @param handler called on every data point found */ template -void data_point::extract_data_points(const metric_request_ptr& metrics, - data_point_handler&& handler) { +void otl_data_point::extract_data_points(const metric_request_ptr& metrics, + data_point_handler&& handler) { using namespace ::opentelemetry::proto::metrics::v1; for (const ResourceMetrics& resource_metric : metrics->resource_metrics()) { const ::opentelemetry::proto::resource::v1::Resource& resource = @@ -203,26 +203,31 @@ void data_point::extract_data_points(const metric_request_ptr& metrics, switch (pb_metric.data_case()) { case Metric::kGauge: for (const NumberDataPoint& iter : pb_metric.gauge().data_points()) - handler(data_point(metrics, resource, scope, pb_metric, iter)); + handler( + otl_data_point(metrics, resource, scope, pb_metric, iter)); break; case Metric::kSum: for (const NumberDataPoint& iter : pb_metric.sum().data_points()) - handler(data_point(metrics, resource, scope, pb_metric, iter)); + handler( + otl_data_point(metrics, resource, scope, pb_metric, iter)); break; case Metric::kHistogram: for (const HistogramDataPoint& iter : pb_metric.histogram().data_points()) - handler(data_point(metrics, resource, scope, pb_metric, iter)); + handler( + otl_data_point(metrics, resource, scope, pb_metric, iter)); break; case Metric::kExponentialHistogram: for (const ExponentialHistogramDataPoint& iter : pb_metric.exponential_histogram().data_points()) - handler(data_point(metrics, resource, scope, pb_metric, iter)); + handler( + otl_data_point(metrics, resource, scope, pb_metric, iter)); break; case Metric::kSummary: for (const SummaryDataPoint& iter : pb_metric.summary().data_points()) - handler(data_point(metrics, resource, scope, pb_metric, iter)); + handler( + otl_data_point(metrics, resource, scope, pb_metric, iter)); break; } } @@ -232,4 +237,4 @@ void data_point::extract_data_points(const metric_request_ptr& metrics, }; // namespace com::centreon::engine::modules::opentelemetry -#endif \ No newline at end of file +#endif diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/telegraf/conf_server.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/telegraf/conf_server.hh index cc024e1d5fb..1e6a94b9f6b 100644 --- a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/telegraf/conf_server.hh +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/telegraf/conf_server.hh @@ -79,11 +79,11 @@ class conf_session : public connection_class { bool _get_commands(const std::string& host_name, std::string& request_body); - bool _otel_command_to_stream(const std::string& cmd_name, - const std::string& cmd_line, - const std::string& host, - const std::string& service, - std::string& to_append); + bool _otel_connector_to_stream(const std::string& cmd_name, + const std::string& cmd_line, + const std::string& host, + const std::string& service, + std::string& to_append); public: using my_type = conf_session; diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/telegraf/nagios_converter.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/telegraf/nagios_check_result_builder.hh similarity index 79% rename from engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/telegraf/nagios_converter.hh rename to engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/telegraf/nagios_check_result_builder.hh index dc3b36fcbc9..77bcd34b533 100644 --- a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/telegraf/nagios_converter.hh +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/telegraf/nagios_check_result_builder.hh @@ -91,26 +91,26 @@ namespace com::centreon::engine::modules::opentelemetry::telegraf { * * */ -class nagios_converter : public otl_converter { +class nagios_check_result_builder : public otl_check_result_builder { protected: bool _build_result_from_metrics(metric_name_to_fifo& fifos, commands::result& res) override; public: - nagios_converter(const std::string& cmd_line, - uint64_t command_id, - const host& host, - const service* service, - std::chrono::system_clock::time_point timeout, - commands::otel::result_callback&& handler, - const std::shared_ptr& logger) - : otl_converter(cmd_line, - command_id, - host, - service, - timeout, - std::move(handler), - logger) {} + nagios_check_result_builder(const std::string& cmd_line, + uint64_t command_id, + const host& host, + const service* service, + std::chrono::system_clock::time_point timeout, + commands::otel::result_callback&& handler, + const std::shared_ptr& logger) + : otl_check_result_builder(cmd_line, + command_id, + host, + service, + timeout, + std::move(handler), + logger) {} }; } // namespace com::centreon::engine::modules::opentelemetry::telegraf diff --git a/engine/modules/opentelemetry/src/data_point_fifo.cc b/engine/modules/opentelemetry/src/data_point_fifo.cc index 8c1827854ac..3082d0644c5 100644 --- a/engine/modules/opentelemetry/src/data_point_fifo.cc +++ b/engine/modules/opentelemetry/src/data_point_fifo.cc @@ -41,7 +41,7 @@ void data_point_fifo::update_fifo_limit(time_t second_datapoint_expiry, * * @param data_pt */ -void data_point_fifo::add_data_point(const data_point& data_pt) { +void data_point_fifo::add_data_point(const otl_data_point& data_pt) { clean(); _fifo.insert(data_pt); } diff --git a/engine/modules/opentelemetry/src/data_point_fifo_container.cc b/engine/modules/opentelemetry/src/data_point_fifo_container.cc index b2ab98dc433..112ffb271d5 100644 --- a/engine/modules/opentelemetry/src/data_point_fifo_container.cc +++ b/engine/modules/opentelemetry/src/data_point_fifo_container.cc @@ -65,12 +65,12 @@ void data_point_fifo_container::clean_empty_fifos( * @brief add a data point in the corresponding fifo * mutex must be locked during returned data use * - * @param data_pt data_point to add + * @param data_pt otl_data_point to add */ void data_point_fifo_container::add_data_point(const std::string_view& host, const std::string_view& service, const std::string_view& metric, - const data_point& data_pt) { + const otl_data_point& data_pt) { metric_name_to_fifo& fifos = _data[std::make_pair(host, service)]; auto exist = fifos.find(metric); if (exist == fifos.end()) { diff --git a/engine/modules/opentelemetry/src/host_serv_extractor.cc b/engine/modules/opentelemetry/src/host_serv_extractor.cc index 1912a84971e..bbb26cdb215 100644 --- a/engine/modules/opentelemetry/src/host_serv_extractor.cc +++ b/engine/modules/opentelemetry/src/host_serv_extractor.cc @@ -35,7 +35,7 @@ using namespace com::centreon::engine::modules::opentelemetry; bool host_serv_extractor::is_allowed( const std::string& host, const std::string& service_description) const { - return _host_serv_list->is_allowed(host, service_description); + return _host_serv_list->contains(host, service_description); } std::shared_ptr host_serv_extractor::create( @@ -77,7 +77,7 @@ std::shared_ptr host_serv_extractor::create( * * @param command_line command line that contains options used by extractor * @param host_serv_list list that will be shared bu host_serv_extractor and - * otel_command + * otel_connector */ host_serv_attributes_extractor::host_serv_attributes_extractor( const std::string& command_line, @@ -113,7 +113,7 @@ host_serv_attributes_extractor::host_serv_attributes_extractor( } else if (sz_attr == "scope") { attr = attribute_owner::scope; } else { - attr = attribute_owner::data_point; + attr = attribute_owner::otl_data_point; } }; @@ -125,13 +125,13 @@ host_serv_attributes_extractor::host_serv_attributes_extractor( .run(), vm); if (!vm.count("host_path")) { - _host_path = attribute_owner::data_point; + _host_path = attribute_owner::otl_data_point; _host_key = "host"; } else { parse_path(vm["host_path"].as(), _host_path, _host_key); } if (!vm.count("service_path")) { - _serv_path = attribute_owner::data_point; + _serv_path = attribute_owner::otl_data_point; _serv_key = "service"; } else { parse_path(vm["service_path"].as(), _serv_path, _serv_key); @@ -154,15 +154,15 @@ host_serv_attributes_extractor::host_serv_attributes_extractor( * found */ host_serv_metric host_serv_attributes_extractor::extract_host_serv_metric( - const data_point& data_pt) const { + const otl_data_point& data_pt) const { auto extract = - [](const data_point& data_pt, attribute_owner owner, + [](const otl_data_point& data_pt, attribute_owner owner, const std::string& key) -> absl::flat_hash_set { absl::flat_hash_set ret; const ::google::protobuf::RepeatedPtrField< ::opentelemetry::proto::common::v1::KeyValue>* attributes = nullptr; switch (owner) { - case attribute_owner::data_point: + case attribute_owner::otl_data_point: attributes = &data_pt.get_data_point_attributes(); break; case attribute_owner::scope: diff --git a/engine/modules/opentelemetry/src/main.cc b/engine/modules/opentelemetry/src/main.cc index abd6d08cfc5..54a63103f57 100644 --- a/engine/modules/opentelemetry/src/main.cc +++ b/engine/modules/opentelemetry/src/main.cc @@ -16,7 +16,7 @@ * For more information : contact@centreon.com */ -#include "com/centreon/engine/commands/otel_command.hh" +#include "com/centreon/engine/commands/otel_connector.hh" #include "com/centreon/engine/nebmods.hh" #include "com/centreon/engine/nebmodules.hh" #include "com/centreon/exceptions/msg_fmt.hh" @@ -108,7 +108,7 @@ extern "C" int nebmodule_init(int flags, char const* args, void* handle) { open_telemetry::load(conf_file_path, g_io_context, log_v2::instance().get(log_v2::OTEL)); - commands::otel_command::init_all(); + commands::otel_connector::init_all(); return 0; } diff --git a/engine/modules/opentelemetry/src/open_telemetry.cc b/engine/modules/opentelemetry/src/open_telemetry.cc index 478564393bd..34da5d8fbf8 100644 --- a/engine/modules/opentelemetry/src/open_telemetry.cc +++ b/engine/modules/opentelemetry/src/open_telemetry.cc @@ -218,7 +218,7 @@ void open_telemetry::_shutdown() { * @param cmdline which begins with name of extractor, following parameters * are used by extractor * @param host_serv_list list that will be shared bu host_serv_extractor and - * otel_command + * otel_connector * @return * std::shared_ptr * @throw if extractor type is unknown @@ -264,16 +264,19 @@ open_telemetry::create_extractor( /** * @brief converter is created for each check, so in order to not parse otel - * connector command line on each check , we create a converter_config - * object that is used to create converter it search the flag extractor + * connector command line on each check , we create a + * check_result_builder_config object that is used to create converter it search + * the flag extractor * * @param cmd_line * @return - * std::shared_ptr + * std::shared_ptr */ -std::shared_ptr -open_telemetry::create_converter_config(const std::string& cmd_line) { - return otl_converter::create_converter_config(cmd_line); +std::shared_ptr< + com::centreon::engine::commands::otel::check_result_builder_config> +open_telemetry::create_check_result_builder_config( + const std::string& cmd_line) { + return otl_check_result_builder::create_check_result_builder_config(cmd_line); } /** @@ -295,16 +298,18 @@ open_telemetry::create_converter_config(const std::string& cmd_line) { */ bool open_telemetry::check( const std::string& processed_cmd, - const std::shared_ptr& conv_config, + const std::shared_ptr& + conv_config, uint64_t command_id, nagios_macros& macros, uint32_t timeout, commands::result& res, commands::otel::result_callback&& handler) { - std::shared_ptr to_use; + std::shared_ptr to_use; try { - to_use = otl_converter::create( - processed_cmd, std::static_pointer_cast(conv_config), + to_use = otl_check_result_builder::create( + processed_cmd, + std::static_pointer_cast(conv_config), command_id, *macros.host_ptr, macros.service_ptr, std::chrono::system_clock::now() + std::chrono::seconds(timeout), std::move(handler), _logger); @@ -335,61 +340,63 @@ bool open_telemetry::check( /** * @brief called on metric reception - * we first fill data_point fifos and then if a converter of a service is - * waiting for data_point, we call him. If it achieve to generate a check - * result, the handler of otl_converter is called + * we first fill otl_data_point fifos and then if a converter of a service is + * waiting for otl_data_point, we call him. If it achieve to generate a check + * result, the handler of otl_check_result_builder is called * unknown metrics are passed to _forward_to_broker * * @param metrics collector request */ void open_telemetry::_on_metric(const metric_request_ptr& metrics) { - std::vector unknown; + std::vector unknown; { std::lock_guard l(_protect); if (_extractors.empty()) { // no extractor configured => all unknown - data_point::extract_data_points(metrics, - [&unknown](const data_point& data_pt) { - unknown.push_back(data_pt); - }); + otl_data_point::extract_data_points( + metrics, [&unknown](const otl_data_point& data_pt) { + unknown.push_back(data_pt); + }); } else { waiting_converter::nth_index<0>::type& host_serv_index = _waiting.get<0>(); - std::vector> to_notify; + std::vector> to_notify; auto last_success = _extractors.begin(); - data_point::extract_data_points(metrics, [this, &unknown, &last_success, - &host_serv_index, &to_notify]( - const data_point& data_pt) { - bool data_point_known = false; - // we try all extractors and we begin with the last which has - // achieved to extract host - for (unsigned tries = 0; tries < _extractors.size(); ++tries) { - host_serv_metric hostservmetric = - last_success->second->extract_host_serv_metric(data_pt); - - if (!hostservmetric.host.empty()) { // match - _fifo.add_data_point(hostservmetric.host, hostservmetric.service, - hostservmetric.metric, data_pt); - - // converters waiting this metric? - auto waiting = host_serv_index.equal_range( - host_serv{hostservmetric.host, hostservmetric.service}); - while (waiting.first != waiting.second) { - to_notify.push_back(*waiting.first); - waiting.first = host_serv_index.erase(waiting.first); + otl_data_point::extract_data_points( + metrics, [this, &unknown, &last_success, &host_serv_index, + &to_notify](const otl_data_point& data_pt) { + bool data_point_known = false; + // we try all extractors and we begin with the last which has + // achieved to extract host + for (unsigned tries = 0; tries < _extractors.size(); ++tries) { + host_serv_metric hostservmetric = + last_success->second->extract_host_serv_metric(data_pt); + + if (!hostservmetric.host.empty()) { // match + _fifo.add_data_point(hostservmetric.host, + hostservmetric.service, + hostservmetric.metric, data_pt); + + // converters waiting this metric? + auto waiting = host_serv_index.equal_range( + host_serv{hostservmetric.host, hostservmetric.service}); + while (waiting.first != waiting.second) { + to_notify.push_back(*waiting.first); + waiting.first = host_serv_index.erase(waiting.first); + } + data_point_known = true; + break; + } + // no match => we try next extractor + ++last_success; + if (last_success == _extractors.end()) { + last_success = _extractors.begin(); + } } - data_point_known = true; - break; - } - // no match => we try next extractor - ++last_success; - if (last_success == _extractors.end()) { - last_success = _extractors.begin(); - } - } - if (!data_point_known) { - unknown.push_back(data_pt); // unknown metric => forward to broker - } - }); + if (!data_point_known) { + unknown.push_back( + data_pt); // unknown metric => forward to broker + } + }); SPDLOG_LOGGER_TRACE(_logger, "fifos:{}", _fifo); // we wait that all request datas have been computed to give us more // chance of converter success @@ -428,7 +435,7 @@ void open_telemetry::_start_second_timer() { * */ void open_telemetry::_second_timer_handler() { - std::vector> to_notify; + std::vector> to_notify; { std::lock_guard l(_protect); std::chrono::system_clock::time_point now = @@ -445,7 +452,7 @@ void open_telemetry::_second_timer_handler() { } // notify all timeout - for (std::shared_ptr to_not : to_notify) { + for (std::shared_ptr to_not : to_notify) { SPDLOG_LOGGER_DEBUG(_logger, "time out: {}", *to_not); to_not->async_time_out(); } @@ -459,4 +466,4 @@ void open_telemetry::_second_timer_handler() { * @param unknown */ void open_telemetry::_forward_to_broker( - const std::vector& unknown) {} + const std::vector& unknown) {} diff --git a/engine/modules/opentelemetry/src/otl_converter.cc b/engine/modules/opentelemetry/src/otl_check_result_builder.cc similarity index 66% rename from engine/modules/opentelemetry/src/otl_converter.cc rename to engine/modules/opentelemetry/src/otl_check_result_builder.cc index 9f45e962b12..e1f75423fee 100644 --- a/engine/modules/opentelemetry/src/otl_converter.cc +++ b/engine/modules/opentelemetry/src/otl_check_result_builder.cc @@ -20,21 +20,34 @@ #include "com/centreon/exceptions/msg_fmt.hh" #include "data_point_fifo_container.hh" -#include "otl_converter.hh" -#include "telegraf/nagios_converter.hh" +#include "otl_check_result_builder.hh" +#include "telegraf/nagios_check_result_builder.hh" #include "absl/flags/commandlineflag.h" #include "absl/strings/str_split.h" using namespace com::centreon::engine::modules::opentelemetry; -otl_converter::otl_converter(const std::string& cmd_line, - uint64_t command_id, - const host& host, - const service* service, - std::chrono::system_clock::time_point timeout, - commands::otel::result_callback&& handler, - const std::shared_ptr& logger) +/** + * @brief Construct a new otl check result builder::otl check result builder + * object + * + * @param cmd_line + * @param command_id + * @param host + * @param service + * @param timeout + * @param handler called when mandatory metrics will be available + * @param logger + */ +otl_check_result_builder::otl_check_result_builder( + const std::string& cmd_line, + uint64_t command_id, + const host& host, + const service* service, + std::chrono::system_clock::time_point timeout, + commands::otel::result_callback&& handler, + const std::shared_ptr& logger) : _cmd_line(cmd_line), _command_id(command_id), _host_serv{host.name(), service ? service->description() : ""}, @@ -42,7 +55,15 @@ otl_converter::otl_converter(const std::string& cmd_line, _callback(handler), _logger(logger) {} -bool otl_converter::sync_build_result_from_metrics( +/** + * @brief try to build a check result + * + * @param data_pts + * @param res + * @return true all mandatory metrics are available and a check_result is built + * @return false + */ +bool otl_check_result_builder::sync_build_result_from_metrics( data_point_fifo_container& data_pts, commands::result& res) { std::lock_guard l(data_pts); @@ -59,10 +80,10 @@ bool otl_converter::sync_build_result_from_metrics( * clients * * @param data_pts - * @return true otl_converter has managed to create check result + * @return true otl_check_result_builder has managed to create check result * @return false */ -bool otl_converter::async_build_result_from_metrics( +bool otl_check_result_builder::async_build_result_from_metrics( data_point_fifo_container& data_pts) { commands::result res; bool success = false; @@ -82,7 +103,7 @@ bool otl_converter::async_build_result_from_metrics( * _timeout * */ -void otl_converter::async_time_out() { +void otl_check_result_builder::async_time_out() { commands::result res; res.exit_status = process::timeout; res.command_id = _command_id; @@ -94,24 +115,26 @@ void otl_converter::async_time_out() { * first field identify type of config * Example: * @code {.c++} - * std::shared_ptr converter = - * otl_converter::create("--processor=nagios_telegraf --fifo_depth=5", conf, 5, *host, serv, - * timeout_point, [](const commads::result &res){}, _logger); + * std::shared_ptr converter = + * otl_check_result_builder::create("--processor=nagios_telegraf + * --fifo_depth=5", conf, 5, *host, serv, timeout_point, [](const + * commads::result &res){}, _logger); * @endcode * * @param cmd_line - * @param conf bean configuration object created by create_converter_config + * @param conf bean configuration object created by + * create_check_result_builder_config * @param command_id * @param host * @param service * @param timeout * @param handler handler that will be called once we have all metrics mandatory * to create a check_result - * @return std::shared_ptr + * @return std::shared_ptr */ -std::shared_ptr otl_converter::create( +std::shared_ptr otl_check_result_builder::create( const std::string& cmd_line, - const std::shared_ptr& conf, + const std::shared_ptr& conf, uint64_t command_id, const host& host, const service* service, @@ -119,8 +142,9 @@ std::shared_ptr otl_converter::create( commands::otel::result_callback&& handler, const std::shared_ptr& logger) { switch (conf->get_type()) { - case converter_config::converter_type::nagios_converter: - return std::make_shared( + case check_result_builder_config::converter_type:: + nagios_check_result_builder: + return std::make_shared( cmd_line, command_id, host, service, timeout, std::move(handler), logger); default: @@ -134,7 +158,7 @@ std::shared_ptr otl_converter::create( * * @param output string to log */ -void otl_converter::dump(std::string& output) const { +void otl_check_result_builder::dump(std::string& output) const { output = fmt::format( "host:{}, service:{}, command_id={}, timeout:{} cmdline: \"{}\"", _host_serv.first, _host_serv.second, _command_id, _timeout, _cmd_line); @@ -146,13 +170,14 @@ void otl_converter::dump(std::string& output) const { * Example: * @code {.c++} * std::shared_ptr converter = - * otl_converter::create("--processor=nagios_telegraf --fifo_depth=5"); - * @endcode + * otl_converter::create_check_result_builder_config("--processor=nagios_telegraf + * --fifo_depth=5"); * * @param cmd_line - * @return std::shared_ptr + * @return std::shared_ptr */ -std::shared_ptr otl_converter::create_converter_config( +std::shared_ptr +otl_check_result_builder::create_check_result_builder_config( const std::string& cmd_line) { static initialized_data_class desc( [](po::options_description& desc) { @@ -172,8 +197,9 @@ std::shared_ptr otl_converter::create_converter_config( } std::string extractor_type = vm["processor"].as(); if (extractor_type == "nagios_telegraf") { - return std::make_shared( - converter_config::converter_type::nagios_converter); + return std::make_shared( + check_result_builder_config::converter_type:: + nagios_check_result_builder); } else { throw exceptions::msg_fmt("unknown processor in {}", cmd_line); } diff --git a/engine/modules/opentelemetry/src/otl_data_point.cc b/engine/modules/opentelemetry/src/otl_data_point.cc index 0b7811b6fe1..515244c92a9 100644 --- a/engine/modules/opentelemetry/src/otl_data_point.cc +++ b/engine/modules/opentelemetry/src/otl_data_point.cc @@ -21,7 +21,7 @@ using namespace com::centreon::engine::modules::opentelemetry; using namespace ::opentelemetry::proto::metrics::v1; -data_point::data_point( +otl_data_point::otl_data_point( const metric_request_ptr& parent, const ::opentelemetry::proto::resource::v1::Resource& resource, const ::opentelemetry::proto::common::v1::InstrumentationScope& scope, @@ -38,7 +38,7 @@ data_point::data_point( _value = data_pt.as_double() ? data_pt.as_double() : data_pt.as_int(); } -data_point::data_point( +otl_data_point::otl_data_point( const metric_request_ptr& parent, const ::opentelemetry::proto::resource::v1::Resource& resource, const ::opentelemetry::proto::common::v1::InstrumentationScope& scope, @@ -55,7 +55,7 @@ data_point::data_point( _value = data_pt.count(); } -data_point::data_point( +otl_data_point::otl_data_point( const metric_request_ptr& parent, const ::opentelemetry::proto::resource::v1::Resource& resource, const ::opentelemetry::proto::common::v1::InstrumentationScope& scope, @@ -73,7 +73,7 @@ data_point::data_point( _value = data_pt.count(); } -data_point::data_point( +otl_data_point::otl_data_point( const metric_request_ptr& parent, const ::opentelemetry::proto::resource::v1::Resource& resource, const ::opentelemetry::proto::common::v1::InstrumentationScope& scope, diff --git a/engine/modules/opentelemetry/src/telegraf/conf_server.cc b/engine/modules/opentelemetry/src/telegraf/conf_server.cc index 48646b4b1ee..b7b53fa2ec8 100644 --- a/engine/modules/opentelemetry/src/telegraf/conf_server.cc +++ b/engine/modules/opentelemetry/src/telegraf/conf_server.cc @@ -270,7 +270,7 @@ void conf_session::on_receive_request( * @return false */ template -bool conf_session::_otel_command_to_stream( +bool conf_session::_otel_connector_to_stream( const std::string& cmd_name, const std::string& cmd_line, const std::string& host, @@ -341,9 +341,9 @@ bool conf_session::_get_commands(const std::string& host_name, if (use_otl_command(*hst)) { nagios_macros* macros(get_global_macros()); - ret |= _otel_command_to_stream(hst->check_command(), - hst->get_check_command_line(macros), - hst->name(), "", request_body); + ret |= _otel_connector_to_stream(hst->check_command(), + hst->get_check_command_line(macros), + hst->name(), "", request_body); clear_volatile_macros_r(macros); } else { SPDLOG_LOGGER_DEBUG(this->_logger, @@ -359,7 +359,7 @@ bool conf_session::_get_commands(const std::string& host_name, std::shared_ptr serv = serv_iter->second; if (use_otl_command(*serv)) { nagios_macros* macros(get_global_macros()); - ret |= _otel_command_to_stream( + ret |= _otel_connector_to_stream( serv->check_command(), serv->get_check_command_line(macros), serv->get_hostname(), serv->name(), request_body); clear_volatile_macros_r(macros); diff --git a/engine/modules/opentelemetry/src/telegraf/nagios_converter.cc b/engine/modules/opentelemetry/src/telegraf/nagios_check_result_builder.cc similarity index 97% rename from engine/modules/opentelemetry/src/telegraf/nagios_converter.cc rename to engine/modules/opentelemetry/src/telegraf/nagios_check_result_builder.cc index 1078ee3e8e3..7c96fb57d25 100644 --- a/engine/modules/opentelemetry/src/telegraf/nagios_converter.cc +++ b/engine/modules/opentelemetry/src/telegraf/nagios_check_result_builder.cc @@ -17,9 +17,9 @@ */ #include "data_point_fifo_container.hh" -#include "otl_converter.hh" +#include "otl_check_result_builder.hh" -#include "telegraf/nagios_converter.hh" +#include "telegraf/nagios_check_result_builder.hh" using namespace com::centreon::engine::modules::opentelemetry::telegraf; @@ -158,8 +158,9 @@ static std::string_view get_nagios_telegraf_suffix( * check_icmp_state * @return com::centreon::engine::commands::result */ -bool nagios_converter::_build_result_from_metrics(metric_name_to_fifo& fifos, - commands::result& res) { +bool nagios_check_result_builder::_build_result_from_metrics( + metric_name_to_fifo& fifos, + commands::result& res) { // first we search last state timestamp uint64_t last_time = 0; diff --git a/engine/src/commands/CMakeLists.txt b/engine/src/commands/CMakeLists.txt index 1ac102e9129..1c094f5c580 100644 --- a/engine/src/commands/CMakeLists.txt +++ b/engine/src/commands/CMakeLists.txt @@ -31,7 +31,7 @@ set( "${SRC_DIR}/connector.cc" "${SRC_DIR}/environment.cc" "${SRC_DIR}/forward.cc" - "${SRC_DIR}/otel_command.cc" + "${SRC_DIR}/otel_connector.cc" "${SRC_DIR}/otel_interface.cc" "${SRC_DIR}/processing.cc" "${SRC_DIR}/raw.cc" diff --git a/engine/src/commands/otel_command.cc b/engine/src/commands/otel_connector.cc similarity index 73% rename from engine/src/commands/otel_command.cc rename to engine/src/commands/otel_connector.cc index bab48809b64..44538b01e0f 100644 --- a/engine/src/commands/otel_command.cc +++ b/engine/src/commands/otel_connector.cc @@ -16,7 +16,7 @@ * For more information : contact@centreon.com */ -#include "com/centreon/engine/commands/otel_command.hh" +#include "com/centreon/engine/commands/otel_connector.hh" #include "com/centreon/exceptions/msg_fmt.hh" #include "common/log_v2/log_v2.hh" @@ -24,24 +24,24 @@ using namespace com::centreon::engine::commands; using log_v2 = com::centreon::common::log_v2::log_v2; /** - * @brief static list of all otel_command + * @brief static list of all otel_connector * */ -absl::flat_hash_map> - otel_command::_commands; +absl::flat_hash_map> + otel_connector::_commands; /** - * @brief create an otel_command + * @brief create an otel_connector * * @param connector_name * @param cmd_line * @param listener */ -void otel_command::create(const std::string& connector_name, - const std::string& cmd_line, - commands::command_listener* listener) { - std::shared_ptr cmd( - std::make_shared(connector_name, cmd_line, listener)); +void otel_connector::create(const std::string& connector_name, + const std::string& cmd_line, + commands::command_listener* listener) { + std::shared_ptr cmd( + std::make_shared(connector_name, cmd_line, listener)); auto iter_res = _commands.emplace(connector_name, cmd); if (!iter_res.second) { iter_res.first->second = cmd; @@ -55,7 +55,7 @@ void otel_command::create(const std::string& connector_name, * @return true * @return false */ -bool otel_command::remove(const std::string& connector_name) { +bool otel_connector::remove(const std::string& connector_name) { return _commands.erase(connector_name); } @@ -67,8 +67,8 @@ bool otel_command::remove(const std::string& connector_name) { * @return true the otel command was found and hist update method was called * @return false the otel command doesn't exist */ -bool otel_command::update(const std::string& connector_name, - const std::string& cmd_line) { +bool otel_connector::update(const std::string& connector_name, + const std::string& cmd_line) { auto search = _commands.find(connector_name); if (search == _commands.end()) { return false; @@ -81,20 +81,20 @@ bool otel_command::update(const std::string& connector_name, * @brief get otel command from connector name * * @param connector_name - * @return std::shared_ptr + * @return std::shared_ptr */ -std::shared_ptr otel_command::get_otel_command( +std::shared_ptr otel_connector::get_otel_connector( const std::string& connector_name) { auto search = _commands.find(connector_name); return search != _commands.end() ? search->second - : std::shared_ptr(); + : std::shared_ptr(); } /** * @brief erase all otel commands * */ -void otel_command::clear() { +void otel_connector::clear() { _commands.clear(); } @@ -102,7 +102,7 @@ void otel_command::clear() { * @brief to call once otel module have been loaded * */ -void otel_command::init_all() { +void otel_connector::init_all() { for (auto& to_init : _commands) { to_init.second->init(); } @@ -117,9 +117,9 @@ void otel_command::init_all() { * @param cmd_line * @param listener */ -otel_command::otel_command(const std::string& connector_name, - const std::string& cmd_line, - commands::command_listener* listener) +otel_connector::otel_connector(const std::string& connector_name, + const std::string& cmd_line, + commands::command_listener* listener) : command(connector_name, cmd_line, listener, e_type::otel), _host_serv_list(std::make_shared()), _logger(log_v2::instance().get(log_v2::OTEL)) { @@ -131,7 +131,7 @@ otel_command::otel_command(const std::string& connector_name, * * @param cmd_line */ -void otel_command::update(const std::string& cmd_line) { +void otel_connector::update(const std::string& cmd_line) { if (get_command_line() == cmd_line) { return; } @@ -150,11 +150,11 @@ void otel_command::update(const std::string& cmd_line) { * @param caller * @return uint64_t */ -uint64_t otel_command::run(const std::string& processed_cmd, - nagios_macros& macros, - uint32_t timeout, - const check_result::pointer& to_push_to_checker, - const void* caller) { +uint64_t otel_connector::run(const std::string& processed_cmd, + nagios_macros& macros, + uint32_t timeout, + const check_result::pointer& to_push_to_checker, + const void* caller) { std::shared_ptr otel = otel::open_telemetry_base::instance(); @@ -180,17 +180,18 @@ uint64_t otel_command::run(const std::string& processed_cmd, "{} unable to do a check without a converter configuration", get_name()); } - SPDLOG_LOGGER_TRACE(_logger, - "otel_command::async_run: connector='{}', command_id={}, " - "cmd='{}', timeout={}", - _name, command_id, processed_cmd, timeout); + SPDLOG_LOGGER_TRACE( + _logger, + "otel_connector::async_run: connector='{}', command_id={}, " + "cmd='{}', timeout={}", + _name, command_id, processed_cmd, timeout); result res; bool res_available = otel->check( processed_cmd, _conv_conf, command_id, macros, timeout, res, [me = shared_from_this(), command_id](const result& async_res) { SPDLOG_LOGGER_TRACE( - me->_logger, "otel_command async_run callback: connector='{}' {}", + me->_logger, "otel_connector async_run callback: connector='{}' {}", me->_name, async_res); me->update_result_cache(command_id, async_res); if (me->_listener) { @@ -200,7 +201,7 @@ uint64_t otel_command::run(const std::string& processed_cmd, if (res_available) { SPDLOG_LOGGER_TRACE(_logger, - "otel_command data available : connector='{}', " + "otel_connector data available : connector='{}', " "cmd='{}', {}", _name, processed_cmd, res); update_result_cache(command_id, res); @@ -222,10 +223,10 @@ uint64_t otel_command::run(const std::string& processed_cmd, * @param timeout timeout in seconds * @param res check result */ -void otel_command::run(const std::string& processed_cmd, - nagios_macros& macros, - uint32_t timeout, - result& res) { +void otel_connector::run(const std::string& processed_cmd, + nagios_macros& macros, + uint32_t timeout, + result& res) { std::shared_ptr otel = otel::open_telemetry_base::instance(); if (!otel) { @@ -239,7 +240,7 @@ void otel_command::run(const std::string& processed_cmd, uint64_t command_id(get_uniq_id()); SPDLOG_LOGGER_TRACE(_logger, - "otel_command::sync_run: connector='{}', cmd='{}', " + "otel_connector::sync_run: connector='{}', cmd='{}', " "command_id={}, timeout={}", _name, processed_cmd, command_id, timeout); @@ -253,13 +254,13 @@ void otel_command::run(const std::string& processed_cmd, cv.notify_one(); }); - // no data_point available => wait util available or timeout + // no otl_data_point available => wait util available or timeout if (!res_available) { std::unique_lock l(cv_m); cv.wait(l); } SPDLOG_LOGGER_TRACE( - _logger, "otel_command::end sync_run: connector='{}', cmd='{}', {}", + _logger, "otel_connector::end sync_run: connector='{}', cmd='{}', {}", _name, processed_cmd, res); } @@ -270,7 +271,7 @@ void otel_command::run(const std::string& processed_cmd, * otel module loading * */ -void otel_command::init() { +void otel_connector::init() { try { if (!_extractor) { std::shared_ptr otel = @@ -291,7 +292,8 @@ void otel_command::init() { std::shared_ptr otel = otel::open_telemetry_base::instance(); if (otel) { - _conv_conf = otel->create_converter_config(get_command_line()); + _conv_conf = + otel->create_check_result_builder_config(get_command_line()); } } } catch (const std::exception& e) { @@ -308,8 +310,9 @@ void otel_command::init() { * @param host * @param service_description empty if host command */ -void otel_command::register_host_serv(const std::string& host, - const std::string& service_description) { +void otel_connector::register_host_serv( + const std::string& host, + const std::string& service_description) { _host_serv_list->register_host_serv(host, service_description); } @@ -320,8 +323,8 @@ void otel_command::register_host_serv(const std::string& host, * @param host * @param service_description empty if host command */ -void otel_command::unregister_host_serv( +void otel_connector::unregister_host_serv( const std::string& host, const std::string& service_description) { - _host_serv_list->unregister_host_serv(host, service_description); + _host_serv_list->remove(host, service_description); } diff --git a/engine/src/commands/otel_interface.cc b/engine/src/commands/otel_interface.cc index 6e733c75c24..19d5559b1fb 100644 --- a/engine/src/commands/otel_interface.cc +++ b/engine/src/commands/otel_interface.cc @@ -34,9 +34,8 @@ void host_serv_list::register_host_serv( _data[host].insert(service_description); } -void host_serv_list::unregister_host_serv( - const std::string& host, - const std::string& service_description) { +void host_serv_list::remove(const std::string& host, + const std::string& service_description) { absl::WriterMutexLock l(&_data_m); auto host_search = _data.find(host); if (host_search != _data.end()) { @@ -55,8 +54,8 @@ void host_serv_list::unregister_host_serv( * @return true found * @return false not found */ -bool host_serv_list::is_allowed(const std::string& host, - const std::string& service_description) const { +bool host_serv_list::contains(const std::string& host, + const std::string& service_description) const { absl::ReaderMutexLock l(&_data_m); auto host_search = _data.find(host); if (host_search != _data.end()) { diff --git a/engine/src/configuration/applier/command.cc b/engine/src/configuration/applier/command.cc index ee8ae3809a3..c8bd72bdf67 100644 --- a/engine/src/configuration/applier/command.cc +++ b/engine/src/configuration/applier/command.cc @@ -22,7 +22,7 @@ #include "com/centreon/engine/checks/checker.hh" #include "com/centreon/engine/commands/connector.hh" #include "com/centreon/engine/commands/forward.hh" -#include "com/centreon/engine/commands/otel_command.hh" +#include "com/centreon/engine/commands/otel_connector.hh" #include "com/centreon/engine/commands/raw.hh" #include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/exceptions/error.hh" @@ -70,8 +70,8 @@ void applier::command::add_object(configuration::command const& obj) { obj.command_name(), obj.command_line(), found_con->second)}; commands::command::commands[forward->get_name()] = forward; } else { - std::shared_ptr otel_cmd = - commands::otel_command::get_otel_command(obj.connector()); + std::shared_ptr otel_cmd = + commands::otel_connector::get_otel_connector(obj.connector()); if (otel_cmd) { std::shared_ptr forward{ std::make_shared(obj.command_name(), @@ -149,8 +149,8 @@ void applier::command::modify_object(configuration::command const& obj) { obj.command_name(), obj.command_line(), found_con->second)}; commands::command::commands[forward->get_name()] = forward; } else { - std::shared_ptr otel_cmd = - commands::otel_command::get_otel_command(obj.connector()); + std::shared_ptr otel_cmd = + commands::otel_connector::get_otel_connector(obj.connector()); if (otel_cmd) { std::shared_ptr forward{ std::make_shared(obj.command_name(), @@ -214,7 +214,7 @@ void applier::command::resolve_object(configuration::command const& obj) { connector_map::iterator found{ commands::connector::connectors.find(obj.connector())}; if (found == commands::connector::connectors.end() || !found->second) { - if (!commands::otel_command::get_otel_command(obj.connector())) + if (!commands::otel_connector::get_otel_connector(obj.connector())) throw engine_error() << "unknow command " << obj.connector(); } } diff --git a/engine/src/configuration/applier/connector.cc b/engine/src/configuration/applier/connector.cc index a5fcfd47d77..0fdf87f9c40 100644 --- a/engine/src/configuration/applier/connector.cc +++ b/engine/src/configuration/applier/connector.cc @@ -18,7 +18,7 @@ */ #include "com/centreon/engine/commands/connector.hh" #include "com/centreon/engine/checks/checker.hh" -#include "com/centreon/engine/commands/otel_command.hh" +#include "com/centreon/engine/commands/otel_connector.hh" #include "com/centreon/engine/configuration/applier/connector.hh" #include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/exceptions/error.hh" @@ -60,7 +60,7 @@ void applier::connector::add_object(configuration::connector const& obj) { size_t otel_pos = processed_cmd.find(_otel_fake_exe); if (otel_pos < end_path) { - commands::otel_command::create( + commands::otel_connector::create( obj.connector_name(), boost::algorithm::trim_copy( processed_cmd.substr(otel_pos + _otel_fake_exe.length())), @@ -121,12 +121,12 @@ void applier::connector::modify_object(configuration::connector const& obj) { std::string otel_cmdline = boost::algorithm::trim_copy( processed_cmd.substr(otel_pos + _otel_fake_exe.length())); - if (!commands::otel_command::update(obj.key(), processed_cmd)) { + if (!commands::otel_connector::update(obj.key(), processed_cmd)) { // connector object become an otel fake connector if (exist_connector != commands::connector::connectors.end()) { commands::connector::connectors.erase(exist_connector); - commands::otel_command::create(obj.key(), processed_cmd, - &checks::checker::instance()); + commands::otel_connector::create(obj.key(), processed_cmd, + &checks::checker::instance()); } else { throw com::centreon::exceptions::msg_fmt( "unknown open telemetry command to update: {}", obj.key()); @@ -137,8 +137,8 @@ void applier::connector::modify_object(configuration::connector const& obj) { // Set the new command line. exist_connector->second->set_command_line(processed_cmd); } else { - // old otel_command => connector - if (commands::otel_command::remove(obj.key())) { + // old otel_connector => connector + if (commands::otel_connector::remove(obj.key())) { auto cmd = std::make_shared( obj.connector_name(), processed_cmd, &checks::checker::instance()); commands::connector::connectors[obj.connector_name()] = cmd; @@ -174,7 +174,7 @@ void applier::connector::remove_object(configuration::connector const& obj) { commands::connector::connectors.erase(it); } - commands::otel_command::remove(obj.key()); + commands::otel_connector::remove(obj.key()); // Remove connector from the global configuration set. config->connectors().erase(obj); diff --git a/engine/src/configuration/applier/state.cc b/engine/src/configuration/applier/state.cc index c7cbb337439..c145c0d3ee2 100644 --- a/engine/src/configuration/applier/state.cc +++ b/engine/src/configuration/applier/state.cc @@ -21,7 +21,7 @@ #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/commands/connector.hh" -#include "com/centreon/engine/commands/otel_command.hh" +#include "com/centreon/engine/commands/otel_connector.hh" #include "com/centreon/engine/config.hh" #include "com/centreon/engine/configuration/applier/anomalydetection.hh" #include "com/centreon/engine/configuration/applier/command.hh" @@ -150,7 +150,7 @@ void applier::state::clear() { engine::hostgroup::hostgroups.clear(); engine::commands::command::commands.clear(); engine::commands::connector::connectors.clear(); - engine::commands::otel_command::clear(); + engine::commands::otel_connector::clear(); engine::service::services.clear(); engine::service::services_by_id.clear(); engine::servicedependency::servicedependencies.clear(); @@ -189,7 +189,7 @@ applier::state::~state() noexcept { engine::hostgroup::hostgroups.clear(); engine::commands::command::commands.clear(); engine::commands::connector::connectors.clear(); - engine::commands::otel_command::clear(); + engine::commands::otel_connector::clear(); engine::service::services.clear(); engine::service::services_by_id.clear(); engine::servicedependency::servicedependencies.clear(); diff --git a/engine/tests/opentelemetry/host_serv_extractor_test.cc b/engine/tests/opentelemetry/host_serv_extractor_test.cc index 4090ccca5f8..1e20e23d69a 100644 --- a/engine/tests/opentelemetry/host_serv_extractor_test.cc +++ b/engine/tests/opentelemetry/host_serv_extractor_test.cc @@ -33,8 +33,8 @@ TEST(otl_host_serv_extractor_test, empty_request) { std::make_shared<::opentelemetry::proto::collector::metrics::v1:: ExportMetricsServiceRequest>(); - data_point::extract_data_points( - request, [](const data_point& data_pt) { ASSERT_TRUE(false); }); + otl_data_point::extract_data_points( + request, [](const otl_data_point& data_pt) { ASSERT_TRUE(false); }); } class otl_host_serv_attributes_extractor_test : public ::testing::Test { @@ -83,8 +83,9 @@ TEST_F(otl_host_serv_attributes_extractor_test, resource_attrib) { unsigned data_point_extracted_cpt = 0; - data_point::extract_data_points( - request, [this, &data_point_extracted_cpt](const data_point& data_pt) { + otl_data_point::extract_data_points( + request, + [this, &data_point_extracted_cpt](const otl_data_point& data_pt) { ++data_point_extracted_cpt; commands::otel::host_serv_list::pointer host_srv_list = std::make_shared(); @@ -99,8 +100,9 @@ TEST_F(otl_host_serv_attributes_extractor_test, resource_attrib) { ASSERT_EQ(data_point_extracted_cpt, 1); - data_point::extract_data_points( - request, [this, &data_point_extracted_cpt](const data_point& data_pt) { + otl_data_point::extract_data_points( + request, + [this, &data_point_extracted_cpt](const otl_data_point& data_pt) { ++data_point_extracted_cpt; commands::otel::host_serv_list::pointer host_srv_list = std::make_shared(); @@ -110,8 +112,9 @@ TEST_F(otl_host_serv_attributes_extractor_test, resource_attrib) { ASSERT_TRUE(to_test.host.empty()); }); - data_point::extract_data_points( - request, [this, &data_point_extracted_cpt](const data_point& data_pt) { + otl_data_point::extract_data_points( + request, + [this, &data_point_extracted_cpt](const otl_data_point& data_pt) { ++data_point_extracted_cpt; commands::otel::host_serv_list::pointer host_srv_list = std::make_shared(); @@ -124,8 +127,9 @@ TEST_F(otl_host_serv_attributes_extractor_test, resource_attrib) { auto serv = resources->mutable_resource()->mutable_attributes()->Add(); serv->set_key("service"); serv->mutable_value()->set_string_value("my_serv"); - data_point::extract_data_points( - request, [this, &data_point_extracted_cpt](const data_point& data_pt) { + otl_data_point::extract_data_points( + request, + [this, &data_point_extracted_cpt](const otl_data_point& data_pt) { ++data_point_extracted_cpt; commands::otel::host_serv_list::pointer host_srv_list = std::make_shared(); @@ -137,8 +141,9 @@ TEST_F(otl_host_serv_attributes_extractor_test, resource_attrib) { ASSERT_EQ(to_test.metric, "metric cpu"); }); - data_point::extract_data_points( - request, [this, &data_point_extracted_cpt](const data_point& data_pt) { + otl_data_point::extract_data_points( + request, + [this, &data_point_extracted_cpt](const otl_data_point& data_pt) { ++data_point_extracted_cpt; commands::otel::host_serv_list::pointer host_srv_list = std::make_shared(); @@ -149,8 +154,9 @@ TEST_F(otl_host_serv_attributes_extractor_test, resource_attrib) { ASSERT_EQ(to_test.service, "my_serv"); ASSERT_EQ(to_test.metric, "metric cpu"); }); - data_point::extract_data_points( - request, [this, &data_point_extracted_cpt](const data_point& data_pt) { + otl_data_point::extract_data_points( + request, + [this, &data_point_extracted_cpt](const otl_data_point& data_pt) { ++data_point_extracted_cpt; commands::otel::host_serv_list::pointer host_srv_list = std::make_shared(); @@ -163,8 +169,9 @@ TEST_F(otl_host_serv_attributes_extractor_test, resource_attrib) { auto serv2 = resources->mutable_resource()->mutable_attributes()->Add(); serv2->set_key("service"); serv2->mutable_value()->set_string_value("my_serv2"); - data_point::extract_data_points( - request, [this, &data_point_extracted_cpt](const data_point& data_pt) { + otl_data_point::extract_data_points( + request, + [this, &data_point_extracted_cpt](const otl_data_point& data_pt) { ++data_point_extracted_cpt; commands::otel::host_serv_list::pointer host_srv_list = std::make_shared(); @@ -201,8 +208,9 @@ TEST_F(otl_host_serv_attributes_extractor_test, scope_attrib) { unsigned data_point_extracted_cpt = 0; - data_point::extract_data_points( - request, [this, &data_point_extracted_cpt](const data_point& data_pt) { + otl_data_point::extract_data_points( + request, + [this, &data_point_extracted_cpt](const otl_data_point& data_pt) { ++data_point_extracted_cpt; commands::otel::host_serv_list::pointer host_srv_list = std::make_shared(); @@ -217,8 +225,9 @@ TEST_F(otl_host_serv_attributes_extractor_test, scope_attrib) { ASSERT_EQ(data_point_extracted_cpt, 1); - data_point::extract_data_points( - request, [this, &data_point_extracted_cpt](const data_point& data_pt) { + otl_data_point::extract_data_points( + request, + [this, &data_point_extracted_cpt](const otl_data_point& data_pt) { ++data_point_extracted_cpt; commands::otel::host_serv_list::pointer host_srv_list = std::make_shared(); @@ -228,8 +237,9 @@ TEST_F(otl_host_serv_attributes_extractor_test, scope_attrib) { ASSERT_TRUE(to_test.host.empty()); }); - data_point::extract_data_points( - request, [this, &data_point_extracted_cpt](const data_point& data_pt) { + otl_data_point::extract_data_points( + request, + [this, &data_point_extracted_cpt](const otl_data_point& data_pt) { ++data_point_extracted_cpt; commands::otel::host_serv_list::pointer host_srv_list = std::make_shared(); @@ -242,8 +252,9 @@ TEST_F(otl_host_serv_attributes_extractor_test, scope_attrib) { auto serv = scope->mutable_scope()->mutable_attributes()->Add(); serv->set_key("service"); serv->mutable_value()->set_string_value("my_serv"); - data_point::extract_data_points( - request, [this, &data_point_extracted_cpt](const data_point& data_pt) { + otl_data_point::extract_data_points( + request, + [this, &data_point_extracted_cpt](const otl_data_point& data_pt) { ++data_point_extracted_cpt; commands::otel::host_serv_list::pointer host_srv_list = std::make_shared(); @@ -276,8 +287,9 @@ TEST_F(otl_host_serv_attributes_extractor_test, data_point_attrib) { unsigned data_point_extracted_cpt = 0; - data_point::extract_data_points( - request, [this, &data_point_extracted_cpt](const data_point& data_pt) { + otl_data_point::extract_data_points( + request, + [this, &data_point_extracted_cpt](const otl_data_point& data_pt) { ++data_point_extracted_cpt; commands::otel::host_serv_list::pointer host_srv_list = std::make_shared(); @@ -291,8 +303,9 @@ TEST_F(otl_host_serv_attributes_extractor_test, data_point_attrib) { ASSERT_EQ(data_point_extracted_cpt, 1); - data_point::extract_data_points( - request, [this, &data_point_extracted_cpt](const data_point& data_pt) { + otl_data_point::extract_data_points( + request, + [this, &data_point_extracted_cpt](const otl_data_point& data_pt) { ++data_point_extracted_cpt; commands::otel::host_serv_list::pointer host_srv_list = std::make_shared(); @@ -302,8 +315,9 @@ TEST_F(otl_host_serv_attributes_extractor_test, data_point_attrib) { ASSERT_TRUE(to_test.host.empty()); }); - data_point::extract_data_points( - request, [this, &data_point_extracted_cpt](const data_point& data_pt) { + otl_data_point::extract_data_points( + request, + [this, &data_point_extracted_cpt](const otl_data_point& data_pt) { ++data_point_extracted_cpt; commands::otel::host_serv_list::pointer host_srv_list = std::make_shared(); @@ -313,8 +327,9 @@ TEST_F(otl_host_serv_attributes_extractor_test, data_point_attrib) { ASSERT_TRUE(to_test.host.empty()); }); - data_point::extract_data_points( - request, [this, &data_point_extracted_cpt](const data_point& data_pt) { + otl_data_point::extract_data_points( + request, + [this, &data_point_extracted_cpt](const otl_data_point& data_pt) { ++data_point_extracted_cpt; commands::otel::host_serv_list::pointer host_srv_list = std::make_shared(); @@ -327,8 +342,9 @@ TEST_F(otl_host_serv_attributes_extractor_test, data_point_attrib) { auto serv = point->mutable_attributes()->Add(); serv->set_key("service"); serv->mutable_value()->set_string_value("my_serv"); - data_point::extract_data_points( - request, [this, &data_point_extracted_cpt](const data_point& data_pt) { + otl_data_point::extract_data_points( + request, + [this, &data_point_extracted_cpt](const otl_data_point& data_pt) { ++data_point_extracted_cpt; commands::otel::host_serv_list::pointer host_srv_list = std::make_shared(); diff --git a/engine/tests/opentelemetry/opentelemetry_test.cc b/engine/tests/opentelemetry/opentelemetry_test.cc index c06aa5579dc..d26d169ff87 100644 --- a/engine/tests/opentelemetry/opentelemetry_test.cc +++ b/engine/tests/opentelemetry/opentelemetry_test.cc @@ -163,10 +163,11 @@ TEST_F(open_telemetry_test, data_available) { nagios_macros macros; macros.host_ptr = host::hosts.begin()->second.get(); macros.service_ptr = service::services.begin()->second.get(); - ASSERT_TRUE(instance->check( - "nagios_telegraf", - instance->create_converter_config("--processor=nagios_telegraf"), 1, - macros, 1, res, [](const commands::result&) {})); + ASSERT_TRUE(instance->check("nagios_telegraf", + instance->create_check_result_builder_config( + "--processor=nagios_telegraf"), + 1, macros, 1, res, + [](const commands::result&) {})); ASSERT_EQ(res.command_id, 1); ASSERT_EQ(res.start_time.to_useconds(), 1707744430000000); ASSERT_EQ(res.end_time.to_useconds(), 1707744430000000); @@ -196,13 +197,14 @@ TEST_F(open_telemetry_test, timeout) { macros.service_ptr = service::services.begin()->second.get(); std::condition_variable cv; std::mutex cv_m; - ASSERT_FALSE(instance->check( - "nagios_telegraf", - instance->create_converter_config("--processor=nagios_telegraf"), 1, - macros, 1, res, [&res, &cv](const commands::result& async_res) { - res = async_res; - cv.notify_one(); - })); + ASSERT_FALSE(instance->check("nagios_telegraf", + instance->create_check_result_builder_config( + "--processor=nagios_telegraf"), + 1, macros, 1, res, + [&res, &cv](const commands::result& async_res) { + res = async_res; + cv.notify_one(); + })); std::unique_lock l(cv_m); ASSERT_EQ(cv.wait_for(l, std::chrono::seconds(3)), @@ -232,8 +234,8 @@ TEST_F(open_telemetry_test, wait_for_data) { std::mutex cv_m; std::condition_variable cv; bool data_available = instance->check( - "nagios_telegraf", instance->create_converter_config(otl_conf), 1, macros, - 1, res, [&res, &cv](const commands::result& async_res) { + "nagios_telegraf", instance->create_check_result_builder_config(otl_conf), + 1, macros, 1, res, [&res, &cv](const commands::result& async_res) { res = async_res; cv.notify_one(); }); diff --git a/engine/tests/opentelemetry/otl_converter_test.cc b/engine/tests/opentelemetry/otl_converter_test.cc index 65b3ea539b6..8ebc07f4282 100644 --- a/engine/tests/opentelemetry/otl_converter_test.cc +++ b/engine/tests/opentelemetry/otl_converter_test.cc @@ -37,8 +37,8 @@ #include "opentelemetry/proto/metrics/v1/metrics.pb.h" #include "com/centreon/engine/modules/opentelemetry/data_point_fifo_container.hh" -#include "com/centreon/engine/modules/opentelemetry/otl_converter.hh" -#include "com/centreon/engine/modules/opentelemetry/telegraf/nagios_converter.hh" +#include "com/centreon/engine/modules/opentelemetry/otl_check_result_builder.hh" +#include "com/centreon/engine/modules/opentelemetry/telegraf/nagios_check_result_builder.hh" #include "helper.hh" #include "test_engine.hh" @@ -81,7 +81,7 @@ void otl_converter_test::TearDown() { TEST_F(otl_converter_test, empty_fifo) { data_point_fifo_container empty; - telegraf::nagios_converter conv( + telegraf::nagios_check_result_builder conv( "", 1, *host::hosts.begin()->second, service::services.begin()->second.get(), std::chrono::system_clock::time_point(), [&](const commands::result&) {}, @@ -581,12 +581,13 @@ TEST_F(otl_converter_test, nagios_telegraf) { ::google::protobuf::util::JsonStringToMessage(telegraf_example, request.get()); - data_point::extract_data_points(request, [&](const data_point& data_pt) { - received.add_data_point("localhost", "check_icmp", - data_pt.get_metric().name(), data_pt); - }); + otl_data_point::extract_data_points( + request, [&](const otl_data_point& data_pt) { + received.add_data_point("localhost", "check_icmp", + data_pt.get_metric().name(), data_pt); + }); - telegraf::nagios_converter conv( + telegraf::nagios_check_result_builder conv( "", 1, *host::hosts.begin()->second, service::services.begin()->second.get(), std::chrono::system_clock::time_point(), [&](const commands::result&) {}, @@ -616,12 +617,13 @@ TEST_F(otl_converter_test, nagios_telegraf_le_ge) { ::google::protobuf::util::JsonStringToMessage(example, request.get()); - data_point::extract_data_points(request, [&](const data_point& data_pt) { - received.add_data_point("localhost", "check_icmp", - data_pt.get_metric().name(), data_pt); - }); + otl_data_point::extract_data_points( + request, [&](const otl_data_point& data_pt) { + received.add_data_point("localhost", "check_icmp", + data_pt.get_metric().name(), data_pt); + }); - telegraf::nagios_converter conv( + telegraf::nagios_check_result_builder conv( "", 1, *host::hosts.begin()->second, service::services.begin()->second.get(), std::chrono::system_clock::time_point(), [&](const commands::result&) {}, @@ -649,12 +651,13 @@ TEST_F(otl_converter_test, nagios_telegraf_max) { ::google::protobuf::util::JsonStringToMessage(example, request.get()); - data_point::extract_data_points(request, [&](const data_point& data_pt) { - received.add_data_point("localhost", "check_icmp", - data_pt.get_metric().name(), data_pt); - }); + otl_data_point::extract_data_points( + request, [&](const otl_data_point& data_pt) { + received.add_data_point("localhost", "check_icmp", + data_pt.get_metric().name(), data_pt); + }); - telegraf::nagios_converter conv( + telegraf::nagios_check_result_builder conv( "", 1, *host::hosts.begin()->second, service::services.begin()->second.get(), std::chrono::system_clock::time_point(), [&](const commands::result&) {}, diff --git a/tests/resources/opentelemetry/telegraf1.conf b/tests/resources/opentelemetry/telegraf1.conf deleted file mode 100644 index 413e25eeb85..00000000000 --- a/tests/resources/opentelemetry/telegraf1.conf +++ /dev/null @@ -1,36 +0,0 @@ -# Centreon telegraf configuration -# This telegraf configuration is generated by centreon centengine -[agent] - ## Default data collection interval for all inputs - interval = "60s" - -[[outputs.opentelemetry]] - service_address = "127.0.0.1:4317" - - -[[inputs.exec]] - name_override = "host_1__service_2" - commands = ["/usr/lib/nagios/plugins/check_icmp 127.0.0.2"] - data_format = "nagios" - [inputs.exec.tags] - host = "host_1" - service = "service_2" - - -[[inputs.exec]] - name_override = "host_1__service_1" - commands = ["/usr/lib/nagios/plugins/check_icmp 127.0.0.1"] - data_format = "nagios" - [inputs.exec.tags] - host = "host_1" - service = "service_1" - - -[[inputs.exec]] - name_override = "host_1__" - commands = ["/usr/lib/nagios/plugins/check_icmp 127.0.0.10"] - data_format = "nagios" - [inputs.exec.tags] - host = "host_1" - service = "" - diff --git a/tests/resources/opentelemetry/telegraf2.conf b/tests/resources/opentelemetry/telegraf2.conf deleted file mode 100644 index 17f0d8a7f6f..00000000000 --- a/tests/resources/opentelemetry/telegraf2.conf +++ /dev/null @@ -1,27 +0,0 @@ -# Centreon telegraf configuration -# This telegraf configuration is generated by centreon centengine -[agent] - ## Default data collection interval for all inputs - interval = "60s" - -[[outputs.opentelemetry]] - service_address = "127.0.0.1:4317" - - -[[inputs.exec]] - name_override = "host_3__service_5" - commands = ["/usr/lib/nagios/plugins/check_icmp 127.0.0.5"] - data_format = "nagios" - [inputs.exec.tags] - host = "host_3" - service = "service_5" - - -[[inputs.exec]] - name_override = "host_2__" - commands = ["/usr/lib/nagios/plugins/check_icmp 127.0.0.20"] - data_format = "nagios" - [inputs.exec.tags] - host = "host_2" - service = "" - From 69c90d426f1f7e707d30f7f2154b8a6fed5bc5d5 Mon Sep 17 00:00:00 2001 From: David Boucher Date: Fri, 7 Jun 2024 17:45:39 +0200 Subject: [PATCH 31/60] fix(engine): configuration module has its own logger (#1408) REFS: MON-111552 --- broker/core/src/main.cc | 2 + .../engine/configuration/connector.hh | 37 +- .../engine/configuration/extended_conf.hh | 1 + .../centreon/engine/configuration/object.hh | 1 + .../centreon/engine/configuration/parser.hh | 41 +- .../centreon/engine/configuration/state.hh | 4 +- .../engine/configuration/whitelist.hh | 12 +- engine/src/configuration/anomalydetection.cc | 274 ++------ engine/src/configuration/command.cc | 3 +- engine/src/configuration/connector.cc | 1 - engine/src/configuration/contactgroup.cc | 15 +- engine/src/configuration/extended_conf.cc | 18 +- engine/src/configuration/host.cc | 25 +- engine/src/configuration/hostdependency.cc | 15 +- engine/src/configuration/hostgroup.cc | 36 +- engine/src/configuration/object.cc | 12 +- engine/src/configuration/parser.cc | 24 +- engine/src/configuration/service.cc | 125 ++-- engine/src/configuration/servicedependency.cc | 3 +- engine/src/configuration/serviceescalation.cc | 54 +- engine/src/configuration/state.cc | 595 ++++++++---------- engine/src/configuration/whitelist.cc | 47 +- engine/src/main.cc | 8 +- tests/broker-engine/start-stop.robot | 1 + 24 files changed, 544 insertions(+), 810 deletions(-) diff --git a/broker/core/src/main.cc b/broker/core/src/main.cc index 7d910ae6d43..6dd584e2c0d 100644 --- a/broker/core/src/main.cc +++ b/broker/core/src/main.cc @@ -274,6 +274,8 @@ int main(int argc, char* argv[]) { config::parser parsr; config::state conf{parsr.parse(gl_mainconfigfiles.front())}; auto& log_conf = conf.log_conf(); + /* It is important to apply the log conf before broker threads start. + * Otherwise we will have issues with concurrent accesses. */ try { log_v2::instance().apply(log_conf); } catch (const std::exception& e) { diff --git a/engine/inc/com/centreon/engine/configuration/connector.hh b/engine/inc/com/centreon/engine/configuration/connector.hh index 98c6129d172..f94ff488609 100644 --- a/engine/inc/com/centreon/engine/configuration/connector.hh +++ b/engine/inc/com/centreon/engine/configuration/connector.hh @@ -1,22 +1,21 @@ -/* -** Copyright 2011-2013,2017 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2013,2017-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCE_CONFIGURATION_CONNECTOR_HH #define CCE_CONFIGURATION_CONNECTOR_HH diff --git a/engine/inc/com/centreon/engine/configuration/extended_conf.hh b/engine/inc/com/centreon/engine/configuration/extended_conf.hh index fbd65a3c6c3..28df0aa9958 100644 --- a/engine/inc/com/centreon/engine/configuration/extended_conf.hh +++ b/engine/inc/com/centreon/engine/configuration/extended_conf.hh @@ -31,6 +31,7 @@ class state; * */ class extended_conf { + std::shared_ptr _logger; std::string _path; struct stat _file_info; rapidjson::Document _content; diff --git a/engine/inc/com/centreon/engine/configuration/object.hh b/engine/inc/com/centreon/engine/configuration/object.hh index 4f0e00390df..62ccea67a47 100644 --- a/engine/inc/com/centreon/engine/configuration/object.hh +++ b/engine/inc/com/centreon/engine/configuration/object.hh @@ -119,6 +119,7 @@ class object { bool _should_register; list_string _templates; object_type _type; + std::shared_ptr _logger; }; typedef std::shared_ptr object_ptr; diff --git a/engine/inc/com/centreon/engine/configuration/parser.hh b/engine/inc/com/centreon/engine/configuration/parser.hh index be6652587cc..6b2924259dc 100644 --- a/engine/inc/com/centreon/engine/configuration/parser.hh +++ b/engine/inc/com/centreon/engine/configuration/parser.hh @@ -1,22 +1,21 @@ -/* -** Copyright 2011-2013,2017 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2013,2017-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCE_CONFIGURATION_PARSER_HH #define CCE_CONFIGURATION_PARSER_HH @@ -39,6 +38,8 @@ namespace com::centreon::engine { namespace configuration { class parser { + std::shared_ptr _logger; + public: enum read_options { read_commands = (1 << 0), @@ -61,7 +62,7 @@ class parser { }; parser(unsigned int read_options = read_all); - ~parser() throw(); + ~parser() noexcept = default; void parse(std::string const& path, state& config); private: diff --git a/engine/inc/com/centreon/engine/configuration/state.hh b/engine/inc/com/centreon/engine/configuration/state.hh index 5fa107fb945..b24712ae80c 100644 --- a/engine/inc/com/centreon/engine/configuration/state.hh +++ b/engine/inc/com/centreon/engine/configuration/state.hh @@ -61,6 +61,8 @@ class setter_base { * to manage configuration data. */ class state { + std::shared_ptr _logger; + public: /** * @enum state::date_format @@ -101,7 +103,7 @@ class state { state(); state(state const& right); - ~state() noexcept; + ~state() noexcept = default; state& operator=(state const& right); bool operator==(state const& right) const noexcept; bool operator!=(state const& right) const noexcept; diff --git a/engine/inc/com/centreon/engine/configuration/whitelist.hh b/engine/inc/com/centreon/engine/configuration/whitelist.hh index 134d46fbe57..7936621be18 100644 --- a/engine/inc/com/centreon/engine/configuration/whitelist.hh +++ b/engine/inc/com/centreon/engine/configuration/whitelist.hh @@ -20,8 +20,10 @@ #define CCE_CONFIGURATION_WHITELIST_HH #include "com/centreon/engine/globals.hh" +#include "common/log_v2/log_v2.hh" namespace com::centreon::engine::configuration { +using com::centreon::common::log_v2::log_v2; extern const std::string command_blacklist_output; @@ -40,6 +42,8 @@ string * */ class whitelist { + std::shared_ptr _logger; + // don't reorder values enum e_refresh_result { no_directory, empty_directory, no_rule, rules }; @@ -82,7 +86,8 @@ class whitelist { }; template -whitelist::whitelist(string_iter dir_path_begin, string_iter dir_path_end) { +whitelist::whitelist(string_iter dir_path_begin, string_iter dir_path_end) + : _logger{log_v2::instance().get(log_v2::CONFIG)} { init_ryml_error_handler(); e_refresh_result res = e_refresh_result::no_directory; for (; dir_path_begin != dir_path_end; ++dir_path_begin) { @@ -93,12 +98,11 @@ whitelist::whitelist(string_iter dir_path_begin, string_iter dir_path_end) { switch (res) { case e_refresh_result::no_directory: SPDLOG_LOGGER_INFO( - config_logger, - "no whitelist directory found, all commands are accepted"); + _logger, "no whitelist directory found, all commands are accepted"); break; case e_refresh_result::empty_directory: case e_refresh_result::no_rule: - SPDLOG_LOGGER_INFO(config_logger, + SPDLOG_LOGGER_INFO(_logger, "whitelist directory found, but no restrictions, " "all commands are accepted"); break; diff --git a/engine/src/configuration/anomalydetection.cc b/engine/src/configuration/anomalydetection.cc index 660ebcd2cb1..9b672055549 100644 --- a/engine/src/configuration/anomalydetection.cc +++ b/engine/src/configuration/anomalydetection.cc @@ -21,18 +21,15 @@ #include #include #include -#include "com/centreon/engine/customvariable.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" #include "com/centreon/engine/host.hh" -#include "com/centreon/engine/logging/logger.hh" extern int config_warnings; extern int config_errors; using namespace com::centreon; using namespace com::centreon::engine::configuration; -using namespace com::centreon::engine::logging; #define SETTER(type, method) \ &object::setter::generic @@ -323,442 +320,312 @@ anomalydetection& anomalydetection::operator=(anomalydetection const& other) { bool anomalydetection::operator==( anomalydetection const& other) const noexcept { if (!object::operator==(other)) { - engine_logger(dbg_config, more) - << "configuration::anomalydetection::equality => object don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::equality => object don't match"); return false; } if (_acknowledgement_timeout != other._acknowledgement_timeout) { - engine_logger(dbg_config, more) - << "configuration::anomalydetection::equality => " - "acknowledgement_timeout don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::equality => " "acknowledgement_timeout don't match"); return false; } if (_action_url != other._action_url) { - engine_logger(dbg_config, more) << "configuration::anomalydetection::" - "equality => action_url don't match"; - config_logger->debug( - "configuration::anomalydetection::" - "equality => action_url don't match"); + _logger->debug( + "configuration::anomalydetection::equality => action_url don't match"); return false; } if (_status_change != other._status_change) { - engine_logger(dbg_config, more) << "configuration::anomalydetection::" - "equality => status_change don't match"; - config_logger->debug( - "configuration::anomalydetection::" - "equality => status_change don't match"); + _logger->debug( + "configuration::anomalydetection::equality => status_change don't " + "match"); return false; } if (_checks_active != other._checks_active) { - engine_logger(dbg_config, more) << "configuration::anomalydetection::" - "equality => checks_active don't match"; - config_logger->debug( - "configuration::anomalydetection::" - "equality => checks_active don't match"); + _logger->debug( + "configuration::anomalydetection::equality => checks_active don't " + "match"); return false; } if (_checks_passive != other._checks_passive) { - engine_logger(dbg_config, more) << "configuration::anomalydetection::" - "equality => checks_passive don't match"; - config_logger->debug( - "configuration::anomalydetection::" - "equality => checks_passive don't match"); + _logger->debug( + "configuration::anomalydetection::equality => checks_passive don't " + "match"); return false; } if (_metric_name != other._metric_name) { - engine_logger(dbg_config, more) << "configuration::anomalydetection::" - "equality => metric_name don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::" "equality => metric_name don't match"); return false; } if (_thresholds_file != other._thresholds_file) { - engine_logger(dbg_config, more) - << "configuration::anomalydetection::equality => thresholds_file don't " - "match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::equality => thresholds_file don't " "match"); return false; } if (_check_freshness != other._check_freshness) { - engine_logger(dbg_config, more) - << "configuration::anomalydetection::equality => check_freshness don't " - "match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::equality => check_freshness don't " "match"); return false; } if (_check_interval != other._check_interval) { - engine_logger(dbg_config, more) << "configuration::anomalydetection::" - "equality => check_interval don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::" "equality => check_interval don't match"); return false; } if (_contactgroups != other._contactgroups) { - engine_logger(dbg_config, more) << "configuration::anomalydetection::" - "equality => contactgroups don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::" "equality => contactgroups don't match"); return false; } if (_contacts != other._contacts) { - engine_logger(dbg_config, more) - << "configuration::anomalydetection::equality => contacts don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::equality => contacts don't match"); return false; } if (std::operator!=(_customvariables, other._customvariables)) { - engine_logger(dbg_config, more) - << "configuration::anomalydetection::equality => customvariables don't " - "match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::equality => customvariables don't " "match"); return false; } if (_display_name != other._display_name) { - engine_logger(dbg_config, more) << "configuration::anomalydetection::" - "equality => display_name don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::" "equality => display_name don't match"); return false; } if (_event_handler != other._event_handler) { - engine_logger(dbg_config, more) << "configuration::anomalydetection::" - "equality => event_handler don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::" "equality => event_handler don't match"); return false; } if (_event_handler_enabled != other._event_handler_enabled) { - engine_logger(dbg_config, more) << "configuration::anomalydetection::" - "equality => event_handler don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::" "equality => event_handler don't match"); return false; } if (_first_notification_delay != other._first_notification_delay) { - engine_logger(dbg_config, more) - << "configuration::anomalydetection::equality => " - "first_notification_delay don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::equality => " "first_notification_delay don't match"); return false; } if (_flap_detection_enabled != other._flap_detection_enabled) { - engine_logger(dbg_config, more) - << "configuration::anomalydetection::equality => " - "flap_detection_enabled don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::equality => " "flap_detection_enabled don't match"); return false; } if (_flap_detection_options != other._flap_detection_options) { - engine_logger(dbg_config, more) - << "configuration::anomalydetection::equality => " - "flap_detection_options don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::equality => " "flap_detection_options don't match"); return false; } if (_freshness_threshold != other._freshness_threshold) { - engine_logger(dbg_config, more) - << "configuration::anomalydetection::equality => " - "freshness_threshold don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::equality => " "freshness_threshold don't match"); return false; } if (_high_flap_threshold != other._high_flap_threshold) { - engine_logger(dbg_config, more) - << "configuration::anomalydetection::equality => " - "high_flap_threshold don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::equality => " "high_flap_threshold don't match"); return false; } if (_host_name != other._host_name) { - engine_logger(dbg_config, more) << "configuration::anomalydetection::" - "equality => _host_name don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::" "equality => _host_name don't match"); return false; } if (_icon_image != other._icon_image) { - engine_logger(dbg_config, more) << "configuration::anomalydetection::" - "equality => icon_image don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::" "equality => icon_image don't match"); return false; } if (_icon_image_alt != other._icon_image_alt) { - engine_logger(dbg_config, more) << "configuration::anomalydetection::" - "equality => icon_image_alt don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::" "equality => icon_image_alt don't match"); return false; } if (_initial_state != other._initial_state) { - engine_logger(dbg_config, more) << "configuration::anomalydetection::" - "equality => initial_state don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::" "equality => initial_state don't match"); return false; } if (_is_volatile != other._is_volatile) { - engine_logger(dbg_config, more) << "configuration::anomalydetection::" - "equality => is_volatile don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::" "equality => is_volatile don't match"); return false; } if (_low_flap_threshold != other._low_flap_threshold) { - engine_logger(dbg_config, more) - << "configuration::anomalydetection::equality => low_flap_threshold " - "don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::equality => low_flap_threshold " "don't match"); return false; } if (_max_check_attempts != other._max_check_attempts) { - engine_logger(dbg_config, more) - << "configuration::anomalydetection::equality => max_check_attempts " - "don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::equality => max_check_attempts " "don't match"); return false; } if (_notes != other._notes) { - engine_logger(dbg_config, more) - << "configuration::anomalydetection::equality => notes don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::equality => notes don't match"); return false; } if (_notes_url != other._notes_url) { - engine_logger(dbg_config, more) - << "configuration::anomalydetection::equality => notes_url don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::equality => notes_url don't match"); return false; } if (_notifications_enabled != other._notifications_enabled) { - engine_logger(dbg_config, more) - << "configuration::anomalydetection::equality => " - "notifications_enabled don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::equality => " "notifications_enabled don't match"); return false; } if (_notification_interval != other._notification_interval) { - engine_logger(dbg_config, more) - << "configuration::anomalydetection::equality => " - "notification_interval don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::equality => " "notification_interval don't match"); return false; } if (_notification_options != other._notification_options) { - engine_logger(dbg_config, more) - << "configuration::anomalydetection::equality => " - "notification_options don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::equality => " "notification_options don't match"); return false; } if (_notification_period != other._notification_period) { - engine_logger(dbg_config, more) - << "configuration::anomalydetection::equality => " - "notification_period don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::equality => " "notification_period don't match"); return false; } if (_obsess_over_service != other._obsess_over_service) { - engine_logger(dbg_config, more) - << "configuration::anomalydetection::equality => " - "obsess_over_service don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::equality => " "obsess_over_service don't match"); return false; } if (_process_perf_data != other._process_perf_data) { - engine_logger(dbg_config, more) - << "configuration::anomalydetection::equality => process_perf_data " - "don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::equality => process_perf_data " "don't match"); return false; } if (_retain_nonstatus_information != other._retain_nonstatus_information) { - engine_logger(dbg_config, more) - << "configuration::anomalydetection::equality => " - "retain_nonstatus_information don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::equality => " "retain_nonstatus_information don't match"); return false; } if (_retain_status_information != other._retain_status_information) { - engine_logger(dbg_config, more) - << "configuration::anomalydetection::equality => " - "retain_status_information don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::equality => " "retain_status_information don't match"); return false; } if (_retry_interval != other._retry_interval) { - engine_logger(dbg_config, more) << "configuration::anomalydetection::" - "equality => retry_interval don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::" "equality => retry_interval don't match"); return false; } if (_recovery_notification_delay != other._recovery_notification_delay) { - engine_logger(dbg_config, more) - << "configuration::anomalydetection::equality => " - "recovery_notification_delay don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::equality => " "recovery_notification_delay don't match"); return false; } if (_servicegroups != other._servicegroups) { - engine_logger(dbg_config, more) << "configuration::anomalydetection::" - "equality => servicegroups don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::" "equality => servicegroups don't match"); return false; } if (_service_description != other._service_description) { - engine_logger(dbg_config, more) - << "configuration::anomalydetection::equality => " - "service_description don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::equality => " "service_description don't match"); return false; } if (_host_id != other._host_id) { - engine_logger(dbg_config, more) - << "configuration::anomalydetection::equality => host_id don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::equality => host_id don't match"); return false; } if (_host_id != other._host_id) { - engine_logger(dbg_config, more) - << "configuration::anomalydetection::equality => host_id don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::equality => host_id don't match"); return false; } if (_service_id != other._service_id) { - engine_logger(dbg_config, more) << "configuration::anomalydetection::" - "equality => service_id don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::" "equality => service_id don't match"); return false; } if (_internal_id != other._internal_id) { - config_logger->debug( + _logger->debug( "configuration::anomalydetection::equality => internal_id " "don't match"); return false; } if (_dependent_service_id != other._dependent_service_id) { - engine_logger(dbg_config, more) - << "configuration::anomalydetection::equality => dependent_service_id " - "don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::equality => dependent_service_id " "don't match"); return false; } if (_stalking_options != other._stalking_options) { - engine_logger(dbg_config, more) - << "configuration::anomalydetection::equality => stalking_options " - "don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::equality => stalking_options " "don't match"); return false; } if (_timezone != other._timezone) { - engine_logger(dbg_config, more) - << "configuration::anomalydetection::equality => timezone don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::equality => timezone don't match"); return false; } if (_severity_id != other._severity_id) { - engine_logger(dbg_config, more) << "configuration::anomalydetection::" - "equality => severity id don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::equality => severity id don't match"); return false; } if (_icon_id != other._icon_id) { - engine_logger(dbg_config, more) - << "configuration::anomalydetection::equality => icon id don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::equality => icon id don't match"); return false; } if (_tags != other._tags) { - engine_logger(dbg_config, more) - << "configuration::anomalydetection::equality => tags don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::equality => tags don't match"); return false; } if (_sensitivity != other._sensitivity) { - engine_logger(dbg_config, more) << "configuration::anomalydetection::" - "equality => sensitivity don't match"; - config_logger->debug( + _logger->debug( "configuration::anomalydetection::equality => sensitivity don't match"); return false; } - engine_logger(dbg_config, more) - << "configuration::anomalydetection::equality => OK"; - config_logger->debug("configuration::anomalydetection::equality => OK"); + _logger->debug("configuration::anomalydetection::equality => OK"); return true; } @@ -1748,10 +1615,7 @@ bool anomalydetection::_set_event_handler_enabled(bool value) { */ bool anomalydetection::_set_failure_prediction_enabled(bool value) { (void)value; - engine_logger(log_verification_error, basic) - << "Warning: anomalydetection failure_prediction_enabled is deprecated." - << " This option will not be supported in 20.04."; - config_logger->warn( + _logger->warn( "Warning: anomalydetection failure_prediction_enabled is deprecated. " "This option will not be supported in 20.04."); ++config_warnings; @@ -1768,10 +1632,7 @@ bool anomalydetection::_set_failure_prediction_enabled(bool value) { bool anomalydetection::_set_failure_prediction_options( std::string const& value) { (void)value; - engine_logger(log_verification_error, basic) - << "Warning: anomalydetection failure_prediction_options is deprecated." - << " This option will not be supported in 20.04."; - config_logger->warn( + _logger->warn( "Warning: anomalydetection failure_prediction_options is deprecated. " "This option will not be supported in 20.04."); ++config_warnings; @@ -2070,10 +1931,7 @@ bool anomalydetection::_set_obsess_over_service(bool value) { */ bool anomalydetection::_set_parallelize_check(bool value) { (void)value; - engine_logger(log_verification_error, basic) - << "Warning: anomalydetection parallelize_check is deprecated" - << " This option will not be supported in 20.04."; - config_logger->warn( + _logger->warn( "Warning: anomalydetection parallelize_check is deprecated This option " "will not be supported in 20.04."); ++config_warnings; @@ -2271,7 +2129,7 @@ bool anomalydetection::_set_category_tags(const std::string& value) { if (parse_ok) { _tags.emplace(id, tag::servicecategory); } else { - config_logger->warn( + _logger->warn( "Warning: anomalydetection ({}, {}) error for parsing tag {}", _host_id, _service_id, value); ret = false; @@ -2306,7 +2164,7 @@ bool anomalydetection::_set_group_tags(const std::string& value) { if (parse_ok) { _tags.emplace(id, tag::servicegroup); } else { - config_logger->warn( + _logger->warn( "Warning: anomalydetection ({}, {}) error for parsing tag {}", _host_id, _service_id, value); ret = false; diff --git a/engine/src/configuration/command.cc b/engine/src/configuration/command.cc index 6258d974196..2cde3522942 100644 --- a/engine/src/configuration/command.cc +++ b/engine/src/configuration/command.cc @@ -118,7 +118,6 @@ void command::check_validity() const { if (_command_line.empty()) throw(engine_error() << "Command '" << _command_name << "' has no command line (property 'command_line')"); - return; } /** @@ -127,7 +126,7 @@ void command::check_validity() const { * @return The command name. */ command::key_type const& command::key() const throw() { - return (_command_name); + return _command_name; } /** diff --git a/engine/src/configuration/connector.cc b/engine/src/configuration/connector.cc index 1e3b83d920f..83c637b8510 100644 --- a/engine/src/configuration/connector.cc +++ b/engine/src/configuration/connector.cc @@ -120,7 +120,6 @@ void connector::check_validity() const { throw( engine_error() << "Connector '" << _connector_name << "' has no command line (property 'connector_line')"); - return; } /** diff --git a/engine/src/configuration/contactgroup.cc b/engine/src/configuration/contactgroup.cc index 9bad91e0cf5..c9c05c5dd8b 100644 --- a/engine/src/configuration/contactgroup.cc +++ b/engine/src/configuration/contactgroup.cc @@ -53,7 +53,7 @@ contactgroup::contactgroup(contactgroup const& right) : object(right) { /** * Destructor. */ -contactgroup::~contactgroup() throw() {} +contactgroup::~contactgroup() noexcept {} /** * Copy constructor. @@ -70,7 +70,7 @@ contactgroup& contactgroup::operator=(contactgroup const& right) { _contactgroup_name = right._contactgroup_name; _members = right._members; } - return (*this); + return *this; } /** @@ -124,7 +124,6 @@ void contactgroup::check_validity() const { if (_contactgroup_name.empty()) throw(engine_error() << "Contact group has no name " "(property 'contactgroup_name')"); - return; } /** @@ -133,7 +132,7 @@ void contactgroup::check_validity() const { * @return The contact group name. */ contactgroup::key_type const& contactgroup::key() const throw() { - return (_contactgroup_name); + return _contactgroup_name; } /** @@ -175,7 +174,7 @@ bool contactgroup::parse(char const* key, char const* value) { * @return The alias. */ std::string const& contactgroup::alias() const throw() { - return (_alias); + return _alias; } /** @@ -232,7 +231,7 @@ set_string const& contactgroup::members() const throw() { */ bool contactgroup::_set_alias(std::string const& value) { _alias = value; - return (true); + return true; } /** @@ -244,7 +243,7 @@ bool contactgroup::_set_alias(std::string const& value) { */ bool contactgroup::_set_contactgroup_members(std::string const& value) { _contactgroup_members = value; - return (true); + return true; } /** @@ -256,7 +255,7 @@ bool contactgroup::_set_contactgroup_members(std::string const& value) { */ bool contactgroup::_set_contactgroup_name(std::string const& value) { _contactgroup_name = value; - return (true); + return true; } /** diff --git a/engine/src/configuration/extended_conf.cc b/engine/src/configuration/extended_conf.cc index 49d686dbd01..84d85c07ca0 100644 --- a/engine/src/configuration/extended_conf.cc +++ b/engine/src/configuration/extended_conf.cc @@ -20,8 +20,10 @@ #include "com/centreon/engine/configuration/state.hh" #include "com/centreon/engine/globals.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon::engine::configuration; +using com::centreon::common::log_v2::log_v2; std::list> extended_conf::_confs; @@ -31,17 +33,18 @@ std::list> extended_conf::_confs; * @param path of the configuration file * @throw exception if json malformed */ -extended_conf::extended_conf(const std::string& path) : _path(path) { +extended_conf::extended_conf(const std::string& path) + : _logger{log_v2::instance().get(log_v2::CONFIG)}, _path(path) { if (::stat(_path.c_str(), &_file_info)) { - SPDLOG_LOGGER_ERROR(config_logger, "can't access to {}", _path); + SPDLOG_LOGGER_ERROR(_logger, "can't access to {}", _path); throw exceptions::msg_fmt("can't access to {}", _path); } try { _content = common::rapidjson_helper::read_from_file(_path); - SPDLOG_LOGGER_INFO(config_logger, "extended conf file {} loaded", _path); + SPDLOG_LOGGER_INFO(_logger, "extended conf file {} loaded", _path); } catch (const std::exception& e) { SPDLOG_LOGGER_ERROR( - config_logger, + _logger, "extended_conf::extended_conf : fail to read json content from {}: {}", _path, e.what()); throw; @@ -57,9 +60,8 @@ extended_conf::extended_conf(const std::string& path) : _path(path) { void extended_conf::reload() { struct stat file_info; if (::stat(_path.c_str(), &file_info)) { - SPDLOG_LOGGER_ERROR(config_logger, - "can't access to {} anymore => we keep old content", - _path); + SPDLOG_LOGGER_ERROR( + _logger, "can't access to {} anymore => we keep old content", _path); return; } if (!memcmp(&file_info, &_file_info, sizeof(struct stat))) { @@ -69,7 +71,7 @@ void extended_conf::reload() { _content = common::rapidjson_helper::read_from_file(_path); _file_info = file_info; } catch (const std::exception& e) { - SPDLOG_LOGGER_ERROR(config_logger, + SPDLOG_LOGGER_ERROR(_logger, "extended_conf::extended_conf : fail to read json " "content from {} => we keep old content, cause: {}", _path, e.what()); diff --git a/engine/src/configuration/host.cc b/engine/src/configuration/host.cc index 707d77c0687..81dc5838a89 100644 --- a/engine/src/configuration/host.cc +++ b/engine/src/configuration/host.cc @@ -1267,12 +1267,8 @@ bool host::_set_event_handler_enabled(bool value) { * * @return True on success, otherwise false. */ -bool host::_set_failure_prediction_enabled(bool value) { - (void)value; - engine_logger(log_verification_error, basic) - << "Warning: host failure_prediction_enabled is deprecated" - << " This option will not be supported in 20.04."; - config_logger->warn( +bool host::_set_failure_prediction_enabled(bool value [[maybe_unused]]) { + _logger->warn( "Warning: host failure_prediction_enabled is deprecated This option will " "not be supported in 20.04."); ++config_warnings; @@ -1286,12 +1282,9 @@ bool host::_set_failure_prediction_enabled(bool value) { * * @return True on success, otherwise false. */ -bool host::_set_failure_prediction_options(std::string const& value) { - (void)value; - engine_logger(log_verification_error, basic) - << "Warning: service failure_prediction_options is deprecated" - << " This option will not be supported in 20.04."; - config_logger->warn( +bool host::_set_failure_prediction_options(const std::string& value + [[maybe_unused]]) { + _logger->warn( "Warning: service failure_prediction_options is deprecated This option " "will not be supported in 20.04."); ++config_warnings; @@ -1738,8 +1731,8 @@ bool host::_set_category_tags(const std::string& value) { if (parse_ok) { _tags.emplace(id, tag::hostcategory); } else { - config_logger->warn("Warning: host ({}) error for parsing tag {}", - _host_id, value); + _logger->warn("Warning: host ({}) error for parsing tag {}", _host_id, + value); ret = false; } } @@ -1772,8 +1765,8 @@ bool host::_set_group_tags(const std::string& value) { if (parse_ok) { _tags.emplace(id, tag::hostgroup); } else { - config_logger->warn("Warning: host ({}) error for parsing tag {}", - _host_id, value); + _logger->warn("Warning: host ({}) error for parsing tag {}", _host_id, + value); ret = false; } } diff --git a/engine/src/configuration/hostdependency.cc b/engine/src/configuration/hostdependency.cc index 1f7110b15ec..e4fe29ad219 100644 --- a/engine/src/configuration/hostdependency.cc +++ b/engine/src/configuration/hostdependency.cc @@ -90,7 +90,7 @@ hostdependency::hostdependency(hostdependency const& right) : object(right) { /** * Destructor. */ -hostdependency::~hostdependency() throw() {} +hostdependency::~hostdependency() noexcept {} /** * Copy constructor. @@ -122,7 +122,7 @@ hostdependency& hostdependency::operator=(hostdependency const& right) { * * @return True if is the same hostdependency, otherwise false. */ -bool hostdependency::operator==(hostdependency const& right) const throw() { +bool hostdependency::operator==(hostdependency const& right) const noexcept { return (object::operator==(right) && _dependency_period == right._dependency_period && _dependency_type == right._dependency_type && @@ -141,7 +141,7 @@ bool hostdependency::operator==(hostdependency const& right) const throw() { * * @return True if is not the same hostdependency, otherwise false. */ -bool hostdependency::operator!=(hostdependency const& right) const throw() { +bool hostdependency::operator!=(hostdependency const& right) const noexcept { return !operator==(right); } @@ -196,10 +196,7 @@ void hostdependency::check_validity() const { std::string dependend_host_name(!_dependent_hosts->empty() ? *_dependent_hosts->begin() : *_dependent_hostgroups->begin()); - engine_logger(log_config_warning, basic) - << "Warning: Ignoring lame host dependency of '" << dependend_host_name - << "' on host/hostgroups '" << host_name << "'."; - config_logger->warn( + _logger->warn( "Warning: Ignoring lame host dependency of '{}' on host/hostgroups " "'{}'.", dependend_host_name, host_name); @@ -404,7 +401,7 @@ bool hostdependency::inherits_parent() const noexcept { * @param[in] options New options. */ void hostdependency::notification_failure_options( - unsigned int options) throw() { + unsigned int options) noexcept { _notification_failure_options.set(options); } @@ -413,7 +410,7 @@ void hostdependency::notification_failure_options( * * @return The notification_failure_options. */ -unsigned int hostdependency::notification_failure_options() const throw() { +unsigned int hostdependency::notification_failure_options() const noexcept { return _notification_failure_options; } diff --git a/engine/src/configuration/hostgroup.cc b/engine/src/configuration/hostgroup.cc index 0e09a0b0c24..a9c66e163bd 100644 --- a/engine/src/configuration/hostgroup.cc +++ b/engine/src/configuration/hostgroup.cc @@ -91,58 +91,38 @@ hostgroup& hostgroup::operator=(hostgroup const& right) { */ bool hostgroup::operator==(hostgroup const& right) const throw() { if (!object::operator==(right)) { - engine_logger(dbg_config, more) - << "configuration::hostgroup::equality => object don't match"; - config_logger->debug( - "configuration::hostgroup::equality => object don't match"); + _logger->debug("configuration::hostgroup::equality => object don't match"); return false; } if (_action_url != right._action_url) { - engine_logger(dbg_config, more) - << "configuration::hostgroup::equality => action url don't match"; - config_logger->debug( + _logger->debug( "configuration::hostgroup::equality => action url don't match"); return false; } if (_alias != right._alias) { - engine_logger(dbg_config, more) - << "configuration::hostgroup::equality => alias don't match"; - config_logger->debug( - "configuration::hostgroup::equality => alias don't match"); + _logger->debug("configuration::hostgroup::equality => alias don't match"); return false; } if (_hostgroup_id != right._hostgroup_id) { - engine_logger(dbg_config, more) - << "configuration::hostgroup::equality => hostgroup id don't match"; - config_logger->debug( + _logger->debug( "configuration::hostgroup::equality => hostgroup id don't match"); return false; } if (_hostgroup_name != right._hostgroup_name) { - engine_logger(dbg_config, more) - << "configuration::hostgroup::equality => hostgroup name don't match"; - config_logger->debug( + _logger->debug( "configuration::hostgroup::equality => hostgroup name don't match"); return false; } if (_members != right._members) { - engine_logger(dbg_config, more) - << "configuration::hostgroup::equality => members don't match"; - config_logger->debug( - "configuration::hostgroup::equality => members don't match"); + _logger->debug("configuration::hostgroup::equality => members don't match"); return false; } if (_notes != right._notes) { - engine_logger(dbg_config, more) - << "configuration::hostgroup::equality => notes don't match"; - config_logger->debug( - "configuration::hostgroup::equality => notes don't match"); + _logger->debug("configuration::hostgroup::equality => notes don't match"); return false; } if (_notes_url != right._notes_url) { - engine_logger(dbg_config, more) - << "configuration::hostgroup::equality => notes url don't match"; - config_logger->debug( + _logger->debug( "configuration::hostgroup::equality => notes url don't match"); return false; } diff --git a/engine/src/configuration/object.cc b/engine/src/configuration/object.cc index 9eafe7d4e22..87c593a79c0 100644 --- a/engine/src/configuration/object.cc +++ b/engine/src/configuration/object.cc @@ -35,9 +35,11 @@ #include "com/centreon/engine/configuration/tag.hh" #include "com/centreon/engine/configuration/timeperiod.hh" #include "com/centreon/engine/exceptions/error.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon; using namespace com::centreon::engine::configuration; +using com::centreon::common::log_v2::log_v2; #define SETTER(type, method) \ &object::setter::generic @@ -53,7 +55,10 @@ object::setters const object::_setters[] = { * @param[in] type The object type. */ object::object(object::object_type type) - : _is_resolve(false), _should_register(true), _type(type) {} + : _is_resolve(false), + _should_register(true), + _type(type), + _logger{log_v2::instance().get(log_v2::CONFIG)} {} /** * Copy constructor. @@ -83,6 +88,7 @@ object& object::operator=(object const& right) { _should_register = right._should_register; _templates = right._templates; _type = right._type; + _logger = right._logger; } return *this; } @@ -261,7 +267,9 @@ std::string const& object::type_name() const noexcept { "serviceextinfo", "servicegroup", "timeperiod", - "anomalydetection"}; + "anomalydetection", + "severity", + "tag"}; return tab[_type]; } diff --git a/engine/src/configuration/parser.cc b/engine/src/configuration/parser.cc index 96df2e3ad45..29cd8f032ae 100644 --- a/engine/src/configuration/parser.cc +++ b/engine/src/configuration/parser.cc @@ -16,15 +16,16 @@ * For more information : contact@centreon.com * */ - #include "com/centreon/engine/configuration/parser.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" #include "com/centreon/io/directory_entry.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon; using namespace com::centreon::engine::configuration; using namespace com::centreon::io; +using com::centreon::common::log_v2::log_v2; parser::store parser::_store[] = { &parser::_store_into_map, @@ -77,12 +78,9 @@ static bool get_next_line(std::ifstream& stream, * (use to skip some object type). */ parser::parser(unsigned int read_options) - : _config(NULL), _read_options(read_options) {} - -/** - * Destructor. - */ -parser::~parser() throw() {} + : _logger{log_v2::instance().get(log_v2::CONFIG)}, + _config(nullptr), + _read_options(read_options) {} /** * Parse configuration file. @@ -309,9 +307,7 @@ void parser::_parse_directory_configuration(std::string const& path) { * @param[in] path The configuration path. */ void parser::_parse_global_configuration(const std::string& path) { - engine_logger(logging::log_info_message, logging::most) - << "Reading main configuration file '" << path << "'."; - config_logger->info("Reading main configuration file '{}'.", path); + _logger->info("Reading main configuration file '{}'.", path); std::ifstream stream(path.c_str(), std::ios::binary); if (!stream.is_open()) @@ -348,9 +344,7 @@ void parser::_parse_global_configuration(const std::string& path) { * @param[in] path The object definitions path. */ void parser::_parse_object_definitions(std::string const& path) { - engine_logger(logging::log_info_message, logging::basic) - << "Processing object config file '" << path << "'"; - config_logger->info("Processing object config file '{}'", path); + _logger->info("Processing object config file '{}'", path); std::ifstream stream(path, std::ios::binary); if (!stream.is_open()) @@ -427,9 +421,7 @@ void parser::_parse_object_definitions(std::string const& path) { * @param[in] path The resource file path. */ void parser::_parse_resource_file(std::string const& path) { - engine_logger(logging::log_info_message, logging::most) - << "Reading resource file '" << path << "'"; - config_logger->info("Reading resource file '{}'", path); + _logger->info("Reading resource file '{}'", path); std::ifstream stream(path.c_str(), std::ios::binary); if (!stream.is_open()) diff --git a/engine/src/configuration/service.cc b/engine/src/configuration/service.cc index 49d84efb0d1..e47f720ab87 100644 --- a/engine/src/configuration/service.cc +++ b/engine/src/configuration/service.cc @@ -307,14 +307,13 @@ bool service::operator==(service const& other) const noexcept { if (!object::operator==(other)) { engine_logger(dbg_config, more) << "configuration::service::equality => object don't match"; - config_logger->debug( - "configuration::service::equality => object don't match"); + _logger->debug("configuration::service::equality => object don't match"); return false; } if (_acknowledgement_timeout != other._acknowledgement_timeout) { engine_logger(dbg_config, more) << "configuration::service::equality => " "acknowledgement_timeout don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => " "acknowledgement_timeout don't match"); return false; @@ -322,105 +321,104 @@ bool service::operator==(service const& other) const noexcept { if (_action_url != other._action_url) { engine_logger(dbg_config, more) << "configuration::service::equality => action_url don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => action_url don't match"); return false; } if (_checks_active != other._checks_active) { engine_logger(dbg_config, more) << "configuration::service::equality => checks_active don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => checks_active don't match"); return false; } if (_checks_passive != other._checks_passive) { engine_logger(dbg_config, more) << "configuration::service::equality => checks_passive don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => checks_passive don't match"); return false; } if (_check_command != other._check_command) { engine_logger(dbg_config, more) << "configuration::service::equality => checks_passive don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => checks_passive don't match"); return false; } if (_check_command_is_important != other._check_command_is_important) { engine_logger(dbg_config, more) << "configuration::service::equality => check_command don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => check_command don't match"); return false; } if (_check_freshness != other._check_freshness) { engine_logger(dbg_config, more) << "configuration::service::equality => check_freshness don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => check_freshness don't match"); return false; } if (_check_interval != other._check_interval) { engine_logger(dbg_config, more) << "configuration::service::equality => check_interval don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => check_interval don't match"); return false; } if (_check_period != other._check_period) { engine_logger(dbg_config, more) << "configuration::service::equality => check_period don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => check_period don't match"); return false; } if (_contactgroups != other._contactgroups) { engine_logger(dbg_config, more) << "configuration::service::equality => contactgroups don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => contactgroups don't match"); return false; } if (_contacts != other._contacts) { engine_logger(dbg_config, more) << "configuration::service::equality => contacts don't match"; - config_logger->debug( - "configuration::service::equality => contacts don't match"); + _logger->debug("configuration::service::equality => contacts don't match"); return false; } if (std::operator!=(_customvariables, other._customvariables)) { engine_logger(dbg_config, more) << "configuration::service::equality => customvariables don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => customvariables don't match"); return false; } if (_display_name != other._display_name) { engine_logger(dbg_config, more) << "configuration::service::equality => display_name don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => display_name don't match"); return false; } if (_event_handler != other._event_handler) { engine_logger(dbg_config, more) << "configuration::service::equality => event_handler don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => event_handler don't match"); return false; } if (_event_handler_enabled != other._event_handler_enabled) { engine_logger(dbg_config, more) << "configuration::service::equality => event_handler don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => event_handler don't match"); return false; } if (_first_notification_delay != other._first_notification_delay) { engine_logger(dbg_config, more) << "configuration::service::equality => " "first_notification_delay don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => " "first_notification_delay don't match"); return false; @@ -428,7 +426,7 @@ bool service::operator==(service const& other) const noexcept { if (_flap_detection_enabled != other._flap_detection_enabled) { engine_logger(dbg_config, more) << "configuration::service::equality => " "flap_detection_enabled don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => " "flap_detection_enabled don't match"); return false; @@ -436,7 +434,7 @@ bool service::operator==(service const& other) const noexcept { if (_flap_detection_options != other._flap_detection_options) { engine_logger(dbg_config, more) << "configuration::service::equality => " "flap_detection_options don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => " "flap_detection_options don't match"); return false; @@ -444,7 +442,7 @@ bool service::operator==(service const& other) const noexcept { if (_freshness_threshold != other._freshness_threshold) { engine_logger(dbg_config, more) << "configuration::service::equality => " "freshness_threshold don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => " "freshness_threshold don't match"); return false; @@ -452,7 +450,7 @@ bool service::operator==(service const& other) const noexcept { if (_high_flap_threshold != other._high_flap_threshold) { engine_logger(dbg_config, more) << "configuration::service::equality => " "high_flap_threshold don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => " "high_flap_threshold don't match"); return false; @@ -460,77 +458,74 @@ bool service::operator==(service const& other) const noexcept { if (_hostgroups != other._hostgroups) { engine_logger(dbg_config, more) << "configuration::service::equality => hostgroups don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => hostgroups don't match"); return false; } if (_hosts != other._hosts) { engine_logger(dbg_config, more) << "configuration::service::equality => _hosts don't match"; - config_logger->debug( - "configuration::service::equality => _hosts don't match"); + _logger->debug("configuration::service::equality => _hosts don't match"); return false; } if (_icon_image != other._icon_image) { engine_logger(dbg_config, more) << "configuration::service::equality => icon_image don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => icon_image don't match"); return false; } if (_icon_image_alt != other._icon_image_alt) { engine_logger(dbg_config, more) << "configuration::service::equality => icon_image_alt don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => icon_image_alt don't match"); return false; } if (_initial_state != other._initial_state) { engine_logger(dbg_config, more) << "configuration::service::equality => initial_state don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => initial_state don't match"); return false; } if (_is_volatile != other._is_volatile) { engine_logger(dbg_config, more) << "configuration::service::equality => is_volatile don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => is_volatile don't match"); return false; } if (_low_flap_threshold != other._low_flap_threshold) { engine_logger(dbg_config, more) << "configuration::service::equality => low_flap_threshold don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => low_flap_threshold don't match"); return false; } if (_max_check_attempts != other._max_check_attempts) { engine_logger(dbg_config, more) << "configuration::service::equality => max_check_attempts don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => max_check_attempts don't match"); return false; } if (_notes != other._notes) { engine_logger(dbg_config, more) << "configuration::service::equality => notes don't match"; - config_logger->debug( - "configuration::service::equality => notes don't match"); + _logger->debug("configuration::service::equality => notes don't match"); return false; } if (_notes_url != other._notes_url) { engine_logger(dbg_config, more) << "configuration::service::equality => notes_url don't match"; - config_logger->debug( - "configuration::service::equality => notes_url don't match"); + _logger->debug("configuration::service::equality => notes_url don't match"); return false; } if (_notifications_enabled != other._notifications_enabled) { engine_logger(dbg_config, more) << "configuration::service::equality => " "notifications_enabled don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => " "notifications_enabled don't match"); return false; @@ -538,7 +533,7 @@ bool service::operator==(service const& other) const noexcept { if (_notification_interval != other._notification_interval) { engine_logger(dbg_config, more) << "configuration::service::equality => " "notification_interval don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => " "notification_interval don't match"); return false; @@ -546,7 +541,7 @@ bool service::operator==(service const& other) const noexcept { if (_notification_options != other._notification_options) { engine_logger(dbg_config, more) << "configuration::service::equality => " "notification_options don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => " "notification_options don't match"); return false; @@ -554,7 +549,7 @@ bool service::operator==(service const& other) const noexcept { if (_notification_period != other._notification_period) { engine_logger(dbg_config, more) << "configuration::service::equality => " "notification_period don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => " "notification_period don't match"); return false; @@ -562,7 +557,7 @@ bool service::operator==(service const& other) const noexcept { if (_obsess_over_service != other._obsess_over_service) { engine_logger(dbg_config, more) << "configuration::service::equality => " "obsess_over_service don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => " "obsess_over_service don't match"); return false; @@ -570,7 +565,7 @@ bool service::operator==(service const& other) const noexcept { if (_process_perf_data != other._process_perf_data) { engine_logger(dbg_config, more) << "configuration::service::equality => process_perf_data don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => process_perf_data don't match"); return false; } @@ -578,7 +573,7 @@ bool service::operator==(service const& other) const noexcept { engine_logger(dbg_config, more) << "configuration::service::equality => " "retain_nonstatus_information don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => " "retain_nonstatus_information don't match"); return false; @@ -586,7 +581,7 @@ bool service::operator==(service const& other) const noexcept { if (_retain_status_information != other._retain_status_information) { engine_logger(dbg_config, more) << "configuration::service::equality => " "retain_status_information don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => " "retain_status_information don't match"); return false; @@ -594,7 +589,7 @@ bool service::operator==(service const& other) const noexcept { if (_retry_interval != other._retry_interval) { engine_logger(dbg_config, more) << "configuration::service::equality => retry_interval don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => retry_interval don't match"); return false; } @@ -602,7 +597,7 @@ bool service::operator==(service const& other) const noexcept { engine_logger(dbg_config, more) << "configuration::service::equality => " "recovery_notification_delay don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => " "recovery_notification_delay don't match"); return false; @@ -610,14 +605,14 @@ bool service::operator==(service const& other) const noexcept { if (_servicegroups != other._servicegroups) { engine_logger(dbg_config, more) << "configuration::service::equality => servicegroups don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => servicegroups don't match"); return false; } if (_service_description != other._service_description) { engine_logger(dbg_config, more) << "configuration::service::equality => " "service_description don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => " "service_description don't match"); return false; @@ -625,54 +620,50 @@ bool service::operator==(service const& other) const noexcept { if (_host_id != other._host_id) { engine_logger(dbg_config, more) << "configuration::service::equality => host_id don't match"; - config_logger->debug( - "configuration::service::equality => host_id don't match"); + _logger->debug("configuration::service::equality => host_id don't match"); return false; } if (_service_id != other._service_id) { engine_logger(dbg_config, more) << "configuration::service::equality => service_id don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => service_id don't match"); return false; } if (_stalking_options != other._stalking_options) { engine_logger(dbg_config, more) << "configuration::service::equality => stalking_options don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => stalking_options don't match"); return false; } if (_timezone != other._timezone) { engine_logger(dbg_config, more) << "configuration::service::equality => timezone don't match"; - config_logger->debug( - "configuration::service::equality => timezone don't match"); + _logger->debug("configuration::service::equality => timezone don't match"); return false; } if (_severity_id != other._severity_id) { engine_logger(dbg_config, more) << "configuration::service::equality => severity id don't match"; - config_logger->debug( + _logger->debug( "configuration::service::equality => severity id don't match"); return false; } if (_icon_id != other._icon_id) { engine_logger(dbg_config, more) << "configuration::service::equality => icon id don't match"; - config_logger->debug( - "configuration::service::equality => icon id don't match"); + _logger->debug("configuration::service::equality => icon id don't match"); return false; } if (_tags != other._tags) { engine_logger(dbg_config, more) << "configuration::service::equality => tags don't match"; - config_logger->debug( - "configuration::service::equality => tags don't match"); + _logger->debug("configuration::service::equality => tags don't match"); return false; } engine_logger(dbg_config, more) << "configuration::service::equality => OK"; - config_logger->debug("configuration::service::equality => OK"); + _logger->debug("configuration::service::equality => OK"); return true; } @@ -1645,7 +1636,7 @@ bool service::_set_failure_prediction_enabled(bool value) { engine_logger(log_verification_error, basic) << "Warning: service failure_prediction_enabled is deprecated." << " This option will not be supported in 20.04."; - config_logger->warn( + _logger->warn( "Warning: service failure_prediction_enabled is deprecated. This option " "will not be supported in 20.04."); ++config_warnings; @@ -1664,7 +1655,7 @@ bool service::_set_failure_prediction_options(std::string const& value) { engine_logger(log_verification_error, basic) << "Warning: service failure_prediction_options is deprecated." << " This option will not be supported in 20.04."; - config_logger->warn( + _logger->warn( "Warning: service failure_prediction_options is deprecated. This option " "will not be supported in 20.04."); ++config_warnings; @@ -1978,7 +1969,7 @@ bool service::_set_parallelize_check(bool value) { engine_logger(log_verification_error, basic) << "Warning: service parallelize_check is deprecated" << " This option will not be supported in 20.04."; - config_logger->warn( + _logger->warn( "Warning: service parallelize_check is deprecated This option will not " "be supported in 20.04."); ++config_warnings; @@ -2152,8 +2143,8 @@ bool service::_set_category_tags(const std::string& value) { if (parse_ok) { _tags.emplace(id, tag::servicecategory); } else { - config_logger->warn("Warning: service ({}, {}) error for parsing tag {}", - _host_id, _service_id, value); + _logger->warn("Warning: service ({}, {}) error for parsing tag {}", + _host_id, _service_id, value); ret = false; } } @@ -2186,8 +2177,8 @@ bool service::_set_group_tags(const std::string& value) { if (parse_ok) { _tags.emplace(id, tag::servicegroup); } else { - config_logger->warn("Warning: service ({}, {}) error for parsing tag {}", - _host_id, _service_id, value); + _logger->warn("Warning: service ({}, {}) error for parsing tag {}", + _host_id, _service_id, value); ret = false; } } diff --git a/engine/src/configuration/servicedependency.cc b/engine/src/configuration/servicedependency.cc index 50798ee51c1..ebc0e7667ef 100644 --- a/engine/src/configuration/servicedependency.cc +++ b/engine/src/configuration/servicedependency.cc @@ -277,8 +277,7 @@ void servicedependency::check_validity() const { else msg << "host '" << _hosts->front() << "'"; } - engine_logger(log_config_warning, basic) << msg.str(); - config_logger->warn(msg.str()); + _logger->warn(msg.str()); } } diff --git a/engine/src/configuration/serviceescalation.cc b/engine/src/configuration/serviceescalation.cc index 729690709c1..19d7e005523 100644 --- a/engine/src/configuration/serviceescalation.cc +++ b/engine/src/configuration/serviceescalation.cc @@ -123,100 +123,70 @@ bool serviceescalation::operator==(serviceescalation const& right) const * constructor in almost all cases, we can have two equal escalations * with different uuid.*/ if (!object::operator==(right)) { - engine_logger(dbg_config, more) - << "configuration::serviceescalation::equality => object don't match"; - config_logger->debug( + _logger->debug( "configuration::serviceescalation::equality => object don't match"); return false; } if (_contactgroups != right._contactgroups) { - engine_logger(dbg_config, more) << "configuration::serviceescalation::" - "equality => contact groups don't match"; - config_logger->debug( + _logger->debug( "configuration::serviceescalation::" "equality => contact groups don't match"); return false; } if (_escalation_options != right._escalation_options) { - engine_logger(dbg_config, more) - << "configuration::serviceescalation::equality => escalation options " - "don't match"; - config_logger->debug( + _logger->debug( "configuration::serviceescalation::equality => escalation options " "don't match"); return false; } if (_escalation_period != right._escalation_period) { - engine_logger(dbg_config, more) - << "configuration::serviceescalation::equality => escalation periods " - "don't match"; - config_logger->debug( + _logger->debug( "configuration::serviceescalation::equality => escalation periods " "don't match"); return false; } if (_first_notification != right._first_notification) { - engine_logger(dbg_config, more) - << "configuration::serviceescalation::equality => first notifications " - "don't match"; - config_logger->debug( + _logger->debug( "configuration::serviceescalation::equality => first notifications " "don't match"); return false; } if (_hostgroups != right._hostgroups) { - engine_logger(dbg_config, more) << "configuration::serviceescalation::" - "equality => host groups don't match"; - config_logger->debug( + _logger->debug( "configuration::serviceescalation::" "equality => host groups don't match"); return false; } if (_hosts != right._hosts) { - engine_logger(dbg_config, more) - << "configuration::serviceescalation::equality => hosts don't match"; - config_logger->debug( + _logger->debug( "configuration::serviceescalation::equality => hosts don't match"); return false; } if (_last_notification != right._last_notification) { - engine_logger(dbg_config, more) - << "configuration::serviceescalation::equality => last notification " - "don't match"; - config_logger->debug( + _logger->debug( "configuration::serviceescalation::equality => last notification " "don't match"); return false; } if (_notification_interval != right._notification_interval) { - engine_logger(dbg_config, more) - << "configuration::serviceescalation::equality => notification " - "interval don't match"; - config_logger->debug( + _logger->debug( "configuration::serviceescalation::equality => notification " "interval don't match"); return false; } if (_servicegroups != right._servicegroups) { - engine_logger(dbg_config, more) << "configuration::serviceescalation::" - "equality => service groups don't match"; - config_logger->debug( + _logger->debug( "configuration::serviceescalation::" "equality => service groups don't match"); return false; } if (_service_description != right._service_description) { - engine_logger(dbg_config, more) - << "configuration::serviceescalation::equality => service descriptions " - "don't match"; - config_logger->debug( + _logger->debug( "configuration::serviceescalation::equality => service descriptions " "don't match"); return false; } - engine_logger(dbg_config, more) - << "configuration::serviceescalation::equality => OK"; - config_logger->debug("configuration::serviceescalation::equality => OK"); + _logger->debug("configuration::serviceescalation::equality => OK"); return true; } diff --git a/engine/src/configuration/state.cc b/engine/src/configuration/state.cc index 2f74aa66503..6d870495e20 100644 --- a/engine/src/configuration/state.cc +++ b/engine/src/configuration/state.cc @@ -33,7 +33,12 @@ using com::centreon::common::log_v2::log_v2; namespace com::centreon::engine::configuration::detail { template struct setter : public setter_base { - setter(const std::string_view& field_name) : setter_base(field_name) {} + std::shared_ptr _logger; + + setter(const std::string_view& field_name) + : setter_base(field_name), + _logger{log_v2::instance().get(log_v2::CONFIG)} {} + bool apply_from_cfg(state& obj, char const* value) override { try { U val(0); @@ -67,8 +72,8 @@ struct setter : public setter_base { std::is_same_v); } } catch (const std::exception& e) { - config_logger->error("Failed to parse '{}={}': {}", - setter_base::_field_name, value, e.what()); + _logger->error("Failed to parse '{}={}': {}", setter_base::_field_name, + value, e.what()); } return true; } @@ -79,7 +84,7 @@ struct setter : public setter_base { common::rapidjson_helper(doc).get(setter_base::_field_name.data()); (obj.*ptr)(val); } catch (std::exception const& e) { - SPDLOG_LOGGER_ERROR(config_logger, "fail to update {} : {}", + SPDLOG_LOGGER_ERROR(_logger, "fail to update {} : {}", setter_base::_field_name, e.what()); return false; } @@ -87,14 +92,19 @@ struct setter : public setter_base { } }; -template -struct setter : public setter_base { - setter(const std::string_view& field_name) : setter_base(field_name) {} +template +struct setter : public setter_base { + std::shared_ptr _logger; + + setter(const std::string_view& field_name) + : setter_base(field_name), + _logger{log_v2::instance().get(log_v2::CONFIG)} {} + bool apply_from_cfg(state& obj, char const* value) override { try { (obj.*ptr)(value); } catch (std::exception const& e) { - SPDLOG_LOGGER_ERROR(config_logger, "fail to update {} with value {}: {}", + SPDLOG_LOGGER_ERROR(_logger, "fail to update {} with value {}: {}", _field_name, value, e.what()); return false; } @@ -106,7 +116,7 @@ struct setter : public setter_base { common::rapidjson_helper(doc).get_string(_field_name.data()); (obj.*ptr)(val); } catch (std::exception const& e) { - SPDLOG_LOGGER_ERROR(config_logger, "fail to update {} : {}", _field_name, + SPDLOG_LOGGER_ERROR(_logger, "fail to update {} : {}", _field_name, e.what()); return false; } @@ -125,49 +135,49 @@ void state::_init_setter() { SETTER(bool, accept_passive_host_checks, "accept_passive_host_checks"); SETTER(bool, accept_passive_service_checks, "accept_passive_service_checks"); SETTER(int, additional_freshness_latency, "additional_freshness_latency"); - SETTER(std::string const&, admin_email, "admin_email"); - SETTER(std::string const&, admin_pager, "admin_pager"); - SETTER(std::string const&, _set_aggregate_status_updates, + SETTER(const std::string&, admin_email, "admin_email"); + SETTER(const std::string&, admin_pager, "admin_pager"); + SETTER(const std::string&, _set_aggregate_status_updates, "aggregate_status_updates"); SETTER(bool, allow_empty_hostgroup_assignment, "allow_empty_hostgroup_assignment"); - SETTER(std::string const&, _set_auth_file, "auth_file"); + SETTER(const std::string&, _set_auth_file, "auth_file"); SETTER(bool, auto_reschedule_checks, "auto_reschedule_checks"); SETTER(unsigned int, auto_rescheduling_interval, "auto_rescheduling_interval"); SETTER(unsigned int, auto_rescheduling_window, "auto_rescheduling_window"); - SETTER(std::string const&, _set_bare_update_check, "bare_update_check"); - SETTER(std::string const&, broker_module_directory, + SETTER(const std::string&, _set_bare_update_check, "bare_update_check"); + SETTER(const std::string&, broker_module_directory, "broker_module_directory"); - SETTER(std::string const&, _set_broker_module, "broker_module"); + SETTER(const std::string&, _set_broker_module, "broker_module"); SETTER(unsigned long, cached_host_check_horizon, "cached_host_check_horizon"); SETTER(unsigned long, cached_service_check_horizon, "cached_service_check_horizon"); - SETTER(std::string const&, _set_cfg_dir, "cfg_dir"); - SETTER(std::string const&, _set_cfg_file, "cfg_file"); + SETTER(const std::string&, _set_cfg_dir, "cfg_dir"); + SETTER(const std::string&, _set_cfg_file, "cfg_file"); SETTER(bool, check_external_commands, "check_external_commands"); SETTER(bool, check_orphaned_hosts, "check_for_orphaned_hosts"); SETTER(bool, check_orphaned_services, "check_for_orphaned_services"); - SETTER(std::string const&, _set_check_for_updates, "check_for_updates"); + SETTER(const std::string&, _set_check_for_updates, "check_for_updates"); SETTER(bool, check_host_freshness, "check_host_freshness"); SETTER(unsigned int, check_reaper_interval, "check_result_reaper_frequency"); SETTER(bool, check_service_freshness, "check_service_freshness"); - SETTER(std::string const&, _set_child_processes_fork_twice, + SETTER(const std::string&, _set_child_processes_fork_twice, "child_processes_fork_twice"); - SETTER(std::string const&, _set_command_check_interval, + SETTER(const std::string&, _set_command_check_interval, "command_check_interval"); - SETTER(std::string const&, command_file, "command_file"); - SETTER(std::string const&, _set_comment_file, "comment_file"); - SETTER(std::string const&, _set_daemon_dumps_core, "daemon_dumps_core"); - SETTER(std::string const&, _set_date_format, "date_format"); - SETTER(std::string const&, debug_file, "debug_file"); + SETTER(const std::string&, command_file, "command_file"); + SETTER(const std::string&, _set_comment_file, "comment_file"); + SETTER(const std::string&, _set_daemon_dumps_core, "daemon_dumps_core"); + SETTER(const std::string&, _set_date_format, "date_format"); + SETTER(const std::string&, debug_file, "debug_file"); SETTER(int64_t, debug_level, "debug_level"); SETTER(unsigned int, debug_verbosity, "debug_verbosity"); - SETTER(std::string const&, _set_downtime_file, "downtime_file"); - SETTER(std::string const&, _set_enable_embedded_perl, "enable_embedded_perl"); + SETTER(const std::string&, _set_downtime_file, "downtime_file"); + SETTER(const std::string&, _set_enable_embedded_perl, "enable_embedded_perl"); SETTER(bool, enable_environment_macros, "enable_environment_macros"); SETTER(bool, enable_event_handlers, "enable_event_handlers"); - SETTER(std::string const&, _set_enable_failure_prediction, + SETTER(const std::string&, _set_enable_failure_prediction, "enable_failure_prediction"); SETTER(bool, enable_flap_detection, "enable_flap_detection"); SETTER(bool, enable_macros_filter, "enable_macros_filter"); @@ -176,80 +186,80 @@ void state::_init_setter() { "enable_predictive_host_dependency_checks"); SETTER(bool, enable_predictive_service_dependency_checks, "enable_predictive_service_dependency_checks"); - SETTER(std::string const&, _set_event_broker_options, "event_broker_options"); + SETTER(const std::string&, _set_event_broker_options, "event_broker_options"); SETTER(unsigned int, event_handler_timeout, "event_handler_timeout"); SETTER(bool, execute_host_checks, "execute_host_checks"); SETTER(bool, execute_service_checks, "execute_service_checks"); SETTER(int, external_command_buffer_slots, "external_command_buffer_slots"); - SETTER(std::string const&, _set_free_child_process_memory, + SETTER(const std::string&, _set_free_child_process_memory, "free_child_process_memory"); - SETTER(std::string const&, global_host_event_handler, + SETTER(const std::string&, global_host_event_handler, "global_host_event_handler"); - SETTER(std::string const&, global_service_event_handler, + SETTER(const std::string&, global_service_event_handler, "global_service_event_handler"); SETTER(float, high_host_flap_threshold, "high_host_flap_threshold"); SETTER(float, high_service_flap_threshold, "high_service_flap_threshold"); SETTER(unsigned int, host_check_timeout, "host_check_timeout"); SETTER(unsigned int, host_freshness_check_interval, "host_freshness_check_interval"); - SETTER(std::string const&, _set_host_inter_check_delay_method, + SETTER(const std::string&, _set_host_inter_check_delay_method, "host_inter_check_delay_method"); - SETTER(std::string const&, host_perfdata_command, "host_perfdata_command"); - SETTER(std::string const&, host_perfdata_file, "host_perfdata_file"); - SETTER(std::string const&, _set_host_perfdata_file_mode, + SETTER(const std::string&, host_perfdata_command, "host_perfdata_command"); + SETTER(const std::string&, host_perfdata_file, "host_perfdata_file"); + SETTER(const std::string&, _set_host_perfdata_file_mode, "host_perfdata_file_mode"); - SETTER(std::string const&, host_perfdata_file_processing_command, + SETTER(const std::string&, host_perfdata_file_processing_command, "host_perfdata_file_processing_command"); SETTER(unsigned int, host_perfdata_file_processing_interval, "host_perfdata_file_processing_interval"); - SETTER(std::string const&, host_perfdata_file_template, + SETTER(const std::string&, host_perfdata_file_template, "host_perfdata_file_template"); - SETTER(std::string const&, illegal_output_chars, + SETTER(const std::string&, illegal_output_chars, "illegal_macro_output_chars"); - SETTER(std::string const&, illegal_object_chars, "illegal_object_name_chars"); + SETTER(const std::string&, illegal_object_chars, "illegal_object_name_chars"); SETTER(unsigned int, interval_length, "interval_length"); - SETTER(std::string const&, _set_lock_file, "lock_file"); - SETTER(std::string const&, _set_log_archive_path, "log_archive_path"); + SETTER(const std::string&, _set_lock_file, "lock_file"); + SETTER(const std::string&, _set_log_archive_path, "log_archive_path"); SETTER(bool, log_event_handlers, "log_event_handlers"); SETTER(bool, log_external_commands, "log_external_commands"); - SETTER(std::string const&, log_file, "log_file"); + SETTER(const std::string&, log_file, "log_file"); SETTER(bool, log_host_retries, "log_host_retries"); - SETTER(std::string const&, _set_log_initial_states, "log_initial_states"); + SETTER(const std::string&, _set_log_initial_states, "log_initial_states"); SETTER(bool, log_notifications, "log_notifications"); SETTER(bool, log_passive_checks, "log_passive_checks"); SETTER(bool, log_pid, "log_pid"); SETTER(bool, log_file_line, "log_file_line"); - SETTER(std::string const&, _set_log_rotation_method, "log_rotation_method"); + SETTER(const std::string&, _set_log_rotation_method, "log_rotation_method"); SETTER(bool, log_service_retries, "log_service_retries"); SETTER(float, low_host_flap_threshold, "low_host_flap_threshold"); SETTER(float, low_service_flap_threshold, "low_service_flap_threshold"); - SETTER(std::string const&, macros_filter, "macros_filter"); + SETTER(const std::string&, macros_filter, "macros_filter"); SETTER(unsigned int, max_parallel_service_checks, "max_concurrent_checks"); SETTER(unsigned long, max_debug_file_size, "max_debug_file_size"); SETTER(unsigned int, max_host_check_spread, "max_host_check_spread"); SETTER(unsigned long, max_log_file_size, "max_log_file_size"); SETTER(uint32_t, log_flush_period, "log_flush_period"); SETTER(unsigned int, max_service_check_spread, "max_service_check_spread"); - SETTER(std::string const&, _set_nagios_group, "nagios_group"); - SETTER(std::string const&, _set_nagios_user, "nagios_user"); + SETTER(const std::string&, _set_nagios_group, "nagios_group"); + SETTER(const std::string&, _set_nagios_user, "nagios_user"); SETTER(unsigned int, notification_timeout, "notification_timeout"); - SETTER(std::string const&, _set_object_cache_file, "object_cache_file"); + SETTER(const std::string&, _set_object_cache_file, "object_cache_file"); SETTER(bool, obsess_over_hosts, "obsess_over_hosts"); SETTER(bool, obsess_over_services, "obsess_over_services"); - SETTER(std::string const&, ochp_command, "ochp_command"); + SETTER(const std::string&, ochp_command, "ochp_command"); SETTER(unsigned int, ochp_timeout, "ochp_timeout"); - SETTER(std::string const&, ocsp_command, "ocsp_command"); + SETTER(const std::string&, ocsp_command, "ocsp_command"); SETTER(unsigned int, ocsp_timeout, "ocsp_timeout"); - SETTER(std::string const&, _set_p1_file, "p1_file"); + SETTER(const std::string&, _set_p1_file, "p1_file"); SETTER(int, perfdata_timeout, "perfdata_timeout"); - SETTER(std::string const&, poller_name, "poller_name"); + SETTER(const std::string&, poller_name, "poller_name"); SETTER(uint32_t, poller_id, "poller_id"); SETTER(uint16_t, rpc_port, "rpc_port"); SETTER(const std::string&, rpc_listen_address, "rpc_listen_address"); - SETTER(std::string const&, _set_precached_object_file, + SETTER(const std::string&, _set_precached_object_file, "precached_object_file"); SETTER(bool, process_performance_data, "process_performance_data"); - SETTER(std::string const&, _set_resource_file, "resource_file"); + SETTER(const std::string&, _set_resource_file, "resource_file"); SETTER(unsigned long, retained_contact_host_attribute_mask, "retained_contact_host_attribute_mask"); SETTER(unsigned long, retained_contact_service_attribute_mask, @@ -258,9 +268,9 @@ void state::_init_setter() { "retained_host_attribute_mask"); SETTER(unsigned long, retained_process_host_attribute_mask, "retained_process_host_attribute_mask"); - SETTER(std::string const&, _set_retained_process_service_attribute_mask, + SETTER(const std::string&, _set_retained_process_service_attribute_mask, "retained_process_service_attribute_mask"); - SETTER(std::string const&, _set_retained_service_attribute_mask, + SETTER(const std::string&, _set_retained_service_attribute_mask, "retained_service_attribute_mask"); SETTER(bool, retain_state_information, "retain_state_information"); SETTER(unsigned int, retention_scheduling_horizon, @@ -269,33 +279,33 @@ void state::_init_setter() { SETTER(unsigned int, service_check_timeout, "service_check_timeout"); SETTER(unsigned int, service_freshness_check_interval, "service_freshness_check_interval"); - SETTER(std::string const&, _set_service_inter_check_delay_method, + SETTER(const std::string&, _set_service_inter_check_delay_method, "service_inter_check_delay_method"); - SETTER(std::string const&, _set_service_interleave_factor_method, + SETTER(const std::string&, _set_service_interleave_factor_method, "service_interleave_factor"); - SETTER(std::string const&, service_perfdata_command, + SETTER(const std::string&, service_perfdata_command, "service_perfdata_command"); - SETTER(std::string const&, service_perfdata_file, "service_perfdata_file"); - SETTER(std::string const&, _set_service_perfdata_file_mode, + SETTER(const std::string&, service_perfdata_file, "service_perfdata_file"); + SETTER(const std::string&, _set_service_perfdata_file_mode, "service_perfdata_file_mode"); - SETTER(std::string const&, service_perfdata_file_processing_command, + SETTER(const std::string&, service_perfdata_file_processing_command, "service_perfdata_file_processing_command"); SETTER(unsigned int, service_perfdata_file_processing_interval, "service_perfdata_file_processing_interval"); - SETTER(std::string const&, service_perfdata_file_template, + SETTER(const std::string&, service_perfdata_file_template, "service_perfdata_file_template"); SETTER(unsigned int, check_reaper_interval, "service_reaper_frequency"); SETTER(float, sleep_time, "sleep_time"); SETTER(bool, soft_state_dependencies, "soft_state_dependencies"); - SETTER(std::string const&, state_retention_file, "state_retention_file"); - SETTER(std::string const&, status_file, "status_file"); + SETTER(const std::string&, state_retention_file, "state_retention_file"); + SETTER(const std::string&, status_file, "status_file"); SETTER(unsigned int, status_update_interval, "status_update_interval"); - SETTER(std::string const&, _set_temp_file, "temp_file"); - SETTER(std::string const&, _set_temp_path, "temp_path"); + SETTER(const std::string&, _set_temp_file, "temp_file"); + SETTER(const std::string&, _set_temp_path, "temp_path"); SETTER(unsigned int, time_change_threshold, "time_change_threshold"); SETTER(bool, use_aggressive_host_checking, "use_aggressive_host_checking"); SETTER(bool, use_aggressive_host_checking, "use_agressive_host_checking"); - SETTER(std::string const&, _set_use_embedded_perl_implicitly, + SETTER(const std::string&, _set_use_embedded_perl_implicitly, "use_embedded_perl_implicitly"); SETTER(bool, use_large_installation_tweaks, "use_large_installation_tweaks"); SETTER(uint32_t, instance_heartbeat_interval, "instance_heartbeat_interval"); @@ -306,27 +316,27 @@ void state::_init_setter() { SETTER(bool, use_syslog, "use_syslog"); SETTER(bool, log_v2_enabled, "log_v2_enabled"); SETTER(bool, log_legacy_enabled, "log_legacy_enabled"); - SETTER(std::string const&, log_v2_logger, "log_v2_logger"); - SETTER(std::string const&, log_level_functions, "log_level_functions"); - SETTER(std::string const&, log_level_config, "log_level_config"); - SETTER(std::string const&, log_level_events, "log_level_events"); - SETTER(std::string const&, log_level_checks, "log_level_checks"); - SETTER(std::string const&, log_level_notifications, + SETTER(const std::string&, log_v2_logger, "log_v2_logger"); + SETTER(const std::string&, log_level_functions, "log_level_functions"); + SETTER(const std::string&, log_level_config, "log_level_config"); + SETTER(const std::string&, log_level_events, "log_level_events"); + SETTER(const std::string&, log_level_checks, "log_level_checks"); + SETTER(const std::string&, log_level_notifications, "log_level_notifications"); - SETTER(std::string const&, log_level_eventbroker, "log_level_eventbroker"); - SETTER(std::string const&, log_level_external_command, + SETTER(const std::string&, log_level_eventbroker, "log_level_eventbroker"); + SETTER(const std::string&, log_level_external_command, "log_level_external_command"); - SETTER(std::string const&, log_level_commands, "log_level_commands"); - SETTER(std::string const&, log_level_downtimes, "log_level_downtimes"); - SETTER(std::string const&, log_level_comments, "log_level_comments"); - SETTER(std::string const&, log_level_macros, "log_level_macros"); - SETTER(std::string const&, log_level_process, "log_level_process"); - SETTER(std::string const&, log_level_runtime, "log_level_runtime"); - SETTER(std::string const&, log_level_otl, "log_level_otl"); - SETTER(std::string const&, use_timezone, "use_timezone"); + SETTER(const std::string&, log_level_commands, "log_level_commands"); + SETTER(const std::string&, log_level_downtimes, "log_level_downtimes"); + SETTER(const std::string&, log_level_comments, "log_level_comments"); + SETTER(const std::string&, log_level_macros, "log_level_macros"); + SETTER(const std::string&, log_level_process, "log_level_process"); + SETTER(const std::string&, log_level_runtime, "log_level_runtime"); + SETTER(const std::string&, log_level_otl, "log_level_otl"); + SETTER(const std::string&, use_timezone, "use_timezone"); SETTER(bool, use_true_regexp_matching, "use_true_regexp_matching"); - SETTER(std::string const&, _set_comment_file, "xcddefault_comment_file"); - SETTER(std::string const&, _set_downtime_file, "xdddefault_downtime_file"); + SETTER(const std::string&, _set_comment_file, "xcddefault_comment_file"); + SETTER(const std::string&, _set_downtime_file, "xdddefault_downtime_file"); SETTER(bool, use_send_recovery_notifications_anyways, "send_recovery_notifications_anyways"); } @@ -470,7 +480,8 @@ static const std::string default_rpc_listen_address("localhost"); * Default constructor. */ state::state() - : _accept_passive_host_checks(default_accept_passive_host_checks), + : _logger{log_v2::instance().get(log_v2::CONFIG)}, + _accept_passive_host_checks(default_accept_passive_host_checks), _accept_passive_service_checks(default_accept_passive_service_checks), _additional_freshness_latency(default_additional_freshness_latency), _admin_email(default_admin_email), @@ -620,11 +631,6 @@ state::state(state const& right) { operator=(right); } -/** - * Destructor. - */ -state::~state() noexcept {} - /** * Copy operator. * @@ -634,6 +640,7 @@ state::~state() noexcept {} */ state& state::operator=(state const& right) { if (this != &right) { + _logger = right._logger; _cfg_main = right._cfg_main; _accept_passive_host_checks = right._accept_passive_host_checks; _accept_passive_service_checks = right._accept_passive_service_checks; @@ -1032,7 +1039,7 @@ void state::additional_freshness_latency(int value) { * * @return The admin_email value. */ -std::string const& state::admin_email() const noexcept { +const std::string& state::admin_email() const noexcept { return _admin_email; } @@ -1041,7 +1048,7 @@ std::string const& state::admin_email() const noexcept { * * @param[in] value The new admin_email value. */ -void state::admin_email(std::string const& value) { +void state::admin_email(const std::string& value) { _admin_email = value; } @@ -1050,7 +1057,7 @@ void state::admin_email(std::string const& value) { * * @return The admin_pager value. */ -std::string const& state::admin_pager() const noexcept { +const std::string& state::admin_pager() const noexcept { return _admin_pager; } @@ -1059,7 +1066,7 @@ std::string const& state::admin_pager() const noexcept { * * @param[in] value The new admin_pager value. */ -void state::admin_pager(std::string const& value) { +void state::admin_pager(const std::string& value) { _admin_pager = value; } @@ -1162,7 +1169,7 @@ void state::broker_module(std::list const& value) { * * @return The broker_module_directory value. */ -std::string const& state::broker_module_directory() const noexcept { +const std::string& state::broker_module_directory() const noexcept { return _broker_module_directory; } @@ -1171,7 +1178,7 @@ std::string const& state::broker_module_directory() const noexcept { * * @param[in] value The new broker_module_directory value. */ -void state::broker_module_directory(std::string const& value) { +void state::broker_module_directory(const std::string& value) { if (value.empty() || value[0] == '/') _broker_module_directory = value; else { @@ -1249,7 +1256,7 @@ bool state::check_external_commands() const noexcept { * * @param[in] value The new cfg_main value. */ -void state::cfg_main(std::string const& value) { +void state::cfg_main(const std::string& value) { _cfg_main = value; } @@ -1258,7 +1265,7 @@ void state::cfg_main(std::string const& value) { * * @return The cfg_main value. */ -std::string const& state::cfg_main() const noexcept { +const std::string& state::cfg_main() const noexcept { return _cfg_main; } @@ -1506,7 +1513,7 @@ bool state::command_check_interval_is_seconds() const noexcept { * * @return The command_file value. */ -std::string const& state::command_file() const noexcept { +const std::string& state::command_file() const noexcept { return _command_file; } @@ -1515,7 +1522,7 @@ std::string const& state::command_file() const noexcept { * * @param[in] value The new command_file value. */ -void state::command_file(std::string const& value) { +void state::command_file(const std::string& value) { _command_file = value; } @@ -1709,7 +1716,7 @@ void state::date_format(date_type value) { * * @return The debug_file value. */ -std::string const& state::debug_file() const noexcept { +const std::string& state::debug_file() const noexcept { return _debug_file; } @@ -1718,7 +1725,7 @@ std::string const& state::debug_file() const noexcept { * * @param[in] value The new debug_file value. */ -void state::debug_file(std::string const& value) { +void state::debug_file(const std::string& value) { _debug_file = value; } @@ -1970,7 +1977,7 @@ void state::external_command_buffer_slots(int value) { * * @return The global_host_event_handler value. */ -std::string const& state::global_host_event_handler() const noexcept { +const std::string& state::global_host_event_handler() const noexcept { return _global_host_event_handler; } @@ -1979,7 +1986,7 @@ std::string const& state::global_host_event_handler() const noexcept { * * @param[in] value The new global_host_event_handler value. */ -void state::global_host_event_handler(std::string const& value) { +void state::global_host_event_handler(const std::string& value) { _global_host_event_handler = value; } @@ -1988,7 +1995,7 @@ void state::global_host_event_handler(std::string const& value) { * * @return The global_service_event_handler value. */ -std::string const& state::global_service_event_handler() const noexcept { +const std::string& state::global_service_event_handler() const noexcept { return _global_service_event_handler; } @@ -1997,7 +2004,7 @@ std::string const& state::global_service_event_handler() const noexcept { * * @param[in] value The new global_service_event_handler value. */ -void state::global_service_event_handler(std::string const& value) { +void state::global_service_event_handler(const std::string& value) { _global_service_event_handler = value; } @@ -2169,7 +2176,7 @@ set_host::const_iterator state::hosts_find(host::key_type const& k) const { return _hosts.end(); } -set_host::const_iterator state::hosts_find(std::string const& name) const { +set_host::const_iterator state::hosts_find(const std::string& name) const { for (set_host::const_iterator it(_hosts.begin()), end(_hosts.end()); it != end; ++it) { if (it->host_name() == name) @@ -2256,7 +2263,7 @@ void state::host_inter_check_delay_method(inter_check_delay value) { * * @return The host_perfdata_command value. */ -std::string const& state::host_perfdata_command() const noexcept { +const std::string& state::host_perfdata_command() const noexcept { return _host_perfdata_command; } @@ -2265,7 +2272,7 @@ std::string const& state::host_perfdata_command() const noexcept { * * @param[in] value The new host_perfdata_command value. */ -void state::host_perfdata_command(std::string const& value) { +void state::host_perfdata_command(const std::string& value) { _host_perfdata_command = value; } @@ -2274,7 +2281,7 @@ void state::host_perfdata_command(std::string const& value) { * * @return The host_perfdata_file value. */ -std::string const& state::host_perfdata_file() const noexcept { +const std::string& state::host_perfdata_file() const noexcept { return _host_perfdata_file; } @@ -2283,7 +2290,7 @@ std::string const& state::host_perfdata_file() const noexcept { * * @param[in] value The new host_perfdata_file value. */ -void state::host_perfdata_file(std::string const& value) { +void state::host_perfdata_file(const std::string& value) { _host_perfdata_file = value; } @@ -2310,7 +2317,7 @@ void state::host_perfdata_file_mode(perfdata_file_mode value) { * * @return The host_perfdata_file_processing_command value. */ -std::string const& state::host_perfdata_file_processing_command() +const std::string& state::host_perfdata_file_processing_command() const noexcept { return _host_perfdata_file_processing_command; } @@ -2320,7 +2327,7 @@ std::string const& state::host_perfdata_file_processing_command() * * @param[in] value The new host_perfdata_file_processing_command value. */ -void state::host_perfdata_file_processing_command(std::string const& value) { +void state::host_perfdata_file_processing_command(const std::string& value) { _host_perfdata_file_processing_command = value; } @@ -2347,7 +2354,7 @@ void state::host_perfdata_file_processing_interval(unsigned int value) { * * @return The host_perfdata_file_template value. */ -std::string const& state::host_perfdata_file_template() const noexcept { +const std::string& state::host_perfdata_file_template() const noexcept { return _host_perfdata_file_template; } @@ -2356,7 +2363,7 @@ std::string const& state::host_perfdata_file_template() const noexcept { * * @param[in] value The new host_perfdata_file_template value. */ -void state::host_perfdata_file_template(std::string const& value) { +void state::host_perfdata_file_template(const std::string& value) { _host_perfdata_file_template = value; } @@ -2365,7 +2372,7 @@ void state::host_perfdata_file_template(std::string const& value) { * * @return The illegal_object_chars value. */ -std::string const& state::illegal_object_chars() const noexcept { +const std::string& state::illegal_object_chars() const noexcept { return _illegal_object_chars; } @@ -2374,7 +2381,7 @@ std::string const& state::illegal_object_chars() const noexcept { * * @param[in] value The new illegal_object_chars value. */ -void state::illegal_object_chars(std::string const& value) { +void state::illegal_object_chars(const std::string& value) { _illegal_object_chars = value; } @@ -2383,7 +2390,7 @@ void state::illegal_object_chars(std::string const& value) { * * @return The illegal_output_chars value. */ -std::string const& state::illegal_output_chars() const noexcept { +const std::string& state::illegal_output_chars() const noexcept { return _illegal_output_chars; } @@ -2392,7 +2399,7 @@ std::string const& state::illegal_output_chars() const noexcept { * * @param[in] value The new illegal_output_chars value. */ -void state::illegal_output_chars(std::string const& value) { +void state::illegal_output_chars(const std::string& value) { _illegal_output_chars = value; } @@ -2463,7 +2470,7 @@ void state::log_external_commands(bool value) { * * @return The log_file value. */ -std::string const& state::log_file() const noexcept { +const std::string& state::log_file() const noexcept { return _log_file; } @@ -2472,7 +2479,7 @@ std::string const& state::log_file() const noexcept { * * @param[in] value The new log_file value. */ -void state::log_file(std::string const& value) { +void state::log_file(const std::string& value) { _log_file = value; } @@ -2790,7 +2797,7 @@ void state::obsess_over_services(bool value) { * * @return The ochp_command value. */ -std::string const& state::ochp_command() const noexcept { +const std::string& state::ochp_command() const noexcept { return _ochp_command; } @@ -2799,7 +2806,7 @@ std::string const& state::ochp_command() const noexcept { * * @param[in] value The new ochp_command value. */ -void state::ochp_command(std::string const& value) { +void state::ochp_command(const std::string& value) { _ochp_command = value; } @@ -2828,7 +2835,7 @@ void state::ochp_timeout(unsigned int value) { * * @return The ocsp_command value. */ -std::string const& state::ocsp_command() const noexcept { +const std::string& state::ocsp_command() const noexcept { return _ocsp_command; } @@ -2837,7 +2844,7 @@ std::string const& state::ocsp_command() const noexcept { * * @param[in] value The new ocsp_command value. */ -void state::ocsp_command(std::string const& value) { +void state::ocsp_command(const std::string& value) { _ocsp_command = value; } @@ -2884,7 +2891,7 @@ void state::perfdata_timeout(int value) { * * @return The poller_name value. */ -std::string const& state::poller_name() const noexcept { +const std::string& state::poller_name() const noexcept { return _poller_name; } @@ -2893,7 +2900,7 @@ std::string const& state::poller_name() const noexcept { * * @param[in] value The new poller_name value. */ -void state::poller_name(std::string const& value) { +void state::poller_name(const std::string& value) { _poller_name = value; } @@ -3329,8 +3336,8 @@ set_service::iterator state::services_find(service::key_type const& k) { } set_service::const_iterator state::services_find( - std::string const& host_name, - std::string const& service_desc) const { + const std::string& host_name, + const std::string& service_desc) const { for (auto it = _services.begin(), end = _services.end(); it != end; ++it) { if (it->service_description() == service_desc && *it->hosts().begin() == host_name) @@ -3422,7 +3429,7 @@ void state::service_interleave_factor_method(interleave_factor value) { * * @return The service_perfdata_command value. */ -std::string const& state::service_perfdata_command() const noexcept { +const std::string& state::service_perfdata_command() const noexcept { return _service_perfdata_command; } @@ -3431,7 +3438,7 @@ std::string const& state::service_perfdata_command() const noexcept { * * @param[in] value The new service_perfdata_command value. */ -void state::service_perfdata_command(std::string const& value) { +void state::service_perfdata_command(const std::string& value) { _service_perfdata_command = value; } @@ -3440,7 +3447,7 @@ void state::service_perfdata_command(std::string const& value) { * * @return The service_perfdata_file value. */ -std::string const& state::service_perfdata_file() const noexcept { +const std::string& state::service_perfdata_file() const noexcept { return _service_perfdata_file; } @@ -3449,7 +3456,7 @@ std::string const& state::service_perfdata_file() const noexcept { * * @param[in] value The new service_perfdata_file value. */ -void state::service_perfdata_file(std::string const& value) { +void state::service_perfdata_file(const std::string& value) { _service_perfdata_file = value; } @@ -3476,7 +3483,7 @@ void state::service_perfdata_file_mode(perfdata_file_mode value) { * * @return The service_perfdata_file_processing_command value. */ -std::string const& state::service_perfdata_file_processing_command() +const std::string& state::service_perfdata_file_processing_command() const noexcept { return _service_perfdata_file_processing_command; } @@ -3486,7 +3493,7 @@ std::string const& state::service_perfdata_file_processing_command() * * @param[in] value The new service_perfdata_file_processing_command value. */ -void state::service_perfdata_file_processing_command(std::string const& value) { +void state::service_perfdata_file_processing_command(const std::string& value) { _service_perfdata_file_processing_command = value; } @@ -3513,7 +3520,7 @@ void state::service_perfdata_file_processing_interval(unsigned int value) { * * @return The service_perfdata_file_template value. */ -std::string const& state::service_perfdata_file_template() const noexcept { +const std::string& state::service_perfdata_file_template() const noexcept { return _service_perfdata_file_template; } @@ -3522,7 +3529,7 @@ std::string const& state::service_perfdata_file_template() const noexcept { * * @param[in] value The new service_perfdata_file_template value. */ -void state::service_perfdata_file_template(std::string const& value) { +void state::service_perfdata_file_template(const std::string& value) { _service_perfdata_file_template = value; } @@ -3570,7 +3577,7 @@ void state::soft_state_dependencies(bool value) { * * @return The state_retention_file value. */ -std::string const& state::state_retention_file() const noexcept { +const std::string& state::state_retention_file() const noexcept { return _state_retention_file; } @@ -3579,7 +3586,7 @@ std::string const& state::state_retention_file() const noexcept { * * @param[in] value The new state_retention_file value. */ -void state::state_retention_file(std::string const& value) { +void state::state_retention_file(const std::string& value) { if (value.empty() || value[0] == '/') _state_retention_file = value; else { @@ -3594,7 +3601,7 @@ void state::state_retention_file(std::string const& value) { * * @return The status_file value. */ -std::string const& state::status_file() const noexcept { +const std::string& state::status_file() const noexcept { return _status_file; } @@ -3603,7 +3610,7 @@ std::string const& state::status_file() const noexcept { * * @param[in] value The new status_file value. */ -void state::status_file(std::string const& value) { +void state::status_file(const std::string& value) { _status_file = value; } @@ -3642,8 +3649,7 @@ bool state::set(char const* key, char const* value) { if (it != _setters.end()) return (it->second)->apply_from_cfg(*this, value); } catch (std::exception const& e) { - engine_logger(log_config_error, basic) << e.what(); - config_logger->error(e.what()); + _logger->error(e.what()); return false; } return true; @@ -3751,7 +3757,7 @@ void state::user(std::unordered_map const& value) { * @param[in] key The user key. * @param[in] value The user value. */ -void state::user(std::string const& key, std::string const& value) { +void state::user(const std::string& key, std::string const& value) { if (key.size() < 3 || key[0] != '$' || key[key.size() - 1] != '$') throw engine_error() << "Invalid user key '" << key << "'"; std::string new_key = key; @@ -3766,7 +3772,7 @@ void state::user(std::string const& key, std::string const& value) { * @param[in] key The user key. * @param[in] value The user value. */ -void state::user(unsigned int key, std::string const& value) { +void state::user(unsigned int key, const std::string& value) { _users[fmt::format("{}", key)] = value; } @@ -3777,10 +3783,7 @@ void state::user(unsigned int key, std::string const& value) { * @param[in] value The new use_aggressive_host_checking value. */ void state::use_aggressive_host_checking(bool value __attribute__((unused))) { - engine_logger(log_verification_error, basic) - << "Warning: use_aggressive_host_checking is deprecated." - " This option is no more supported since version 21.04."; - config_logger->warn( + _logger->warn( "Warning: use_aggressive_host_checking is deprecated. This option is " "no " "more supported since version 21.04."); @@ -3955,7 +3958,7 @@ void state::log_legacy_enabled(bool value) { * * @return The log_v2_logger value. */ -std::string const& state::log_v2_logger() const noexcept { +const std::string& state::log_v2_logger() const noexcept { return _log_v2_logger; } @@ -3964,7 +3967,7 @@ std::string const& state::log_v2_logger() const noexcept { * * @param[in] value The new log_v2_logger value. */ -void state::log_v2_logger(std::string const& value) { +void state::log_v2_logger(const std::string& value) { if (value.empty()) throw engine_error() << "log_v2_logger cannot be empty"; _log_v2_logger = value; @@ -3975,7 +3978,7 @@ void state::log_v2_logger(std::string const& value) { * * @return The log_level_functions value. */ -std::string const& state::log_level_functions() const noexcept { +const std::string& state::log_level_functions() const noexcept { return _log_level_functions; } @@ -3984,7 +3987,7 @@ std::string const& state::log_level_functions() const noexcept { * * @param[in] value The new log_level_functions value. */ -void state::log_level_functions(std::string const& value) { +void state::log_level_functions(const std::string& value) { if (log_v2::instance().contains_level(value)) _log_level_functions = value; else @@ -3996,7 +3999,7 @@ void state::log_level_functions(std::string const& value) { * * @return The log_level_config value. */ -std::string const& state::log_level_config() const noexcept { +const std::string& state::log_level_config() const noexcept { return _log_level_config; } @@ -4005,7 +4008,7 @@ std::string const& state::log_level_config() const noexcept { * * @param[in] value The new log_level_config value. */ -void state::log_level_config(std::string const& value) { +void state::log_level_config(const std::string& value) { if (log_v2::instance().contains_level(value)) _log_level_config = value; else @@ -4017,7 +4020,7 @@ void state::log_level_config(std::string const& value) { * * @return The log_level_events value. */ -std::string const& state::log_level_events() const noexcept { +const std::string& state::log_level_events() const noexcept { return _log_level_events; } @@ -4026,7 +4029,7 @@ std::string const& state::log_level_events() const noexcept { * * @param[in] value The new log_level_events value. */ -void state::log_level_events(std::string const& value) { +void state::log_level_events(const std::string& value) { if (log_v2::instance().contains_level(value)) _log_level_events = value; else @@ -4038,7 +4041,7 @@ void state::log_level_events(std::string const& value) { * * @return The log_level_checks value. */ -std::string const& state::log_level_checks() const noexcept { +const std::string& state::log_level_checks() const noexcept { return _log_level_checks; } @@ -4047,7 +4050,7 @@ std::string const& state::log_level_checks() const noexcept { * * @param[in] value The new log_level_checks value. */ -void state::log_level_checks(std::string const& value) { +void state::log_level_checks(const std::string& value) { if (log_v2::instance().contains_level(value)) _log_level_checks = value; else @@ -4059,7 +4062,7 @@ void state::log_level_checks(std::string const& value) { * * @return The log_level_notifications value. */ -std::string const& state::log_level_notifications() const noexcept { +const std::string& state::log_level_notifications() const noexcept { return _log_level_notifications; } @@ -4068,7 +4071,7 @@ std::string const& state::log_level_notifications() const noexcept { * * @param[in] value The new log_level_notifications value. */ -void state::log_level_notifications(std::string const& value) { +void state::log_level_notifications(const std::string& value) { if (log_v2::instance().contains_level(value)) _log_level_notifications = value; else @@ -4081,7 +4084,7 @@ void state::log_level_notifications(std::string const& value) { * * @return The log_level_eventbroker value. */ -std::string const& state::log_level_eventbroker() const noexcept { +const std::string& state::log_level_eventbroker() const noexcept { return _log_level_eventbroker; } @@ -4090,7 +4093,7 @@ std::string const& state::log_level_eventbroker() const noexcept { * * @param[in] value The new log_level_eventbroker value. */ -void state::log_level_eventbroker(std::string const& value) { +void state::log_level_eventbroker(const std::string& value) { if (log_v2::instance().contains_level(value)) _log_level_eventbroker = value; else @@ -4103,7 +4106,7 @@ void state::log_level_eventbroker(std::string const& value) { * * @return The log_level_external_command value. */ -std::string const& state::log_level_external_command() const noexcept { +const std::string& state::log_level_external_command() const noexcept { return _log_level_external_command; } @@ -4112,7 +4115,7 @@ std::string const& state::log_level_external_command() const noexcept { * * @param[in] value The new log_level_external_command value. */ -void state::log_level_external_command(std::string const& value) { +void state::log_level_external_command(const std::string& value) { if (log_v2::instance().contains_level(value)) _log_level_external_command = value; else @@ -4125,7 +4128,7 @@ void state::log_level_external_command(std::string const& value) { * * @return The log_level_commands value. */ -std::string const& state::log_level_commands() const noexcept { +const std::string& state::log_level_commands() const noexcept { return _log_level_commands; } @@ -4134,7 +4137,7 @@ std::string const& state::log_level_commands() const noexcept { * * @param[in] value The new log_level_commands value. */ -void state::log_level_commands(std::string const& value) { +void state::log_level_commands(const std::string& value) { if (log_v2::instance().contains_level(value)) _log_level_commands = value; else @@ -4146,7 +4149,7 @@ void state::log_level_commands(std::string const& value) { * * @return The log_level_downtimes value. */ -std::string const& state::log_level_downtimes() const noexcept { +const std::string& state::log_level_downtimes() const noexcept { return _log_level_downtimes; } @@ -4155,7 +4158,7 @@ std::string const& state::log_level_downtimes() const noexcept { * * @param[in] value The new log_level_downtimes value. */ -void state::log_level_downtimes(std::string const& value) { +void state::log_level_downtimes(const std::string& value) { if (log_v2::instance().contains_level(value)) _log_level_downtimes = value; else @@ -4167,7 +4170,7 @@ void state::log_level_downtimes(std::string const& value) { * * @return The log_level_comments value. */ -std::string const& state::log_level_comments() const noexcept { +const std::string& state::log_level_comments() const noexcept { return _log_level_comments; } @@ -4176,7 +4179,7 @@ std::string const& state::log_level_comments() const noexcept { * * @param[in] value The new log_level_comments value. */ -void state::log_level_comments(std::string const& value) { +void state::log_level_comments(const std::string& value) { if (log_v2::instance().contains_level(value)) _log_level_comments = value; else @@ -4188,7 +4191,7 @@ void state::log_level_comments(std::string const& value) { * * @return The log_level_macros value. */ -std::string const& state::log_level_macros() const noexcept { +const std::string& state::log_level_macros() const noexcept { return _log_level_macros; } @@ -4197,7 +4200,7 @@ std::string const& state::log_level_macros() const noexcept { * * @param[in] value The new log_level_macros value. */ -void state::log_level_macros(std::string const& value) { +void state::log_level_macros(const std::string& value) { if (log_v2::instance().contains_level(value)) _log_level_macros = value; else @@ -4209,7 +4212,7 @@ void state::log_level_macros(std::string const& value) { * * @return The log_level_process value. */ -std::string const& state::log_level_process() const noexcept { +const std::string& state::log_level_process() const noexcept { return _log_level_process; } @@ -4218,7 +4221,7 @@ std::string const& state::log_level_process() const noexcept { * * @param[in] value The new log_level_process value. */ -void state::log_level_process(std::string const& value) { +void state::log_level_process(const std::string& value) { if (log_v2::instance().contains_level(value)) _log_level_process = value; else @@ -4230,7 +4233,7 @@ void state::log_level_process(std::string const& value) { * * @return The log_level_runtime value. */ -std::string const& state::log_level_runtime() const noexcept { +const std::string& state::log_level_runtime() const noexcept { return _log_level_runtime; } @@ -4239,7 +4242,7 @@ std::string const& state::log_level_runtime() const noexcept { * * @param[in] value The new log_level_runtime value. */ -void state::log_level_runtime(std::string const& value) { +void state::log_level_runtime(const std::string& value) { if (log_v2::instance().contains_level(value)) _log_level_runtime = value; else @@ -4251,7 +4254,7 @@ void state::log_level_runtime(std::string const& value) { * * @return The log_level_otl value. */ -std::string const& state::log_level_otl() const noexcept { +const std::string& state::log_level_otl() const noexcept { return _log_level_otl; } @@ -4260,7 +4263,7 @@ std::string const& state::log_level_otl() const noexcept { * * @param[in] value The new log_level_otl value. */ -void state::log_level_otl(std::string const& value) { +void state::log_level_otl(const std::string& value) { if (log_v2::instance().contains_level(value)) _log_level_otl = value; else @@ -4272,7 +4275,7 @@ void state::log_level_otl(std::string const& value) { * * @return The use_timezone value. */ -std::string const& state::use_timezone() const noexcept { +const std::string& state::use_timezone() const noexcept { return _use_timezone; } @@ -4281,7 +4284,7 @@ std::string const& state::use_timezone() const noexcept { * * @param[in] value The new use_timezone value. */ -void state::use_timezone(std::string const& value) { +void state::use_timezone(const std::string& value) { _use_timezone = value; } @@ -4308,11 +4311,9 @@ void state::use_true_regexp_matching(bool value) { * * @param[in] value Unused. */ -void state::_set_aggregate_status_updates(std::string const& value) { - (void)value; - engine_logger(log_config_warning, basic) - << "Warning: aggregate_status_updates variable ignored"; - config_logger->warn("Warning: aggregate_status_updates variable ignored"); +void state::_set_aggregate_status_updates(const std::string& value + [[maybe_unused]]) { + _logger->warn("Warning: aggregate_status_updates variable ignored"); ++config_warnings; } @@ -4321,11 +4322,8 @@ void state::_set_aggregate_status_updates(std::string const& value) { * * @param[in] value Unused. */ -void state::_set_auth_file(std::string const& value) { - (void)value; - engine_logger(log_config_warning, basic) - << "Warning: auth_file variable ignored"; - config_logger->warn("Warning: auth_file variable ignored"); +void state::_set_auth_file(const std::string& value [[maybe_unused]]) { + _logger->warn("Warning: auth_file variable ignored"); ++config_warnings; } @@ -4334,11 +4332,8 @@ void state::_set_auth_file(std::string const& value) { * * @param[in] value Unused. */ -void state::_set_bare_update_check(std::string const& value) { - (void)value; - engine_logger(log_config_warning, basic) - << "Warning: bare_update_check variable ignored"; - config_logger->warn("Warning: bare_update_check variable ignored"); +void state::_set_bare_update_check(const std::string& value [[maybe_unused]]) { + _logger->warn("Warning: bare_update_check variable ignored"); ++config_warnings; } @@ -4347,7 +4342,7 @@ void state::_set_bare_update_check(std::string const& value) { * * @param[in] value The new broker module. */ -void state::_set_broker_module(std::string const& value) { +void state::_set_broker_module(const std::string& value) { _broker_module.push_back(value); } @@ -4356,7 +4351,7 @@ void state::_set_broker_module(std::string const& value) { * * @param[in] value The new configuration directory. */ -void state::_set_cfg_dir(std::string const& value) { +void state::_set_cfg_dir(const std::string& value) { if (value.empty() || value[0] == '/') _cfg_dir.push_back(value); else { @@ -4371,7 +4366,7 @@ void state::_set_cfg_dir(std::string const& value) { * * @param[in] value The new configuration file. */ -void state::_set_cfg_file(std::string const& value) { +void state::_set_cfg_file(const std::string& value) { if (value.empty() || value[0] == '/') _cfg_file.push_back(value); else { @@ -4386,11 +4381,8 @@ void state::_set_cfg_file(std::string const& value) { * * @param[in] value Unused. */ -void state::_set_check_for_updates(std::string const& value) { - (void)value; - engine_logger(log_config_warning, basic) - << "Warning: check_for_updates variable ignored"; - config_logger->warn("Warning: check_for_updates variable ignored"); +void state::_set_check_for_updates(const std::string& value [[maybe_unused]]) { + _logger->warn("Warning: check_for_updates variable ignored"); ++config_warnings; } @@ -4399,11 +4391,9 @@ void state::_set_check_for_updates(std::string const& value) { * * @param[in] value Unused. */ -void state::_set_child_processes_fork_twice(std::string const& value) { - (void)value; - engine_logger(log_config_warning, basic) - << "Warning: child_processes_fork_twice variable ignored"; - config_logger->warn("Warning: child_processes_fork_twice variable ignored"); +void state::_set_child_processes_fork_twice(const std::string& value + [[maybe_unused]]) { + _logger->warn("Warning: child_processes_fork_twice variable ignored"); ++config_warnings; } @@ -4412,7 +4402,7 @@ void state::_set_child_processes_fork_twice(std::string const& value) { * * @param[in] value The new command check interval. */ -void state::_set_command_check_interval(std::string const& value) { +void state::_set_command_check_interval(const std::string& value) { std::string val(value); size_t pos(val.find('s')); if (pos == std::string::npos) @@ -4430,11 +4420,8 @@ void state::_set_command_check_interval(std::string const& value) { * * @param[in] value Unused. */ -void state::_set_comment_file(std::string const& value) { - (void)value; - engine_logger(log_config_warning, basic) - << "Warning: comment_file variable ignored"; - config_logger->warn("Warning: comment_file variable ignored"); +void state::_set_comment_file(const std::string& value [[maybe_unused]]) { + _logger->warn("Warning: comment_file variable ignored"); ++config_warnings; } @@ -4443,11 +4430,8 @@ void state::_set_comment_file(std::string const& value) { * * @param[in] value Unused. */ -void state::_set_daemon_dumps_core(std::string const& value) { - (void)value; - engine_logger(log_config_warning, basic) - << "Warning: daemon_dumps_core variable ignored"; - config_logger->warn("Warning: daemon_dumps_core variable ignored"); +void state::_set_daemon_dumps_core(const std::string& value [[maybe_unused]]) { + _logger->warn("Warning: daemon_dumps_core variable ignored"); ++config_warnings; } @@ -4456,7 +4440,7 @@ void state::_set_daemon_dumps_core(std::string const& value) { * * @param[in] value The new date format. */ -void state::_set_date_format(std::string const& value) { +void state::_set_date_format(const std::string& value) { if (value == "euro") _date_format = euro; else if (value == "iso8601") @@ -4472,11 +4456,8 @@ void state::_set_date_format(std::string const& value) { * * @param[in] value Unused. */ -void state::_set_downtime_file(std::string const& value) { - (void)value; - engine_logger(log_config_warning, basic) - << "Warning: downtime_file variable ignored"; - config_logger->warn("Warning: downtime_file variable ignored"); +void state::_set_downtime_file(const std::string& value [[maybe_unused]]) { + _logger->warn("Warning: downtime_file variable ignored"); ++config_warnings; } @@ -4485,11 +4466,9 @@ void state::_set_downtime_file(std::string const& value) { * * @param[in] value Unused. */ -void state::_set_enable_embedded_perl(std::string const& value) { - (void)value; - engine_logger(log_config_warning, basic) - << "Warning: enable_embedded_perl variable ignored"; - config_logger->warn("Warning: enable_embedded_perl variable ignored"); +void state::_set_enable_embedded_perl(const std::string& value + [[maybe_unused]]) { + _logger->warn("Warning: enable_embedded_perl variable ignored"); ++config_warnings; } @@ -4498,11 +4477,9 @@ void state::_set_enable_embedded_perl(std::string const& value) { * * @param[in] value Unused. */ -void state::_set_enable_failure_prediction(std::string const& value) { - (void)value; - engine_logger(log_config_warning, basic) - << "Warning: enable_failure_prediction variable ignored"; - config_logger->warn("Warning: enable_failure_prediction variable ignored"); +void state::_set_enable_failure_prediction(const std::string& value + [[maybe_unused]]) { + _logger->warn("Warning: enable_failure_prediction variable ignored"); ++config_warnings; return; } @@ -4512,7 +4489,7 @@ void state::_set_enable_failure_prediction(std::string const& value) { * * @param[in] value The new event_broker_options value. */ -void state::_set_event_broker_options(std::string const& value) { +void state::_set_event_broker_options(const std::string& value) { if (value != "-1") detail::setter("") .apply_from_cfg(*this, value.c_str()); @@ -4526,11 +4503,9 @@ void state::_set_event_broker_options(std::string const& value) { * * @param[in] value Unused. */ -void state::_set_free_child_process_memory(std::string const& value) { - (void)value; - engine_logger(log_config_warning, basic) - << "Warning: free_child_process_memory variable ignored"; - config_logger->warn("Warning: free_child_process_memory variable ignored"); +void state::_set_free_child_process_memory(const std::string& value + [[maybe_unused]]) { + _logger->warn("Warning: free_child_process_memory variable ignored"); ++config_warnings; } @@ -4539,7 +4514,7 @@ void state::_set_free_child_process_memory(std::string const& value) { * * @param[in] value The new host_inter_check_delay_method value. */ -void state::_set_host_inter_check_delay_method(std::string const& value) { +void state::_set_host_inter_check_delay_method(const std::string& value) { if (value == "n") _host_inter_check_delay_method = icd_none; else if (value == "d") @@ -4562,7 +4537,7 @@ void state::_set_host_inter_check_delay_method(std::string const& value) { * * @param[in] value The new host_inter_check_delay_method value. */ -void state::_set_host_perfdata_file_mode(std::string const& value) { +void state::_set_host_perfdata_file_mode(const std::string& value) { if (value == "p") _host_perfdata_file_mode = mode_pipe; else if (value == "w") @@ -4576,11 +4551,8 @@ void state::_set_host_perfdata_file_mode(std::string const& value) { * * @param[in] value Unused. */ -void state::_set_lock_file(std::string const& value) { - (void)value; - engine_logger(log_config_warning, basic) - << "Warning: lock_file variable ignored"; - config_logger->warn("Warning: lock_file variable ignored"); +void state::_set_lock_file(const std::string& value [[maybe_unused]]) { + _logger->warn("Warning: lock_file variable ignored"); ++config_warnings; } @@ -4589,11 +4561,8 @@ void state::_set_lock_file(std::string const& value) { * * @param[in] value Unused. */ -void state::_set_log_archive_path(std::string const& value) { - (void)value; - engine_logger(log_config_warning, basic) - << "Warning: log_archive_path variable ignored"; - config_logger->warn("Warning: log_archive_path variable ignored"); +void state::_set_log_archive_path(const std::string& value [[maybe_unused]]) { + _logger->warn("Warning: log_archive_path variable ignored"); ++config_warnings; } @@ -4602,11 +4571,8 @@ void state::_set_log_archive_path(std::string const& value) { * * @param[in] value Unused. */ -void state::_set_log_initial_states(std::string const& value) { - (void)value; - engine_logger(log_config_warning, basic) - << "Warning: log_initial_states variable ignored"; - config_logger->warn("Warning: log_initial_states variable ignored"); +void state::_set_log_initial_states(const std::string& value [[maybe_unused]]) { + _logger->warn("Warning: log_initial_states variable ignored"); ++config_warnings; return; } @@ -4616,11 +4582,9 @@ void state::_set_log_initial_states(std::string const& value) { * * @param[in] value Unused. */ -void state::_set_log_rotation_method(std::string const& value) { - (void)value; - engine_logger(log_config_warning, basic) - << "Warning: log_rotation_method variable ignored"; - config_logger->warn("Warning: log_rotation_method variable ignored"); +void state::_set_log_rotation_method(const std::string& value + [[maybe_unused]]) { + _logger->warn("Warning: log_rotation_method variable ignored"); ++config_warnings; } @@ -4629,11 +4593,8 @@ void state::_set_log_rotation_method(std::string const& value) { * * @param[in] value Unused. */ -void state::_set_nagios_group(std::string const& value) { - (void)value; - engine_logger(log_config_warning, basic) - << "Warning: nagios_group variable ignored"; - config_logger->warn("Warning: nagios_group variable ignored"); +void state::_set_nagios_group(const std::string& value [[maybe_unused]]) { + _logger->warn("Warning: nagios_group variable ignored"); ++config_warnings; } @@ -4642,11 +4603,8 @@ void state::_set_nagios_group(std::string const& value) { * * @param[in] value Unused. */ -void state::_set_nagios_user(std::string const& value) { - (void)value; - engine_logger(log_config_warning, basic) - << "Warning: nagios_user variable ignored"; - config_logger->warn("Warning: nagios_user variable ignored"); +void state::_set_nagios_user(const std::string& value [[maybe_unused]]) { + _logger->warn("Warning: nagios_user variable ignored"); ++config_warnings; } @@ -4655,11 +4613,8 @@ void state::_set_nagios_user(std::string const& value) { * * @param[in] value Unused. */ -void state::_set_object_cache_file(std::string const& value) { - (void)value; - engine_logger(log_config_warning, basic) - << "Warning: object_cache_file variable ignored"; - config_logger->warn("Warning: object_cache_file variable ignored"); +void state::_set_object_cache_file(const std::string& value [[maybe_unused]]) { + _logger->warn("Warning: object_cache_file variable ignored"); ++config_warnings; } @@ -4668,11 +4623,8 @@ void state::_set_object_cache_file(std::string const& value) { * * @param[in] value Unused. */ -void state::_set_p1_file(std::string const& value) { - (void)value; - engine_logger(log_config_warning, basic) - << "Warning: p1_file variable ignored"; - config_logger->warn("Warning: p1_file variable ignored"); +void state::_set_p1_file(const std::string& value [[maybe_unused]]) { + _logger->warn("Warning: p1_file variable ignored"); ++config_warnings; } @@ -4682,11 +4634,9 @@ void state::_set_p1_file(std::string const& value) { * * @param[in] value Unused. */ -void state::_set_precached_object_file(std::string const& value) { - (void)value; - engine_logger(log_config_warning, basic) - << "Warning: precached_object_file variable ignored"; - config_logger->warn("Warning: precached_object_file variable ignored"); +void state::_set_precached_object_file(const std::string& value + [[maybe_unused]]) { + _logger->warn("Warning: precached_object_file variable ignored"); ++config_warnings; } @@ -4695,7 +4645,7 @@ void state::_set_precached_object_file(std::string const& value) { * * @param[in] value The new resource_file. */ -void state::_set_resource_file(std::string const& value) { +void state::_set_resource_file(const std::string& value) { if (value.empty() || value[0] == '/') _resource_file.push_back(value); else { @@ -4711,11 +4661,8 @@ void state::_set_resource_file(std::string const& value) { * @param[in] value Unused. */ void state::_set_retained_process_service_attribute_mask( - std::string const& value) { - (void)value; - engine_logger(log_config_warning, basic) - << "Warning: retained_process_service_attribute_mask variable ignored"; - config_logger->warn( + const std::string& value [[maybe_unused]]) { + _logger->warn( "Warning: retained_process_service_attribute_mask variable ignored"); ++config_warnings; } @@ -4725,12 +4672,9 @@ void state::_set_retained_process_service_attribute_mask( * * @param[in] value Unused. */ -void state::_set_retained_service_attribute_mask(std::string const& value) { - (void)value; - engine_logger(log_config_warning, basic) - << "Warning: retained_service_attribute_mask variable ignored"; - config_logger->warn( - "Warning: retained_service_attribute_mask variable ignored"); +void state::_set_retained_service_attribute_mask(const std::string& value + [[maybe_unused]]) { + _logger->warn("Warning: retained_service_attribute_mask variable ignored"); ++config_warnings; } @@ -4739,7 +4683,7 @@ void state::_set_retained_service_attribute_mask(std::string const& value) { * * @param[in] value The new service_inter_check_delay_method. */ -void state::_set_service_inter_check_delay_method(std::string const& value) { +void state::_set_service_inter_check_delay_method(const std::string& value) { if (value == "n") _service_inter_check_delay_method = icd_none; else if (value == "d") @@ -4762,7 +4706,7 @@ void state::_set_service_inter_check_delay_method(std::string const& value) { * * @param[in] value The new service_interleave_factor_method. */ -void state::_set_service_interleave_factor_method(std::string const& value) { +void state::_set_service_interleave_factor_method(const std::string& value) { if (value == "s") _service_interleave_factor_method = ilf_smart; else { @@ -4778,7 +4722,7 @@ void state::_set_service_interleave_factor_method(std::string const& value) { * * @param[in] value The new service_inter_check_delay_method value. */ -void state::_set_service_perfdata_file_mode(std::string const& value) { +void state::_set_service_perfdata_file_mode(const std::string& value) { if (value == "p") _service_perfdata_file_mode = mode_pipe; else if (value == "w") @@ -4792,11 +4736,8 @@ void state::_set_service_perfdata_file_mode(std::string const& value) { * * @param[in] value Unused. */ -void state::_set_temp_file(std::string const& value) { - (void)value; - engine_logger(log_config_warning, basic) - << "Warning: temp_file variable ignored"; - config_logger->warn("Warning: temp_file variable ignored"); +void state::_set_temp_file(const std::string& value [[maybe_unused]]) { + _logger->warn("Warning: temp_file variable ignored"); ++config_warnings; } @@ -4805,11 +4746,8 @@ void state::_set_temp_file(std::string const& value) { * * @param[in] value Unused. */ -void state::_set_temp_path(std::string const& value) { - (void)value; - engine_logger(log_config_warning, basic) - << "Warning: temp_path variable ignored"; - config_logger->warn("Warning: temp_path variable ignored"); +void state::_set_temp_path(const std::string& value [[maybe_unused]]) { + _logger->warn("Warning: temp_path variable ignored"); ++config_warnings; } @@ -4818,15 +4756,13 @@ void state::_set_temp_path(std::string const& value) { * * @param[in] value Unused. */ -void state::_set_use_embedded_perl_implicitly(std::string const& value) { - (void)value; - engine_logger(log_config_warning, basic) - << "Warning: use_embedded_perl_implicitly variable ignored"; - config_logger->warn("Warning: use_embedded_perl_implicitly variable ignored"); +void state::_set_use_embedded_perl_implicitly(const std::string& value + [[maybe_unused]]) { + _logger->warn("Warning: use_embedded_perl_implicitly variable ignored"); ++config_warnings; } -void state::macros_filter(std::string const& value) { +void state::macros_filter(const std::string& value) { size_t previous(0), first, last; size_t current(value.find(',')); while (current != std::string::npos) { @@ -4904,19 +4840,18 @@ void state::use_send_recovery_notifications_anyways(bool value) { */ void state::apply_extended_conf(const std::string& file_path, const rapidjson::Document& json_doc) { - SPDLOG_LOGGER_INFO(config_logger, "apply conf from file {}", file_path); + SPDLOG_LOGGER_INFO(_logger, "apply conf from file {}", file_path); for (rapidjson::Value::ConstMemberIterator member_iter = json_doc.MemberBegin(); member_iter != json_doc.MemberEnd(); ++member_iter) { const std::string_view field_name = member_iter->name.GetString(); auto setter = _setters.find(field_name); if (setter == _setters.end()) { - SPDLOG_LOGGER_ERROR(config_logger, "unknown field: {} in file {}", - field_name, file_path); - } else if (!setter->second->apply_from_json(*this, json_doc)) { - SPDLOG_LOGGER_ERROR(config_logger, - "fail to update field: {} from file {}", field_name, + SPDLOG_LOGGER_ERROR(_logger, "unknown field: {} in file {}", field_name, file_path); + } else if (!setter->second->apply_from_json(*this, json_doc)) { + SPDLOG_LOGGER_ERROR(_logger, "fail to update field: {} from file {}", + field_name, file_path); } } } diff --git a/engine/src/configuration/whitelist.cc b/engine/src/configuration/whitelist.cc index 40e617dd0a7..f9849a0bbe8 100644 --- a/engine/src/configuration/whitelist.cc +++ b/engine/src/configuration/whitelist.cc @@ -17,6 +17,7 @@ * */ +#include "common/log_v2/log_v2.hh" #define C4_NO_DEBUG_BREAK 1 #include "com/centreon/engine/configuration/whitelist.hh" @@ -32,11 +33,13 @@ #include "absl/base/call_once.h" #include "com/centreon/engine/globals.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/log_v2/log_v2.hh" using namespace com::centreon; using namespace com::centreon::exceptions; using namespace com::centreon::engine; using namespace com::centreon::engine::configuration; +using com::centreon::common::log_v2::log_v2; namespace com::centreon::engine::configuration { @@ -84,7 +87,8 @@ static std::atomic_uint _instance_gen(1); * @param file_path */ whitelist::whitelist(const std::string_view& file_path) - : _instance_id(_instance_gen.fetch_add(1)) { + : _logger{log_v2::instance().get(log_v2::CONFIG)}, + _instance_id(_instance_gen.fetch_add(1)) { init_ryml_error_handler(); _parse_file(file_path); } @@ -98,15 +102,15 @@ bool whitelist::_parse_file(const std::string_view& file_path) { // check file struct stat infos; if (::stat(file_path.data(), &infos)) { - SPDLOG_LOGGER_ERROR(config_logger, "{} doesn't exist", file_path); + SPDLOG_LOGGER_ERROR(_logger, "{} doesn't exist", file_path); return false; } if ((infos.st_mode & S_IFMT) != S_IFREG) { - SPDLOG_LOGGER_ERROR(config_logger, "{} is not a regular file", file_path); + SPDLOG_LOGGER_ERROR(_logger, "{} is not a regular file", file_path); return false; } if (!infos.st_size) { - SPDLOG_LOGGER_ERROR(config_logger, "{} is an empty file", file_path); + SPDLOG_LOGGER_ERROR(_logger, "{} is an empty file", file_path); return false; } @@ -114,13 +118,12 @@ bool whitelist::_parse_file(const std::string_view& file_path) { if (centengine_group) { if (infos.st_uid || infos.st_gid != centengine_group->gr_gid) { - SPDLOG_LOGGER_ERROR(config_logger, - "file {} must be owned by root@centreon-engine", - file_path); + SPDLOG_LOGGER_ERROR( + _logger, "file {} must be owned by root@centreon-engine", file_path); } } if (infos.st_mode & S_IRWXO || (infos.st_mode & S_IRWXG) != S_IRGRP) { - SPDLOG_LOGGER_ERROR(config_logger, "file {} must have x40 right access", + SPDLOG_LOGGER_ERROR(_logger, "file {} must have x40 right access", file_path); } @@ -134,14 +137,13 @@ bool whitelist::_parse_file(const std::string_view& file_path) { std::streamsize some_read = f.readsome(buff.get() + read, file_size - read); if (some_read < 0) { - SPDLOG_LOGGER_ERROR(config_logger, "fail to read {}: {}"); + SPDLOG_LOGGER_ERROR(_logger, "fail to read {}: {}"); return false; } read += some_read; } } catch (const std::exception& e) { - SPDLOG_LOGGER_ERROR(config_logger, "fail to read {}: {}", file_path, - e.what()); + SPDLOG_LOGGER_ERROR(_logger, "fail to read {}: {}", file_path, e.what()); return false; } // parse file content @@ -150,8 +152,7 @@ bool whitelist::_parse_file(const std::string_view& file_path) { ryml::Tree tree = ryml::parse_in_place(ryml::substr(buff.get(), file_size)); return _read_file_content(tree); } catch (const std::exception& e) { - SPDLOG_LOGGER_ERROR(config_logger, "fail to parse {}: {}", file_path, - e.what()); + SPDLOG_LOGGER_ERROR(_logger, "fail to parse {}: {}", file_path, e.what()); return false; } } @@ -170,12 +171,12 @@ bool whitelist::_read_file_content(const ryml_tree& file_content) { bool ret = false; if (wildcards.valid() && !wildcards.empty()) { if (!wildcards.is_seq()) { // not an array => error - SPDLOG_LOGGER_ERROR(config_logger, "{}: wildcard is not a sequence"); + SPDLOG_LOGGER_ERROR(_logger, "{}: wildcard is not a sequence"); } else { for (auto wildcard : wildcards) { auto value = wildcard.val(); std::string_view str_value(value.data(), value.size()); - SPDLOG_LOGGER_INFO(config_logger, "wildcard '{}' added to whitelist", + SPDLOG_LOGGER_INFO(_logger, "wildcard '{}' added to whitelist", str_value); _wildcards.emplace_back(str_value); ret = true; @@ -184,7 +185,7 @@ bool whitelist::_read_file_content(const ryml_tree& file_content) { } if (regexps.valid() && !regexps.empty()) { if (!regexps.is_seq()) { // not an array => error - SPDLOG_LOGGER_ERROR(config_logger, "{}: regex is not a sequence"); + SPDLOG_LOGGER_ERROR(_logger, "{}: regex is not a sequence"); } else { for (auto re : regexps) { auto value = re.val(); @@ -193,14 +194,14 @@ bool whitelist::_read_file_content(const ryml_tree& file_content) { std::make_unique(str_value); if (to_push_back->error_code() == re2::RE2::ErrorCode::NoError) { // success compile regex - SPDLOG_LOGGER_INFO(config_logger, "regexp '{}' added to whitelist", + SPDLOG_LOGGER_INFO(_logger, "regexp '{}' added to whitelist", str_value); _regex.push_back(std::move(to_push_back)); ret = true; } else { // bad regex SPDLOG_LOGGER_ERROR( - config_logger, "fail to parse regex {}: error: {} at {} ", - str_value, to_push_back->error(), to_push_back->error_arg()); + _logger, "fail to parse regex {}: error: {} at {} ", str_value, + to_push_back->error(), to_push_back->error_arg()); } } } @@ -258,7 +259,7 @@ whitelist::e_refresh_result whitelist::parse_dir( return e_refresh_result::no_directory; } if ((dir_infos.st_mode & S_IFMT) != S_IFDIR) { - SPDLOG_LOGGER_ERROR(config_logger, "{} is not a directory: {}", directory, + SPDLOG_LOGGER_ERROR(_logger, "{} is not a directory: {}", directory, dir_infos.st_mode); return e_refresh_result::no_directory; } @@ -267,7 +268,7 @@ whitelist::e_refresh_result whitelist::parse_dir( if (centengine_group) { if (dir_infos.st_uid || dir_infos.st_gid != centengine_group->gr_gid) { - SPDLOG_LOGGER_ERROR(config_logger, + SPDLOG_LOGGER_ERROR(_logger, "directory {} must be owned by root@centreon-engine", directory); } @@ -275,8 +276,8 @@ whitelist::e_refresh_result whitelist::parse_dir( if (dir_infos.st_mode & S_IRWXO || (dir_infos.st_mode & S_IRWXG) != S_IRGRP + S_IXGRP) { - SPDLOG_LOGGER_ERROR(config_logger, - "directory {} must have 750 right access", directory); + SPDLOG_LOGGER_ERROR(_logger, "directory {} must have 750 right access", + directory); } e_refresh_result res = e_refresh_result::empty_directory; diff --git a/engine/src/main.cc b/engine/src/main.cc index cb7da20c670..100e0245507 100644 --- a/engine/src/main.cc +++ b/engine/src/main.cc @@ -116,12 +116,12 @@ int main(int argc, char* argv[]) { #endif // HAVE_GETOPT_H // Load singletons and global variable. + log_v2::load("centengine"); + + /* It's time to set the logger. Later, we will have acceses from multiple + * threads and we'll only be able to change atomic values. */ config = new configuration::state; - // Hack to instanciate the logger. - log_v2::load("centengine"); - auto config_logger = log_v2::instance().get(log_v2::CONFIG); - auto process_logger = log_v2::instance().get(log_v2::PROCESS); init_loggers(); configuration::applier::logging::instance(); com::centreon::common::pool::load(g_io_context, runtime_logger); diff --git a/tests/broker-engine/start-stop.robot b/tests/broker-engine/start-stop.robot index a52a5497882..6fa1ff5875b 100644 --- a/tests/broker-engine/start-stop.robot +++ b/tests/broker-engine/start-stop.robot @@ -27,6 +27,7 @@ BESS1 BESS2 [Documentation] Start-Stop Broker/Engine - Broker started first - Engine stopped first [Tags] broker engine start-stop + Ctn Clear Retention Ctn Config Engine ${1} Ctn Config Broker central Ctn Config Broker module From 063a994a47ff9059ee79dfa87f2d51d04d471b35 Mon Sep 17 00:00:00 2001 From: David Boucher Date: Mon, 10 Jun 2024 11:27:48 +0200 Subject: [PATCH 32/60] enh(engine): Service/Host/Anomalydetection configuration objects simplified REFS: MON-113242 --- .../engine/configuration/anomalydetection.hh | 2 +- .../centreon/engine/configuration/command.hh | 41 ++-- .../engine/configuration/connector.hh | 1 - .../engine/configuration/contactgroup.hh | 47 ++--- .../engine/configuration/file_info.hh | 40 ++-- .../centreon/engine/configuration/group.hh | 70 +++---- .../engine/configuration/hostdependency.hh | 39 ++-- .../engine/configuration/hostescalation.hh | 39 ++-- .../engine/configuration/hostgroup.hh | 39 ++-- .../centreon/engine/configuration/parser.hh | 8 +- .../centreon/engine/configuration/point_2d.hh | 46 ++-- .../centreon/engine/configuration/point_3d.hh | 40 ++-- .../centreon/engine/configuration/service.hh | 13 +- .../engine/configuration/servicedependency.hh | 39 ++-- .../engine/configuration/serviceescalation.hh | 113 +++++----- .../engine/configuration/servicegroup.hh | 61 +++--- .../centreon/engine/configuration/severity.hh | 41 ++-- .../com/centreon/engine/configuration/tag.hh | 36 ++-- .../engine/configuration/timeperiod.hh | 37 ++-- engine/src/configuration/anomalydetection.cc | 1 - engine/src/configuration/applier/scheduler.cc | 2 +- engine/src/configuration/applier/service.cc | 112 +++------- engine/src/configuration/service.cc | 198 ++---------------- engine/src/configuration/serviceescalation.cc | 5 - engine/src/configuration/state.cc | 2 +- engine/src/main.cc | 2 +- engine/src/xpddefault.cc | 4 +- .../configuration/applier/applier-command.cc | 2 + .../applier/applier-connector.cc | 1 + .../configuration/applier/applier-contact.cc | 1 + .../configuration/applier/applier-service.cc | 3 +- .../applier/applier-servicegroup.cc | 1 + .../configuration/applier/applier-state.cc | 8 +- engine/tests/custom_vars/extcmd.cc | 3 +- .../host_flapping_notification.cc | 1 + .../host_recovery_notification.cc | 1 + 36 files changed, 426 insertions(+), 673 deletions(-) diff --git a/engine/inc/com/centreon/engine/configuration/anomalydetection.hh b/engine/inc/com/centreon/engine/configuration/anomalydetection.hh index 68fb0d74495..71f6c10af98 100644 --- a/engine/inc/com/centreon/engine/configuration/anomalydetection.hh +++ b/engine/inc/com/centreon/engine/configuration/anomalydetection.hh @@ -230,7 +230,7 @@ class anomalydetection : public object { opt _severity_id; opt _icon_id; std::set> _tags; - opt _sensitivity; + double _sensitivity; }; typedef std::shared_ptr anomalydetection_ptr; diff --git a/engine/inc/com/centreon/engine/configuration/command.hh b/engine/inc/com/centreon/engine/configuration/command.hh index 9702d7db9fe..ebca31ad7f3 100644 --- a/engine/inc/com/centreon/engine/configuration/command.hh +++ b/engine/inc/com/centreon/engine/configuration/command.hh @@ -1,22 +1,21 @@ -/* -** Copyright 2011-2013,2017 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2013,2017-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCE_CONFIGURATION_COMMAND_HH #define CCE_CONFIGURATION_COMMAND_HH @@ -58,8 +57,8 @@ class command : public object { static std::unordered_map const _setters; }; -typedef std::shared_ptr command_ptr; -typedef std::set set_command; +using command_ptr = std::shared_ptr; +using set_command = std::set; } // namespace configuration } // namespace com::centreon::engine diff --git a/engine/inc/com/centreon/engine/configuration/connector.hh b/engine/inc/com/centreon/engine/configuration/connector.hh index f94ff488609..b9c784465e5 100644 --- a/engine/inc/com/centreon/engine/configuration/connector.hh +++ b/engine/inc/com/centreon/engine/configuration/connector.hh @@ -19,7 +19,6 @@ #ifndef CCE_CONFIGURATION_CONNECTOR_HH #define CCE_CONFIGURATION_CONNECTOR_HH -#include "com/centreon/engine/commands/connector.hh" #include "com/centreon/engine/configuration/object.hh" namespace com::centreon::engine { diff --git a/engine/inc/com/centreon/engine/configuration/contactgroup.hh b/engine/inc/com/centreon/engine/configuration/contactgroup.hh index 2fb472697c8..ea3fdfd1f10 100644 --- a/engine/inc/com/centreon/engine/configuration/contactgroup.hh +++ b/engine/inc/com/centreon/engine/configuration/contactgroup.hh @@ -1,22 +1,21 @@ /** - * Copyright 2011-2013,2017 Centreon + * Copyright 2011-2013,2017-2024 Centreon * - * This file is part of Centreon Engine. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Centreon Engine is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License version 2 - * as published by the Free Software Foundation. + * http://www.apache.org/licenses/LICENSE-2.0 * - * Centreon Engine is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com * - * You should have received a copy of the GNU General Public License - * along with Centreon Engine. If not, see - * . */ - #ifndef CCE_CONFIGURATION_CONTACTGROUP_HH #define CCE_CONFIGURATION_CONTACTGROUP_HH @@ -32,22 +31,22 @@ class contactgroup : public object { contactgroup(key_type const& key = ""); contactgroup(contactgroup const& right); - ~contactgroup() throw() override; + ~contactgroup() noexcept override; contactgroup& operator=(contactgroup const& right); - bool operator==(contactgroup const& right) const throw(); - bool operator!=(contactgroup const& right) const throw(); - bool operator<(contactgroup const& right) const throw(); + bool operator==(contactgroup const& right) const noexcept; + bool operator!=(contactgroup const& right) const noexcept; + bool operator<(contactgroup const& right) const noexcept; void check_validity() const override; - key_type const& key() const throw(); + key_type const& key() const noexcept; void merge(object const& obj) override; bool parse(char const* key, char const* value) override; - std::string const& alias() const throw(); - set_string& contactgroup_members() throw(); - set_string const& contactgroup_members() const throw(); - std::string const& contactgroup_name() const throw(); - set_string& members() throw(); - set_string const& members() const throw(); + std::string const& alias() const noexcept; + set_string& contactgroup_members() noexcept; + set_string const& contactgroup_members() const noexcept; + std::string const& contactgroup_name() const noexcept; + set_string& members() noexcept; + set_string const& members() const noexcept; private: typedef bool (*setter_func)(contactgroup&, char const*); diff --git a/engine/inc/com/centreon/engine/configuration/file_info.hh b/engine/inc/com/centreon/engine/configuration/file_info.hh index a01262ead8b..6ec9e4e8626 100644 --- a/engine/inc/com/centreon/engine/configuration/file_info.hh +++ b/engine/inc/com/centreon/engine/configuration/file_info.hh @@ -1,22 +1,22 @@ -/* -** Copyright 2011-2013 Merethis -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2013 Merethis + * Copyright 2014-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCE_CONFIGURATION_FILE_INFO_HH #define CCE_CONFIGURATION_FILE_INFO_HH @@ -59,6 +59,6 @@ class file_info { }; } // namespace configuration -} +} // namespace com::centreon::engine #endif // !CCE_CONFIGURATION_FILE_INFO_HH diff --git a/engine/inc/com/centreon/engine/configuration/group.hh b/engine/inc/com/centreon/engine/configuration/group.hh index 45281375df3..4fbe0050cb9 100644 --- a/engine/inc/com/centreon/engine/configuration/group.hh +++ b/engine/inc/com/centreon/engine/configuration/group.hh @@ -1,22 +1,21 @@ -/* -** Copyright 2011-2013,2017 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2013,2017-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCE_CONFIGURATION_GROUP_HH #define CCE_CONFIGURATION_GROUP_HH @@ -29,30 +28,29 @@ typedef std::list list_string; typedef std::set set_string; typedef std::set > set_pair_string; -namespace com::centreon::engine { +namespace com::centreon::engine::configuration { -namespace configuration { template class group { public: group(bool inherit = false); group(group const& other); - ~group() throw(); + ~group() noexcept; group& operator=(group const& other); group& operator=(std::string const& other); group& operator+=(group const& other); - bool operator==(group const& other) const throw(); - bool operator!=(group const& other) const throw(); - bool operator<(group const& other) const throw(); - T& operator*() throw() { return (_data); } - T const& operator*() const throw() { return (_data); } - T* operator->() throw() { return (&_data); } - T const* operator->() const throw() { return (&_data); } - T& get() throw() { return (_data); } - T const& get() const throw() { return (_data); } - bool is_inherit() const throw() { return (_is_inherit); } - void is_inherit(bool enable) throw() { _is_inherit = enable; } - bool is_set() const throw() { return (_is_set); } + bool operator==(group const& other) const noexcept; + bool operator!=(group const& other) const noexcept; + bool operator<(group const& other) const noexcept; + T& operator*() noexcept { return (_data); } + T const& operator*() const noexcept { return (_data); } + T* operator->() noexcept { return (&_data); } + T const* operator->() const noexcept { return (&_data); } + T& get() noexcept { return (_data); } + T const& get() const noexcept { return (_data); } + bool is_inherit() const noexcept { return (_is_inherit); } + void is_inherit(bool enable) noexcept { _is_inherit = enable; } + bool is_set() const noexcept { return (_is_set); } void reset(); private: @@ -61,8 +59,6 @@ class group { bool _is_null; bool _is_set; }; -} // namespace configuration - -} +} // namespace com::centreon::engine::configuration #endif // !CCE_CONFIGURATION_GROUP_HH diff --git a/engine/inc/com/centreon/engine/configuration/hostdependency.hh b/engine/inc/com/centreon/engine/configuration/hostdependency.hh index 4e5bf5317fe..3755f385724 100644 --- a/engine/inc/com/centreon/engine/configuration/hostdependency.hh +++ b/engine/inc/com/centreon/engine/configuration/hostdependency.hh @@ -1,22 +1,21 @@ -/* -** Copyright 2011-2019 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCE_CONFIGURATION_HOSTDEPENDENCY_HH #define CCE_CONFIGURATION_HOSTDEPENDENCY_HH @@ -102,6 +101,6 @@ typedef std::shared_ptr hostdependency_ptr; typedef std::set set_hostdependency; } // namespace configuration -} +} // namespace com::centreon::engine #endif // !CCE_CONFIGURATION_HOSTDEPENDENCY_HH diff --git a/engine/inc/com/centreon/engine/configuration/hostescalation.hh b/engine/inc/com/centreon/engine/configuration/hostescalation.hh index b82af6d9df3..5c5a286a492 100644 --- a/engine/inc/com/centreon/engine/configuration/hostescalation.hh +++ b/engine/inc/com/centreon/engine/configuration/hostescalation.hh @@ -1,22 +1,21 @@ -/* -** Copyright 2011-2013,2017 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2013,2017-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCE_CONFIGURATION_HOSTESCALATION_HH #define CCE_CONFIGURATION_HOSTESCALATION_HH @@ -99,6 +98,6 @@ typedef std::shared_ptr hostescalation_ptr; typedef std::set set_hostescalation; } // namespace configuration -} +} // namespace com::centreon::engine #endif // !CCE_CONFIGURATION_HOSTESCALATION_HH diff --git a/engine/inc/com/centreon/engine/configuration/hostgroup.hh b/engine/inc/com/centreon/engine/configuration/hostgroup.hh index 2ffd52cea3c..4fa758f48d2 100644 --- a/engine/inc/com/centreon/engine/configuration/hostgroup.hh +++ b/engine/inc/com/centreon/engine/configuration/hostgroup.hh @@ -1,22 +1,21 @@ -/* -** Copyright 2011-2013,2017 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2013,2017-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCE_CONFIGURATION_HOSTGROUP_HH #define CCE_CONFIGURATION_HOSTGROUP_HH @@ -77,6 +76,6 @@ typedef std::shared_ptr hostgroup_ptr; typedef std::set set_hostgroup; } // namespace configuration -} +} // namespace com::centreon::engine #endif // !CCE_CONFIGURATION_HOSTGROUP_HH diff --git a/engine/inc/com/centreon/engine/configuration/parser.hh b/engine/inc/com/centreon/engine/configuration/parser.hh index 6b2924259dc..ee6b3e41048 100644 --- a/engine/inc/com/centreon/engine/configuration/parser.hh +++ b/engine/inc/com/centreon/engine/configuration/parser.hh @@ -49,13 +49,11 @@ class parser { read_host = (1 << 4), read_hostdependency = (1 << 5), read_hostescalation = (1 << 6), - read_hostextinfo = (1 << 7), read_hostgroup = (1 << 8), read_hostgroupescalation = (1 << 9), read_service = (1 << 10), read_servicedependency = (1 << 11), read_serviceescalation = (1 << 12), - read_serviceextinfo = (1 << 13), read_servicegroup = (1 << 14), read_timeperiod = (1 << 15), read_all = (~0) @@ -63,7 +61,7 @@ class parser { parser(unsigned int read_options = read_all); ~parser() noexcept = default; - void parse(std::string const& path, state& config); + void parse(const std::string& path, state& config); private: typedef void (parser::*store)(object_ptr obj); @@ -89,8 +87,8 @@ class parser { static void _insert(map_object const& from, std::set& to); std::string const& _map_object_type(map_object const& objects) const throw(); void _parse_directory_configuration(std::string const& path); - void _parse_global_configuration(std::string const& path); - void _parse_object_definitions(std::string const& path); + void _parse_global_configuration(const std::string& path); + void _parse_object_definitions(const std::string& path); void _parse_resource_file(std::string const& path); void _resolve_template(); void _store_into_list(object_ptr obj); diff --git a/engine/inc/com/centreon/engine/configuration/point_2d.hh b/engine/inc/com/centreon/engine/configuration/point_2d.hh index 15e16155b27..1ca19e3f5b9 100644 --- a/engine/inc/com/centreon/engine/configuration/point_2d.hh +++ b/engine/inc/com/centreon/engine/configuration/point_2d.hh @@ -1,28 +1,26 @@ -/* -** Copyright 2011-2013 Merethis -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2013 Merethis + * Copyright 2014-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCE_CONFIGURATION_POINT_2D_HH #define CCE_CONFIGURATION_POINT_2D_HH -namespace com::centreon::engine { - -namespace configuration { +namespace com::centreon::engine::configuration { class point_2d { public: point_2d(int x = -1, int y = -1); @@ -39,8 +37,6 @@ class point_2d { int _x; int _y; }; -} // namespace configuration - -} +} // namespace com::centreon::engine::configuration #endif // !CCE_CONFIGURATION_POINT_2D_HH diff --git a/engine/inc/com/centreon/engine/configuration/point_3d.hh b/engine/inc/com/centreon/engine/configuration/point_3d.hh index 0f50c01d3e4..382711145ce 100644 --- a/engine/inc/com/centreon/engine/configuration/point_3d.hh +++ b/engine/inc/com/centreon/engine/configuration/point_3d.hh @@ -1,22 +1,22 @@ -/* -** Copyright 2011-2013 Merethis -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2013 Merethis + * Copyright 2014-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCE_CONFIGURATION_POINT_3D_HH #define CCE_CONFIGURATION_POINT_3D_HH @@ -43,6 +43,6 @@ class point_3d { }; } // namespace configuration -} +} // namespace com::centreon::engine #endif // !CCE_CONFIGURATION_POINT_3D_HH diff --git a/engine/inc/com/centreon/engine/configuration/service.hh b/engine/inc/com/centreon/engine/configuration/service.hh index 9cacb129f4a..55c15e5d555 100644 --- a/engine/inc/com/centreon/engine/configuration/service.hh +++ b/engine/inc/com/centreon/engine/configuration/service.hh @@ -77,10 +77,7 @@ class service : public object { unsigned short flap_detection_options() const noexcept; unsigned int freshness_threshold() const noexcept; unsigned int high_flap_threshold() const noexcept; - set_string& hostgroups() noexcept; - set_string const& hostgroups() const noexcept; - set_string& hosts() noexcept; - set_string const& hosts() const noexcept; + const std::string& host_name() const; uint64_t host_id() const noexcept; void set_host_id(uint64_t id); std::string const& icon_image() const noexcept; @@ -143,8 +140,7 @@ class service : public object { bool _set_flap_detection_options(std::string const& value); bool _set_freshness_threshold(unsigned int value); bool _set_high_flap_threshold(unsigned int value); - bool _set_hostgroups(std::string const& value); - bool _set_hosts(std::string const& value); + bool _set_host_name(const std::string& value); bool _set_icon_image(std::string const& value); bool _set_icon_image_alt(std::string const& value); bool _set_initial_state(std::string const& value); @@ -193,11 +189,10 @@ class service : public object { opt _flap_detection_options; opt _freshness_threshold; opt _high_flap_threshold; - group _hostgroups; - group _hosts; + std::string _host_name; std::string _icon_image; std::string _icon_image_alt; - opt _initial_state; + uint32_t _initial_state; opt _is_volatile; opt _low_flap_threshold; opt _max_check_attempts; diff --git a/engine/inc/com/centreon/engine/configuration/servicedependency.hh b/engine/inc/com/centreon/engine/configuration/servicedependency.hh index 85b91134e2b..abac725b73e 100644 --- a/engine/inc/com/centreon/engine/configuration/servicedependency.hh +++ b/engine/inc/com/centreon/engine/configuration/servicedependency.hh @@ -1,22 +1,21 @@ -/* -** Copyright 2011-2013,2017 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2013,2017-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCE_CONFIGURATION_SERVICEDEPENDENCY_HH #define CCE_CONFIGURATION_SERVICEDEPENDENCY_HH @@ -119,6 +118,6 @@ typedef std::shared_ptr servicedependency_ptr; typedef std::set set_servicedependency; } // namespace configuration -} +} // namespace com::centreon::engine #endif // !CCE_CONFIGURATION_SERVICEDEPENDENCY_HH diff --git a/engine/inc/com/centreon/engine/configuration/serviceescalation.hh b/engine/inc/com/centreon/engine/configuration/serviceescalation.hh index 71502eeaf0c..a24daa83226 100644 --- a/engine/inc/com/centreon/engine/configuration/serviceescalation.hh +++ b/engine/inc/com/centreon/engine/configuration/serviceescalation.hh @@ -1,22 +1,21 @@ -/* -** Copyright 2011-2013,2017 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2013,2017-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCE_CONFIGURATION_SERVICEESCALATION_HH #define CCE_CONFIGURATION_SERVICEESCALATION_HH @@ -25,10 +24,35 @@ #include "com/centreon/engine/opt.hh" #include "com/centreon/engine/shared.hh" -namespace com::centreon::engine { +namespace com::centreon::engine::configuration { -namespace configuration { class serviceescalation : public object { + typedef bool (*setter_func)(serviceescalation&, char const*); + + group _contactgroups; + opt _escalation_options; + opt _escalation_period; + opt _first_notification; + group _hostgroups; + group _hosts; + opt _last_notification; + opt _notification_interval; + group _servicegroups; + group _service_description; + static std::unordered_map const _setters; + Uuid _uuid; + + bool _set_contactgroups(std::string const& value); + bool _set_escalation_options(std::string const& value); + bool _set_escalation_period(std::string const& value); + bool _set_first_notification(unsigned int value); + bool _set_hostgroups(std::string const& value); + bool _set_hosts(std::string const& value); + bool _set_last_notification(unsigned int value); + bool _set_notification_interval(unsigned int value); + bool _set_servicegroups(std::string const& value); + bool _set_service_description(std::string const& value); + public: enum action_on { none = 0, @@ -42,21 +66,21 @@ class serviceescalation : public object { serviceescalation(); serviceescalation(serviceescalation const& right); - ~serviceescalation() throw() override; + ~serviceescalation() noexcept override = default; serviceescalation& operator=(serviceescalation const& right); - bool operator==(serviceescalation const& right) const throw(); - bool operator!=(serviceescalation const& right) const throw(); + bool operator==(serviceescalation const& right) const noexcept; + bool operator!=(serviceescalation const& right) const noexcept; bool operator<(serviceescalation const& right) const; void check_validity() const override; key_type const& key() const throw(); void merge(object const& obj) override; bool parse(char const* key, char const* value) override; - set_string& contactgroups() throw(); - set_string const& contactgroups() const throw(); - bool contactgroups_defined() const throw(); - void escalation_options(unsigned int options) throw(); - unsigned short escalation_options() const throw(); + set_string& contactgroups() noexcept; + set_string const& contactgroups() const noexcept; + bool contactgroups_defined() const noexcept; + void escalation_options(unsigned int options) noexcept; + unsigned short escalation_options() const noexcept; void escalation_period(std::string const& period); std::string const& escalation_period() const throw(); bool escalation_period_defined() const throw(); @@ -76,39 +100,10 @@ class serviceescalation : public object { list_string& service_description() throw(); list_string const& service_description() const throw(); Uuid const& uuid() const; - - private: - typedef bool (*setter_func)(serviceescalation&, char const*); - - bool _set_contactgroups(std::string const& value); - bool _set_escalation_options(std::string const& value); - bool _set_escalation_period(std::string const& value); - bool _set_first_notification(unsigned int value); - bool _set_hostgroups(std::string const& value); - bool _set_hosts(std::string const& value); - bool _set_last_notification(unsigned int value); - bool _set_notification_interval(unsigned int value); - bool _set_servicegroups(std::string const& value); - bool _set_service_description(std::string const& value); - - group _contactgroups; - opt _escalation_options; - opt _escalation_period; - opt _first_notification; - group _hostgroups; - group _hosts; - opt _last_notification; - opt _notification_interval; - group _servicegroups; - group _service_description; - static std::unordered_map const _setters; - Uuid _uuid; }; typedef std::shared_ptr serviceescalation_ptr; typedef std::set set_serviceescalation; -} // namespace configuration - -} +} // namespace com::centreon::engine::configuration #endif // !CCE_CONFIGURATION_SERVICEESCALATION_HH diff --git a/engine/inc/com/centreon/engine/configuration/servicegroup.hh b/engine/inc/com/centreon/engine/configuration/servicegroup.hh index 59ff29a0cf4..db4c410aa61 100644 --- a/engine/inc/com/centreon/engine/configuration/servicegroup.hh +++ b/engine/inc/com/centreon/engine/configuration/servicegroup.hh @@ -1,22 +1,21 @@ -/* -** Copyright 2011-2013,2017 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2013,2017-2025 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCE_CONFIGURATION_SERVICEGROUP_HH #define CCE_CONFIGURATION_SERVICEGROUP_HH @@ -35,7 +34,7 @@ class servicegroup : public object { servicegroup(key_type const& key = ""); servicegroup(servicegroup const& right); - ~servicegroup() throw() override; + ~servicegroup() noexcept override; servicegroup& operator=(servicegroup const& right); bool operator==(servicegroup const& right) const throw(); bool operator!=(servicegroup const& right) const throw(); @@ -45,16 +44,16 @@ class servicegroup : public object { void merge(object const& obj) override; bool parse(char const* key, char const* value) override; - std::string const& action_url() const throw(); - std::string const& alias() const throw(); - set_pair_string& members() throw(); - set_pair_string const& members() const throw(); - std::string const& notes() const throw(); - std::string const& notes_url() const throw(); - unsigned int servicegroup_id() const throw(); - set_string& servicegroup_members() throw(); - set_string const& servicegroup_members() const throw(); - std::string const& servicegroup_name() const throw(); + std::string const& action_url() const noexcept; + std::string const& alias() const noexcept; + set_pair_string& members() noexcept; + set_pair_string const& members() const noexcept; + std::string const& notes() const noexcept; + std::string const& notes_url() const noexcept; + unsigned int servicegroup_id() const noexcept; + set_string& servicegroup_members() noexcept; + set_string const& servicegroup_members() const noexcept; + std::string const& servicegroup_name() const noexcept; private: typedef bool (*setter_func)(servicegroup&, char const*); @@ -83,6 +82,6 @@ typedef std::shared_ptr servicegroup_ptr; typedef std::set set_servicegroup; } // namespace configuration -} +} // namespace com::centreon::engine #endif // !CCE_CONFIGURATION_SERVICEGROUP_HH diff --git a/engine/inc/com/centreon/engine/configuration/severity.hh b/engine/inc/com/centreon/engine/configuration/severity.hh index 4908bd7ae39..5cd3e04e7e7 100644 --- a/engine/inc/com/centreon/engine/configuration/severity.hh +++ b/engine/inc/com/centreon/engine/configuration/severity.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2022 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCE_CONFIGURATION_SEVERITY_HH #define CCE_CONFIGURATION_SEVERITY_HH @@ -23,9 +23,8 @@ #include "com/centreon/engine/configuration/object.hh" -namespace com::centreon::engine { +namespace com::centreon::engine::configuration { -namespace configuration { class severity : public object { public: using key_type = std::pair; @@ -70,8 +69,6 @@ class severity : public object { }; typedef std::set set_severity; -} // namespace configuration - -} +} // namespace com::centreon::engine::configuration #endif // !CCE_CONFIGURATION_SEVERITY_HH diff --git a/engine/inc/com/centreon/engine/configuration/tag.hh b/engine/inc/com/centreon/engine/configuration/tag.hh index b1819fa12ee..c1697c2b3df 100644 --- a/engine/inc/com/centreon/engine/configuration/tag.hh +++ b/engine/inc/com/centreon/engine/configuration/tag.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ +/** + * Copyright 2022 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCE_CONFIGURATION_TAG_HH #define CCE_CONFIGURATION_TAG_HH @@ -68,6 +68,6 @@ class tag : public object { typedef std::set set_tag; } // namespace configuration -} +} // namespace com::centreon::engine #endif // !CCE_CONFIGURATION_TAG_HH diff --git a/engine/inc/com/centreon/engine/configuration/timeperiod.hh b/engine/inc/com/centreon/engine/configuration/timeperiod.hh index 01a73e42bad..8b05a1e2535 100644 --- a/engine/inc/com/centreon/engine/configuration/timeperiod.hh +++ b/engine/inc/com/centreon/engine/configuration/timeperiod.hh @@ -1,22 +1,21 @@ -/* -** Copyright 2011-2013,2017 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2013,2017-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCE_CONFIGURATION_TIMEPERIOD_HH #define CCE_CONFIGURATION_TIMEPERIOD_HH diff --git a/engine/src/configuration/anomalydetection.cc b/engine/src/configuration/anomalydetection.cc index 9b672055549..c56b45553ec 100644 --- a/engine/src/configuration/anomalydetection.cc +++ b/engine/src/configuration/anomalydetection.cc @@ -841,7 +841,6 @@ void anomalydetection::merge(object const& obj) { MRG_OPTION(_timezone); MRG_OPTION(_severity_id); MRG_OPTION(_icon_id); - MRG_OPTION(_sensitivity); MRG_MAP(_tags); } diff --git a/engine/src/configuration/applier/scheduler.cc b/engine/src/configuration/applier/scheduler.cc index 7db63225c18..c28f7812ce4 100644 --- a/engine/src/configuration/applier/scheduler.cc +++ b/engine/src/configuration/applier/scheduler.cc @@ -836,7 +836,7 @@ std::vector applier::scheduler::_get_services( for (auto it = svc_cfg.rbegin(), end = svc_cfg.rend(); it != end; ++it) { uint64_t host_id(it->host_id()); uint64_t service_id(it->service_id()); - std::string const& host_name(*it->hosts().begin()); + const std::string& host_name = it->host_name(); std::string const& service_description(it->service_description()); service_id_map::const_iterator svc(services.find({host_id, service_id})); if (svc == services.end()) { diff --git a/engine/src/configuration/applier/service.cc b/engine/src/configuration/applier/service.cc index 3d83fb17eb5..fe0259e38fc 100644 --- a/engine/src/configuration/applier/service.cc +++ b/engine/src/configuration/applier/service.cc @@ -87,37 +87,25 @@ applier::service& applier::service::operator=(applier::service const& right) { */ void applier::service::add_object(configuration::service const& obj) { // Check service. - if (obj.hosts().size() < 1) + if (obj.host_name().empty()) throw engine_error() << "Could not create service '" << obj.service_description() << "' with no host defined"; - else if (obj.hosts().size() > 1) - throw engine_error() << "Could not create service '" - << obj.service_description() - << "' with multiple hosts defined"; - else if (!obj.hostgroups().empty()) - throw engine_error() << "Could not create service '" - << obj.service_description() - << "' with multiple host groups defined"; else if (!obj.host_id()) throw engine_error() << "No host_id available for the host '" - << *obj.hosts().begin() - << "' - unable to create service '" + << obj.host_name() << "' - unable to create service '" << obj.service_description() << "'"; // Logging. - engine_logger(logging::dbg_config, logging::more) - << "Creating new service '" << obj.service_description() << "' of host '" - << *obj.hosts().begin() << "'."; config_logger->debug("Creating new service '{}' of host '{}'.", - obj.service_description(), *obj.hosts().begin()); + obj.service_description(), obj.host_name()); // Add service to the global configuration set. config->mut_services().insert(obj); // Create service. engine::service* svc{add_service( - obj.host_id(), obj.service_id(), *obj.hosts().begin(), + obj.host_id(), obj.service_id(), obj.host_name(), obj.service_description(), obj.display_name(), obj.check_period(), static_cast(obj.initial_state()), obj.max_check_attempts(), obj.check_interval(), obj.retry_interval(), @@ -162,11 +150,11 @@ void applier::service::add_object(configuration::service const& obj) { if (!svc) throw engine_error() << "Could not register service '" << obj.service_description() << "' of host '" - << *obj.hosts().begin() << "'"; + << obj.host_name() << "'"; svc->set_initial_notif_time(0); - engine::service::services[{*obj.hosts().begin(), obj.service_description()}] + engine::service::services[{obj.host_name(), obj.service_description()}] ->set_host_id(obj.host_id()); - engine::service::services[{*obj.hosts().begin(), obj.service_description()}] + engine::service::services[{obj.host_name(), obj.service_description()}] ->set_service_id(obj.service_id()); svc->set_acknowledgement_timeout(obj.acknowledgement_timeout() * config->interval_length()); @@ -208,7 +196,7 @@ void applier::service::add_object(configuration::service const& obj) { throw engine_error() << "Could not add the severity (" << k.first << ", " << k.second << ") to the service '" << obj.service_description() << "' of host '" - << *obj.hosts().begin() << "'"; + << obj.host_name() << "'"; svc->set_severity(sv->second); } @@ -239,10 +227,10 @@ void applier::service::add_object(configuration::service const& obj) { void applier::service::expand_objects(configuration::state& s) { // Browse all services. configuration::set_service expanded; - for (auto svc_cfg : s.services()) { + for (auto svc : s.services()) { // Should custom variables be sent to broker ? - for (auto it = svc_cfg.mut_customvariables().begin(), - end = svc_cfg.mut_customvariables().end(); + for (auto it = svc.mut_customvariables().begin(), + end = svc.mut_customvariables().end(); it != end; ++it) { if (!s.enable_macros_filter() || s.macros_filter().find(it->first) != s.macros_filter().end()) { @@ -250,56 +238,18 @@ void applier::service::expand_objects(configuration::state& s) { } } - // Expand service to instances. - std::set target_hosts; + // Expand memberships. + _expand_service_memberships(svc, s); - // Hosts members. - target_hosts = svc_cfg.hosts(); + // Inherits special vars. + _inherits_special_vars(svc, s); - // Host group members. - for (set_string::const_iterator it(svc_cfg.hostgroups().begin()), - end(svc_cfg.hostgroups().end()); - it != end; ++it) { - // Find host group. - set_hostgroup::iterator it2(s.hostgroups_find(*it)); - if (it2 == s.hostgroups().end()) - throw(engine_error() << "Could not find host group '" << *it - << "' on which to apply service '" - << svc_cfg.service_description() << "'"); - - // Check host group and user configuration. - if (it2->members().empty() && !s.allow_empty_hostgroup_assignment()) - throw(engine_error() << "Could not expand host group '" << *it - << "' specified in service '" - << svc_cfg.service_description() << "'"); - - // Add host group members. - target_hosts.insert(it2->members().begin(), it2->members().end()); - } - - // Browse all target hosts. - for (std::set::const_iterator it(target_hosts.begin()), - end(target_hosts.end()); - it != end; ++it) { - // Create service instance. - configuration::service svc(svc_cfg); - svc.hostgroups().clear(); - svc.hosts().clear(); - svc.hosts().insert(*it); - - // Expand memberships. - _expand_service_memberships(svc, s); - - // Inherits special vars. - _inherits_special_vars(svc, s); - - // Insert object. - expanded.insert(svc); - } + // Insert object. + expanded.insert(std::move(svc)); } // Set expanded services in configuration state. - s.mut_services().swap(expanded); + s.mut_services() = std::move(expanded); } /** @@ -309,7 +259,7 @@ void applier::service::expand_objects(configuration::state& s) { * engine. */ void applier::service::modify_object(configuration::service const& obj) { - std::string const& host_name(*obj.hosts().begin()); + const std::string& host_name = obj.host_name(); std::string const& service_description(obj.service_description()); // Logging. @@ -342,15 +292,15 @@ void applier::service::modify_object(configuration::service const& obj) { config->mut_services().insert(obj); // Modify properties. - if (it_obj->second->get_hostname() != *obj.hosts().begin() || + if (it_obj->second->get_hostname() != obj.host_name() || it_obj->second->description() != obj.service_description()) { engine::service::services.erase( {it_obj->second->get_hostname(), it_obj->second->description()}); engine::service::services.insert( - {{*obj.hosts().begin(), obj.service_description()}, it_obj->second}); + {{obj.host_name(), obj.service_description()}, it_obj->second}); } - s->set_hostname(*obj.hosts().begin()); + s->set_hostname(obj.host_name()); s->set_description(obj.service_description()); s->set_display_name(obj.display_name()), s->set_check_command(obj.check_command()); @@ -506,7 +456,7 @@ void applier::service::modify_object(configuration::service const& obj) { throw engine_error() << "Could not update the severity (" << k.first << ", " << k.second << ") to the service '" << obj.service_description() << "' of host '" - << *obj.hosts().begin() << "'"; + << obj.host_name() << "'"; s->set_severity(sv->second); } else s->set_severity(nullptr); @@ -536,7 +486,7 @@ void applier::service::modify_object(configuration::service const& obj) { * engine. */ void applier::service::remove_object(configuration::service const& obj) { - std::string const& host_name(*obj.hosts().begin()); + std::string const& host_name(obj.host_name()); std::string const& service_description(obj.service_description()); assert(obj.key().first); @@ -600,16 +550,16 @@ void applier::service::resolve_object(configuration::service const& obj) { // Logging. engine_logger(logging::dbg_config, logging::more) << "Resolving service '" << obj.service_description() << "' of host '" - << *obj.hosts().begin() << "'."; + << obj.host_name() << "'."; config_logger->debug("Resolving service '{}' of host '{}'.", - obj.service_description(), *obj.hosts().begin()); + obj.service_description(), obj.host_name()); // Find service. service_id_map::iterator it(engine::service::services_by_id.find(obj.key())); if (engine::service::services_by_id.end() == it) throw engine_error() << "Cannot resolve non-existing service '" << obj.service_description() << "' of host '" - << *obj.hosts().begin() << "'"; + << obj.host_name() << "'"; // Remove service group links. it->second->get_parent_groups().clear(); @@ -645,7 +595,7 @@ void applier::service::_expand_service_memberships(configuration::service& obj, if (it_group == s.servicegroups().end()) throw(engine_error() << "Could not add service '" << obj.service_description() << "' of host '" - << *obj.hosts().begin() + << obj.host_name() << "' to non-existing service group '" << *it << "'"); @@ -655,7 +605,7 @@ void applier::service::_expand_service_memberships(configuration::service& obj, // Add service to service members. backup.members().insert( - std::make_pair(*obj.hosts().begin(), obj.service_description())); + std::make_pair(obj.host_name(), obj.service_description())); // Reinsert service group. s.servicegroups().insert(backup); @@ -680,11 +630,11 @@ void applier::service::_inherits_special_vars(configuration::service& obj, !obj.notification_period_defined() || !obj.timezone_defined()) { // Find host. configuration::set_host::const_iterator it( - s.hosts_find(obj.hosts().begin()->c_str())); + s.hosts_find(obj.host_name().c_str())); if (it == s.hosts().end()) throw engine_error() << "Could not inherit special variables for service '" - << obj.service_description() << "': host '" << *obj.hosts().begin() + << obj.service_description() << "': host '" << obj.host_name() << "' does not exist"; // Inherits variables. diff --git a/engine/src/configuration/service.cc b/engine/src/configuration/service.cc index e47f720ab87..19fbe425fb3 100644 --- a/engine/src/configuration/service.cc +++ b/engine/src/configuration/service.cc @@ -37,9 +37,9 @@ using namespace com::centreon::engine::logging; &object::setter::generic std::unordered_map const service::_setters{ - {"host", SETTER(std::string const&, _set_hosts)}, - {"hosts", SETTER(std::string const&, _set_hosts)}, - {"host_name", SETTER(std::string const&, _set_hosts)}, + {"host", SETTER(std::string const&, _set_host_name)}, + {"hosts", SETTER(std::string const&, _set_host_name)}, + {"host_name", SETTER(std::string const&, _set_host_name)}, {"service_description", SETTER(std::string const&, _set_service_description)}, {"service_id", SETTER(uint64_t, set_service_id)}, @@ -47,9 +47,6 @@ std::unordered_map const service::_setters{ {"acknowledgement_timeout", SETTER(int, set_acknowledgement_timeout)}, {"description", SETTER(std::string const&, _set_service_description)}, {"display_name", SETTER(std::string const&, _set_display_name)}, - {"hostgroup", SETTER(std::string const&, _set_hostgroups)}, - {"hostgroups", SETTER(std::string const&, _set_hostgroups)}, - {"hostgroup_name", SETTER(std::string const&, _set_hostgroups)}, {"service_groups", SETTER(std::string const&, _set_servicegroups)}, {"servicegroups", SETTER(std::string const&, _set_servicegroups)}, {"check_command", SETTER(std::string const&, _set_check_command)}, @@ -203,8 +200,7 @@ service::service(service const& other) _flap_detection_options(other._flap_detection_options), _freshness_threshold(other._freshness_threshold), _high_flap_threshold(other._high_flap_threshold), - _hostgroups(other._hostgroups), - _hosts(other._hosts), + _host_name(other._host_name), _icon_image(other._icon_image), _icon_image_alt(other._icon_image_alt), _initial_state(other._initial_state), @@ -263,8 +259,7 @@ service& service::operator=(service const& other) { _flap_detection_options = other._flap_detection_options; _freshness_threshold = other._freshness_threshold; _high_flap_threshold = other._high_flap_threshold; - _hostgroups = other._hostgroups; - _hosts = other._hosts; + _host_name = other._host_name; _icon_image = other._icon_image; _icon_image_alt = other._icon_image_alt; _initial_state = other._initial_state; @@ -305,364 +300,257 @@ service& service::operator=(service const& other) { */ bool service::operator==(service const& other) const noexcept { if (!object::operator==(other)) { - engine_logger(dbg_config, more) - << "configuration::service::equality => object don't match"; _logger->debug("configuration::service::equality => object don't match"); return false; } if (_acknowledgement_timeout != other._acknowledgement_timeout) { - engine_logger(dbg_config, more) << "configuration::service::equality => " - "acknowledgement_timeout don't match"; _logger->debug( "configuration::service::equality => " "acknowledgement_timeout don't match"); return false; } if (_action_url != other._action_url) { - engine_logger(dbg_config, more) - << "configuration::service::equality => action_url don't match"; _logger->debug( "configuration::service::equality => action_url don't match"); return false; } if (_checks_active != other._checks_active) { - engine_logger(dbg_config, more) - << "configuration::service::equality => checks_active don't match"; _logger->debug( "configuration::service::equality => checks_active don't match"); return false; } if (_checks_passive != other._checks_passive) { - engine_logger(dbg_config, more) - << "configuration::service::equality => checks_passive don't match"; _logger->debug( "configuration::service::equality => checks_passive don't match"); return false; } if (_check_command != other._check_command) { - engine_logger(dbg_config, more) - << "configuration::service::equality => checks_passive don't match"; _logger->debug( "configuration::service::equality => checks_passive don't match"); return false; } if (_check_command_is_important != other._check_command_is_important) { - engine_logger(dbg_config, more) - << "configuration::service::equality => check_command don't match"; _logger->debug( "configuration::service::equality => check_command don't match"); return false; } if (_check_freshness != other._check_freshness) { - engine_logger(dbg_config, more) - << "configuration::service::equality => check_freshness don't match"; _logger->debug( "configuration::service::equality => check_freshness don't match"); return false; } if (_check_interval != other._check_interval) { - engine_logger(dbg_config, more) - << "configuration::service::equality => check_interval don't match"; _logger->debug( "configuration::service::equality => check_interval don't match"); return false; } if (_check_period != other._check_period) { - engine_logger(dbg_config, more) - << "configuration::service::equality => check_period don't match"; _logger->debug( "configuration::service::equality => check_period don't match"); return false; } if (_contactgroups != other._contactgroups) { - engine_logger(dbg_config, more) - << "configuration::service::equality => contactgroups don't match"; _logger->debug( "configuration::service::equality => contactgroups don't match"); return false; } if (_contacts != other._contacts) { - engine_logger(dbg_config, more) - << "configuration::service::equality => contacts don't match"; _logger->debug("configuration::service::equality => contacts don't match"); return false; } if (std::operator!=(_customvariables, other._customvariables)) { - engine_logger(dbg_config, more) - << "configuration::service::equality => customvariables don't match"; _logger->debug( "configuration::service::equality => customvariables don't match"); return false; } if (_display_name != other._display_name) { - engine_logger(dbg_config, more) - << "configuration::service::equality => display_name don't match"; _logger->debug( "configuration::service::equality => display_name don't match"); return false; } if (_event_handler != other._event_handler) { - engine_logger(dbg_config, more) - << "configuration::service::equality => event_handler don't match"; _logger->debug( "configuration::service::equality => event_handler don't match"); return false; } if (_event_handler_enabled != other._event_handler_enabled) { - engine_logger(dbg_config, more) - << "configuration::service::equality => event_handler don't match"; _logger->debug( "configuration::service::equality => event_handler don't match"); return false; } if (_first_notification_delay != other._first_notification_delay) { - engine_logger(dbg_config, more) << "configuration::service::equality => " - "first_notification_delay don't match"; _logger->debug( "configuration::service::equality => " "first_notification_delay don't match"); return false; } if (_flap_detection_enabled != other._flap_detection_enabled) { - engine_logger(dbg_config, more) << "configuration::service::equality => " - "flap_detection_enabled don't match"; _logger->debug( "configuration::service::equality => " "flap_detection_enabled don't match"); return false; } if (_flap_detection_options != other._flap_detection_options) { - engine_logger(dbg_config, more) << "configuration::service::equality => " - "flap_detection_options don't match"; _logger->debug( "configuration::service::equality => " "flap_detection_options don't match"); return false; } if (_freshness_threshold != other._freshness_threshold) { - engine_logger(dbg_config, more) << "configuration::service::equality => " - "freshness_threshold don't match"; _logger->debug( "configuration::service::equality => " "freshness_threshold don't match"); return false; } if (_high_flap_threshold != other._high_flap_threshold) { - engine_logger(dbg_config, more) << "configuration::service::equality => " - "high_flap_threshold don't match"; _logger->debug( "configuration::service::equality => " "high_flap_threshold don't match"); return false; } - if (_hostgroups != other._hostgroups) { - engine_logger(dbg_config, more) - << "configuration::service::equality => hostgroups don't match"; + if (_host_name != other._host_name) { _logger->debug( - "configuration::service::equality => hostgroups don't match"); - return false; - } - if (_hosts != other._hosts) { - engine_logger(dbg_config, more) - << "configuration::service::equality => _hosts don't match"; - _logger->debug("configuration::service::equality => _hosts don't match"); + "configuration::service::equality => _host_name don't match"); return false; } if (_icon_image != other._icon_image) { - engine_logger(dbg_config, more) - << "configuration::service::equality => icon_image don't match"; _logger->debug( "configuration::service::equality => icon_image don't match"); return false; } if (_icon_image_alt != other._icon_image_alt) { - engine_logger(dbg_config, more) - << "configuration::service::equality => icon_image_alt don't match"; _logger->debug( "configuration::service::equality => icon_image_alt don't match"); return false; } if (_initial_state != other._initial_state) { - engine_logger(dbg_config, more) - << "configuration::service::equality => initial_state don't match"; _logger->debug( "configuration::service::equality => initial_state don't match"); return false; } if (_is_volatile != other._is_volatile) { - engine_logger(dbg_config, more) - << "configuration::service::equality => is_volatile don't match"; _logger->debug( "configuration::service::equality => is_volatile don't match"); return false; } if (_low_flap_threshold != other._low_flap_threshold) { - engine_logger(dbg_config, more) - << "configuration::service::equality => low_flap_threshold don't match"; _logger->debug( "configuration::service::equality => low_flap_threshold don't match"); return false; } if (_max_check_attempts != other._max_check_attempts) { - engine_logger(dbg_config, more) - << "configuration::service::equality => max_check_attempts don't match"; _logger->debug( "configuration::service::equality => max_check_attempts don't match"); return false; } if (_notes != other._notes) { - engine_logger(dbg_config, more) - << "configuration::service::equality => notes don't match"; _logger->debug("configuration::service::equality => notes don't match"); return false; } if (_notes_url != other._notes_url) { - engine_logger(dbg_config, more) - << "configuration::service::equality => notes_url don't match"; _logger->debug("configuration::service::equality => notes_url don't match"); return false; } if (_notifications_enabled != other._notifications_enabled) { - engine_logger(dbg_config, more) << "configuration::service::equality => " - "notifications_enabled don't match"; _logger->debug( "configuration::service::equality => " "notifications_enabled don't match"); return false; } if (_notification_interval != other._notification_interval) { - engine_logger(dbg_config, more) << "configuration::service::equality => " - "notification_interval don't match"; _logger->debug( "configuration::service::equality => " "notification_interval don't match"); return false; } if (_notification_options != other._notification_options) { - engine_logger(dbg_config, more) << "configuration::service::equality => " - "notification_options don't match"; _logger->debug( "configuration::service::equality => " "notification_options don't match"); return false; } if (_notification_period != other._notification_period) { - engine_logger(dbg_config, more) << "configuration::service::equality => " - "notification_period don't match"; _logger->debug( "configuration::service::equality => " "notification_period don't match"); return false; } if (_obsess_over_service != other._obsess_over_service) { - engine_logger(dbg_config, more) << "configuration::service::equality => " - "obsess_over_service don't match"; _logger->debug( "configuration::service::equality => " "obsess_over_service don't match"); return false; } if (_process_perf_data != other._process_perf_data) { - engine_logger(dbg_config, more) - << "configuration::service::equality => process_perf_data don't match"; _logger->debug( "configuration::service::equality => process_perf_data don't match"); return false; } if (_retain_nonstatus_information != other._retain_nonstatus_information) { - engine_logger(dbg_config, more) - << "configuration::service::equality => " - "retain_nonstatus_information don't match"; _logger->debug( "configuration::service::equality => " "retain_nonstatus_information don't match"); return false; } if (_retain_status_information != other._retain_status_information) { - engine_logger(dbg_config, more) << "configuration::service::equality => " - "retain_status_information don't match"; _logger->debug( "configuration::service::equality => " "retain_status_information don't match"); return false; } if (_retry_interval != other._retry_interval) { - engine_logger(dbg_config, more) - << "configuration::service::equality => retry_interval don't match"; _logger->debug( "configuration::service::equality => retry_interval don't match"); return false; } if (_recovery_notification_delay != other._recovery_notification_delay) { - engine_logger(dbg_config, more) - << "configuration::service::equality => " - "recovery_notification_delay don't match"; _logger->debug( "configuration::service::equality => " "recovery_notification_delay don't match"); return false; } if (_servicegroups != other._servicegroups) { - engine_logger(dbg_config, more) - << "configuration::service::equality => servicegroups don't match"; _logger->debug( "configuration::service::equality => servicegroups don't match"); return false; } if (_service_description != other._service_description) { - engine_logger(dbg_config, more) << "configuration::service::equality => " - "service_description don't match"; _logger->debug( "configuration::service::equality => " "service_description don't match"); return false; } if (_host_id != other._host_id) { - engine_logger(dbg_config, more) - << "configuration::service::equality => host_id don't match"; _logger->debug("configuration::service::equality => host_id don't match"); return false; } if (_service_id != other._service_id) { - engine_logger(dbg_config, more) - << "configuration::service::equality => service_id don't match"; _logger->debug( "configuration::service::equality => service_id don't match"); return false; } if (_stalking_options != other._stalking_options) { - engine_logger(dbg_config, more) - << "configuration::service::equality => stalking_options don't match"; _logger->debug( "configuration::service::equality => stalking_options don't match"); return false; } if (_timezone != other._timezone) { - engine_logger(dbg_config, more) - << "configuration::service::equality => timezone don't match"; _logger->debug("configuration::service::equality => timezone don't match"); return false; } if (_severity_id != other._severity_id) { - engine_logger(dbg_config, more) - << "configuration::service::equality => severity id don't match"; _logger->debug( "configuration::service::equality => severity id don't match"); return false; } if (_icon_id != other._icon_id) { - engine_logger(dbg_config, more) - << "configuration::service::equality => icon id don't match"; _logger->debug("configuration::service::equality => icon id don't match"); return false; } if (_tags != other._tags) { - engine_logger(dbg_config, more) - << "configuration::service::equality => tags don't match"; _logger->debug("configuration::service::equality => tags don't match"); return false; } - engine_logger(dbg_config, more) << "configuration::service::equality => OK"; _logger->debug("configuration::service::equality => OK"); return true; } @@ -692,8 +580,8 @@ bool service::operator<(service const& other) const noexcept { return _host_id < other._host_id; else if (_service_id != other._service_id) return _service_id < other._service_id; - else if (_hosts != other._hosts) - return _hosts < other._hosts; + else if (_host_name != other._host_name) + return _host_name < other._host_name; else if (_service_description != other._service_description) return _service_description < other._service_description; else if (_acknowledgement_timeout != other._acknowledgement_timeout) @@ -736,8 +624,6 @@ bool service::operator<(service const& other) const noexcept { return _freshness_threshold < other._freshness_threshold; else if (_high_flap_threshold != other._high_flap_threshold) return _high_flap_threshold < other._high_flap_threshold; - else if (_hostgroups != other._hostgroups) - return _hostgroups < other._hostgroups; else if (_icon_image != other._icon_image) return _icon_image < other._icon_image; else if (_icon_image_alt != other._icon_image_alt) @@ -796,7 +682,7 @@ void service::check_validity() const { if (_service_description.empty()) throw engine_error() << "Service has no description (property " << "'service_description')"; - if (_hosts->empty() && _hostgroups->empty()) + if (_host_name.empty()) throw engine_error() << "Service '" << _service_description << "' is not attached to any host or host group (properties " @@ -845,11 +731,9 @@ void service::merge(object const& obj) { MRG_OPTION(_flap_detection_options); MRG_OPTION(_freshness_threshold); MRG_OPTION(_high_flap_threshold); - MRG_INHERIT(_hostgroups); - MRG_INHERIT(_hosts); + MRG_DEFAULT(_host_name); MRG_DEFAULT(_icon_image); MRG_DEFAULT(_icon_image_alt); - MRG_OPTION(_initial_state); MRG_OPTION(_is_volatile); MRG_OPTION(_low_flap_threshold); MRG_OPTION(_max_check_attempts); @@ -1118,40 +1002,13 @@ unsigned int service::high_flap_threshold() const noexcept { return _high_flap_threshold; } -/** - * Get hostgroups. - * - * @return The hostgroups. - */ -set_string& service::hostgroups() noexcept { - return *_hostgroups; -} - -/** - * Get hostgroups. - * - * @return The hostgroups. - */ -set_string const& service::hostgroups() const noexcept { - return *_hostgroups; -} - /** * Get hosts. * * @return The hosts. */ -set_string& service::hosts() noexcept { - return *_hosts; -} - -/** - * Get hosts. - * - * @return The hosts. - */ -set_string const& service::hosts() const noexcept { - return *_hosts; +const std::string& service::host_name() const { + return _host_name; } /** @@ -1633,9 +1490,6 @@ bool service::_set_event_handler_enabled(bool value) { */ bool service::_set_failure_prediction_enabled(bool value) { (void)value; - engine_logger(log_verification_error, basic) - << "Warning: service failure_prediction_enabled is deprecated." - << " This option will not be supported in 20.04."; _logger->warn( "Warning: service failure_prediction_enabled is deprecated. This option " "will not be supported in 20.04."); @@ -1652,9 +1506,6 @@ bool service::_set_failure_prediction_enabled(bool value) { */ bool service::_set_failure_prediction_options(std::string const& value) { (void)value; - engine_logger(log_verification_error, basic) - << "Warning: service failure_prediction_options is deprecated." - << " This option will not be supported in 20.04."; _logger->warn( "Warning: service failure_prediction_options is deprecated. This option " "will not be supported in 20.04."); @@ -1742,26 +1593,14 @@ bool service::_set_high_flap_threshold(unsigned int value) { } /** - * Set hostgroups value. - * - * @param[in] value The new hostgroups value. - * - * @return True on success, otherwise false. - */ -bool service::_set_hostgroups(std::string const& value) { - _hostgroups = value; - return true; -} - -/** - * Set hosts value. + * Set host_name value. * - * @param[in] value The new hosts value. + * @param[in] value The new host_name value. * * @return True on success, otherwise false. */ -bool service::_set_hosts(std::string const& value) { - _hosts = value; +bool service::_set_host_name(const std::string& value) { + _host_name = value; return true; } @@ -1966,9 +1805,6 @@ bool service::_set_obsess_over_service(bool value) { */ bool service::_set_parallelize_check(bool value) { (void)value; - engine_logger(log_verification_error, basic) - << "Warning: service parallelize_check is deprecated" - << " This option will not be supported in 20.04."; _logger->warn( "Warning: service parallelize_check is deprecated This option will not " "be supported in 20.04."); diff --git a/engine/src/configuration/serviceescalation.cc b/engine/src/configuration/serviceescalation.cc index 19d7e005523..a4b9348ccf5 100644 --- a/engine/src/configuration/serviceescalation.cc +++ b/engine/src/configuration/serviceescalation.cc @@ -78,11 +78,6 @@ serviceescalation::serviceescalation(serviceescalation const& right) operator=(right); } -/** - * Destructor. - */ -serviceescalation::~serviceescalation() throw() {} - /** * Copy constructor. * diff --git a/engine/src/configuration/state.cc b/engine/src/configuration/state.cc index 6d870495e20..d3fe4d1e0ce 100644 --- a/engine/src/configuration/state.cc +++ b/engine/src/configuration/state.cc @@ -3340,7 +3340,7 @@ set_service::const_iterator state::services_find( const std::string& service_desc) const { for (auto it = _services.begin(), end = _services.end(); it != end; ++it) { if (it->service_description() == service_desc && - *it->hosts().begin() == host_name) + it->host_name() == host_name) return it; } return _services.end(); diff --git a/engine/src/main.cc b/engine/src/main.cc index 100e0245507..53dbe0d08e1 100644 --- a/engine/src/main.cc +++ b/engine/src/main.cc @@ -46,6 +46,7 @@ namespace asio = boost::asio; #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/broker/loader.hh" #include "com/centreon/engine/checks/checker.hh" +#include "com/centreon/engine/commands/connector.hh" #include "com/centreon/engine/config.hh" #include "com/centreon/engine/configuration/applier/logging.hh" #include "com/centreon/engine/configuration/applier/state.hh" @@ -67,7 +68,6 @@ namespace asio = boost::asio; #include "com/centreon/engine/retention/state.hh" #include "com/centreon/engine/statusdata.hh" #include "com/centreon/engine/string.hh" -#include "com/centreon/engine/utils.hh" #include "com/centreon/engine/version.hh" #include "com/centreon/io/directory_entry.hh" #include "com/centreon/logging/engine.hh" diff --git a/engine/src/xpddefault.cc b/engine/src/xpddefault.cc index 3aeaa79adc7..b21b5b3391a 100644 --- a/engine/src/xpddefault.cc +++ b/engine/src/xpddefault.cc @@ -22,6 +22,7 @@ #include #include #include +#include "com/centreon/engine/commands/command.hh" #include "com/centreon/engine/common.hh" #include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/globals.hh" @@ -170,8 +171,7 @@ int xpddefault_initialize_performance_data() { // get the command name, leave any arguments behind. temp_command_name = my_strtok(temp_buffer, "!"); - command_map::iterator cmd_found = - commands::command::commands.find(temp_command_name); + auto cmd_found = commands::command::commands.find(temp_command_name); if (cmd_found == commands::command::commands.end() || !cmd_found->second) { engine_logger(log_runtime_warning, basic) diff --git a/engine/tests/configuration/applier/applier-command.cc b/engine/tests/configuration/applier/applier-command.cc index b108a5a520d..3c530d44896 100755 --- a/engine/tests/configuration/applier/applier-command.cc +++ b/engine/tests/configuration/applier/applier-command.cc @@ -19,6 +19,8 @@ #include #include +#include "com/centreon/engine/commands/command.hh" +#include "com/centreon/engine/commands/connector.hh" #include "com/centreon/engine/configuration/applier/command.hh" #include "com/centreon/engine/configuration/applier/connector.hh" #include "com/centreon/engine/configuration/applier/contact.hh" diff --git a/engine/tests/configuration/applier/applier-connector.cc b/engine/tests/configuration/applier/applier-connector.cc index 57a4f13551c..ff183e871f8 100644 --- a/engine/tests/configuration/applier/applier-connector.cc +++ b/engine/tests/configuration/applier/applier-connector.cc @@ -18,6 +18,7 @@ */ #include #include "../../timeperiod/utils.hh" +#include "com/centreon/engine/commands/connector.hh" #include "com/centreon/engine/configuration/applier/command.hh" #include "com/centreon/engine/configuration/applier/connector.hh" #include "com/centreon/engine/configuration/connector.hh" diff --git a/engine/tests/configuration/applier/applier-contact.cc b/engine/tests/configuration/applier/applier-contact.cc index cf7752674be..001cfed503c 100644 --- a/engine/tests/configuration/applier/applier-contact.cc +++ b/engine/tests/configuration/applier/applier-contact.cc @@ -18,6 +18,7 @@ */ #include +#include "com/centreon/engine/commands/command.hh" #include "com/centreon/engine/configuration/applier/command.hh" #include "com/centreon/engine/configuration/applier/connector.hh" #include "com/centreon/engine/configuration/applier/contact.hh" diff --git a/engine/tests/configuration/applier/applier-service.cc b/engine/tests/configuration/applier/applier-service.cc index 80acf18f9c1..a77d25e71e0 100644 --- a/engine/tests/configuration/applier/applier-service.cc +++ b/engine/tests/configuration/applier/applier-service.cc @@ -29,8 +29,9 @@ #include "com/centreon/engine/configuration/applier/tag.hh" #include "com/centreon/engine/configuration/host.hh" #include "com/centreon/engine/configuration/service.hh" +#include "com/centreon/engine/contact.hh" #include "com/centreon/engine/exceptions/error.hh" -#include "com/centreon/engine/service.hh" +#include "com/centreon/engine/host.hh" #include "helper.hh" using namespace com::centreon; diff --git a/engine/tests/configuration/applier/applier-servicegroup.cc b/engine/tests/configuration/applier/applier-servicegroup.cc index 4798b9da52b..273507f8084 100644 --- a/engine/tests/configuration/applier/applier-servicegroup.cc +++ b/engine/tests/configuration/applier/applier-servicegroup.cc @@ -25,6 +25,7 @@ #include "com/centreon/engine/configuration/applier/service.hh" #include "com/centreon/engine/configuration/applier/servicegroup.hh" #include "com/centreon/engine/configuration/service.hh" +#include "com/centreon/engine/servicegroup.hh" #include "helper.hh" using namespace com::centreon; diff --git a/engine/tests/configuration/applier/applier-state.cc b/engine/tests/configuration/applier/applier-state.cc index cf5251b391a..3248dcf52d3 100644 --- a/engine/tests/configuration/applier/applier-state.cc +++ b/engine/tests/configuration/applier/applier-state.cc @@ -281,7 +281,6 @@ static void CreateConf() { "define service {\n" " host_name host_1\n" " name service_template\n" - " hostgroups hg1,hg2\n" " contacts contact1\n" " _SERVICE_ID 1001\n" " check_command command_19\n" @@ -732,7 +731,6 @@ TEST_F(ApplierState, StateLegacyParsing) { /* Service */ ASSERT_EQ(config.services().size(), SERVICES); auto sit = config.services().begin(); - ASSERT_EQ(sit->hosts().size(), 1u); ASSERT_EQ(sit->service_id(), 1); ASSERT_TRUE(sit->should_register()); ASSERT_TRUE(sit->checks_active()); @@ -745,10 +743,8 @@ TEST_F(ApplierState, StateLegacyParsing) { ++it; ASSERT_EQ(*it, std::string("cg3")); } - ASSERT_EQ(*sit->hosts().begin(), std::string("host_1")); - ASSERT_EQ(sit->service_description(), std::string("service_1")); - EXPECT_EQ(sit->hostgroups().size(), 2u); - EXPECT_EQ(*sit->hostgroups().begin(), std::string("hg1")); + ASSERT_EQ(sit->host_name(), std::string_view("host_1")); + ASSERT_EQ(sit->service_description(), std::string_view("service_1")); EXPECT_EQ(sit->contacts().size(), 2u); EXPECT_EQ(*sit->contacts().begin(), std::string("contact1")); EXPECT_EQ(sit->notification_options(), configuration::service::warning | diff --git a/engine/tests/custom_vars/extcmd.cc b/engine/tests/custom_vars/extcmd.cc index de842a55969..0bde69f2481 100755 --- a/engine/tests/custom_vars/extcmd.cc +++ b/engine/tests/custom_vars/extcmd.cc @@ -20,12 +20,13 @@ #include #include #include "../timeperiod/utils.hh" +#include "com/centreon/engine/commands/command.hh" +#include "com/centreon/engine/commands/commands.hh" #include "com/centreon/engine/configuration/applier/command.hh" #include "com/centreon/engine/configuration/applier/contact.hh" #include "com/centreon/engine/configuration/applier/host.hh" #include "com/centreon/engine/configuration/state.hh" #include "com/centreon/engine/macros/grab_host.hh" -#include "com/centreon/engine/commands/commands.hh" #include "helper.hh" using namespace com::centreon; diff --git a/engine/tests/notifications/host_flapping_notification.cc b/engine/tests/notifications/host_flapping_notification.cc index 6859d909d76..5f51a7a46ff 100644 --- a/engine/tests/notifications/host_flapping_notification.cc +++ b/engine/tests/notifications/host_flapping_notification.cc @@ -27,6 +27,7 @@ #include "com/centreon/engine/configuration/applier/host.hh" #include "com/centreon/engine/configuration/host.hh" #include "com/centreon/engine/exceptions/error.hh" +#include "com/centreon/engine/host.hh" #include "com/centreon/engine/hostescalation.hh" #include "com/centreon/engine/timezone_manager.hh" #include "helper.hh" diff --git a/engine/tests/notifications/host_recovery_notification.cc b/engine/tests/notifications/host_recovery_notification.cc index e9e0a8166e3..11ad9dbc673 100644 --- a/engine/tests/notifications/host_recovery_notification.cc +++ b/engine/tests/notifications/host_recovery_notification.cc @@ -26,6 +26,7 @@ #include "com/centreon/engine/configuration/applier/host.hh" #include "com/centreon/engine/configuration/host.hh" #include "com/centreon/engine/exceptions/error.hh" +#include "com/centreon/engine/host.hh" #include "com/centreon/engine/hostescalation.hh" using namespace com::centreon; From 497e02dbf1f2d9f667b5ce608df8c31cf816f6d1 Mon Sep 17 00:00:00 2001 From: David Boucher Date: Tue, 11 Jun 2024 17:17:38 +0200 Subject: [PATCH 33/60] enh(tests): big metrics do not fail anymore when inserted in database * fix(broker): new script to compute database columns max sizes * fix(broker/bam): the good size of float is inserted into the database for bam * fix(broker): perfdata class contains float numbers now. * enh(tests): big metrics do not fail anymore when inserted in database * fix(broker): double to float changes the precision REFS: MON-92694 --- bbdo/bam/dimension_ba_event.cc | 48 +- bbdo/bam/dimension_bv_event.cc | 48 +- bbdo/bam/dimension_kpi_event.cc | 86 ++-- bbdo/bam/dimension_timeperiod.cc | 79 +-- bbdo/bam/kpi_event.cc | 50 +- bbdo/storage/metric.cc | 35 +- broker/bam/src/availability_thread.cc | 5 +- broker/bam/src/monitoring_stream.cc | 28 +- broker/bam/src/reporting_stream.cc | 363 ++++++++------ .../inc/com/centreon/broker/misc/perfdata.hh | 48 +- broker/core/sql/src/table_max_size.py | 92 ++-- broker/core/src/misc/parse_perfdata.cc | 44 +- broker/core/src/misc/perfdata.cc | 79 ++- broker/core/test/misc/perfdata.cc | 56 +-- broker/grpc/test/acceptor.cc | 2 + broker/lua/test/lua.cc | 6 +- broker/neb/src/acknowledgement.cc | 43 +- broker/neb/src/comment.cc | 42 +- broker/neb/src/custom_variable.cc | 41 +- broker/neb/src/custom_variable_status.cc | 38 +- broker/neb/src/downtime.cc | 38 +- broker/neb/src/host.cc | 117 +++-- broker/neb/src/host_check.cc | 35 +- broker/neb/src/host_dependency.cc | 59 +-- broker/neb/src/host_group.cc | 35 +- broker/neb/src/host_status.cc | 55 ++- broker/neb/src/instance.cc | 41 +- broker/neb/src/instance_status.cc | 38 +- broker/neb/src/log_entry.cc | 58 ++- broker/neb/src/service.cc | 71 +-- broker/neb/src/service_check.cc | 35 +- broker/neb/src/service_dependency.cc | 49 +- broker/neb/src/service_group.cc | 35 +- broker/neb/src/service_status.cc | 47 +- broker/neb/test/service.cc | 3 +- broker/storage/src/conflict_manager_sql.cc | 54 ++- .../storage/src/conflict_manager_storage.cc | 19 +- broker/unified_sql/src/stream_sql.cc | 456 ++++++++++++------ broker/unified_sql/src/stream_storage.cc | 31 +- tests/broker-engine/big-metrics.robot | 50 ++ tests/resources/Engine.py | 27 ++ 41 files changed, 1496 insertions(+), 1090 deletions(-) create mode 100644 tests/broker-engine/big-metrics.robot diff --git a/bbdo/bam/dimension_ba_event.cc b/bbdo/bam/dimension_ba_event.cc index bc124013379..661360adedc 100644 --- a/bbdo/bam/dimension_ba_event.cc +++ b/bbdo/bam/dimension_ba_event.cc @@ -1,20 +1,20 @@ /** -* Copyright 2014-2015 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2014-2015 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "bbdo/bam/dimension_ba_event.hh" @@ -102,14 +102,14 @@ mapping::entry const dimension_ba_event::entries[] = { mapping::entry(&bam::dimension_ba_event::ba_id, "ba_id", mapping::entry::invalid_on_zero), - mapping::entry( - &bam::dimension_ba_event::ba_name, - "ba_name", - get_mod_bam_reporting_ba_col_size(mod_bam_reporting_ba_ba_name)), - mapping::entry( - &bam::dimension_ba_event::ba_description, - "ba_description", - get_mod_bam_reporting_ba_col_size(mod_bam_reporting_ba_ba_description)), + mapping::entry(&bam::dimension_ba_event::ba_name, + "ba_name", + get_centreon_storage_mod_bam_reporting_ba_col_size( + centreon_storage_mod_bam_reporting_ba_ba_name)), + mapping::entry(&bam::dimension_ba_event::ba_description, + "ba_description", + get_centreon_storage_mod_bam_reporting_ba_col_size( + centreon_storage_mod_bam_reporting_ba_ba_description)), mapping::entry(&bam::dimension_ba_event::sla_month_percent_crit, "sla_month_percent_crit"), mapping::entry(&bam::dimension_ba_event::sla_month_percent_warn, diff --git a/bbdo/bam/dimension_bv_event.cc b/bbdo/bam/dimension_bv_event.cc index a35c020c0a8..aa956b2a52c 100644 --- a/bbdo/bam/dimension_bv_event.cc +++ b/bbdo/bam/dimension_bv_event.cc @@ -1,20 +1,20 @@ /** -* Copyright 2014-2015 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2014-2015 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "bbdo/bam/dimension_bv_event.hh" @@ -94,14 +94,14 @@ mapping::entry const dimension_bv_event::entries[] = { mapping::entry(&bam::dimension_bv_event::bv_id, "bv_id", mapping::entry::invalid_on_zero), - mapping::entry( - &bam::dimension_bv_event::bv_name, - "bv_name", - get_mod_bam_reporting_bv_col_size(mod_bam_reporting_bv_bv_name)), - mapping::entry( - &bam::dimension_bv_event::bv_description, - "bv_description", - get_mod_bam_reporting_bv_col_size(mod_bam_reporting_bv_bv_description)), + mapping::entry(&bam::dimension_bv_event::bv_name, + "bv_name", + get_centreon_storage_mod_bam_reporting_bv_col_size( + centreon_storage_mod_bam_reporting_bv_bv_name)), + mapping::entry(&bam::dimension_bv_event::bv_description, + "bv_description", + get_centreon_storage_mod_bam_reporting_bv_col_size( + centreon_storage_mod_bam_reporting_bv_bv_description)), mapping::entry()}; // Operations. diff --git a/bbdo/bam/dimension_kpi_event.cc b/bbdo/bam/dimension_kpi_event.cc index f63ba81d1ab..2745256e1b6 100644 --- a/bbdo/bam/dimension_kpi_event.cc +++ b/bbdo/bam/dimension_kpi_event.cc @@ -1,20 +1,20 @@ /** -* Copyright 2014-2015,2019-2021 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2014-2015,2019-2021 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "bbdo/bam/dimension_kpi_event.hh" @@ -94,47 +94,49 @@ mapping::entry const dimension_kpi_event::entries[] = { mapping::entry(&bam::dimension_kpi_event::ba_id, "ba_id", mapping::entry::invalid_on_zero), - mapping::entry( - &bam::dimension_kpi_event::ba_name, - "ba_name", - get_mod_bam_reporting_kpi_col_size(mod_bam_reporting_kpi_ba_name)), + mapping::entry(&bam::dimension_kpi_event::ba_name, + "ba_name", + get_centreon_storage_mod_bam_reporting_kpi_col_size( + centreon_storage_mod_bam_reporting_kpi_ba_name)), mapping::entry(&bam::dimension_kpi_event::host_id, "host_id", mapping::entry::invalid_on_zero), - mapping::entry( - &bam::dimension_kpi_event::host_name, - "host_name", - get_mod_bam_reporting_kpi_col_size(mod_bam_reporting_kpi_host_name)), + mapping::entry(&bam::dimension_kpi_event::host_name, + "host_name", + get_centreon_storage_mod_bam_reporting_kpi_col_size( + centreon_storage_mod_bam_reporting_kpi_host_name)), mapping::entry(&bam::dimension_kpi_event::service_id, "service_id", mapping::entry::invalid_on_zero), - mapping::entry(&bam::dimension_kpi_event::service_description, - "service_description", - get_mod_bam_reporting_kpi_col_size( - mod_bam_reporting_kpi_service_description)), + mapping::entry( + &bam::dimension_kpi_event::service_description, + "service_description", + get_centreon_storage_mod_bam_reporting_kpi_col_size( + centreon_storage_mod_bam_reporting_kpi_service_description)), mapping::entry(&bam::dimension_kpi_event::kpi_ba_id, "kpi_ba_id", mapping::entry::invalid_on_zero), - mapping::entry( - &bam::dimension_kpi_event::kpi_ba_name, - "kpi_ba_name", - get_mod_bam_reporting_kpi_col_size(mod_bam_reporting_kpi_kpi_ba_name)), + mapping::entry(&bam::dimension_kpi_event::kpi_ba_name, + "kpi_ba_name", + get_centreon_storage_mod_bam_reporting_kpi_col_size( + centreon_storage_mod_bam_reporting_kpi_kpi_ba_name)), mapping::entry(&bam::dimension_kpi_event::meta_service_id, "meta_service_id", mapping::entry::invalid_on_zero), - mapping::entry(&bam::dimension_kpi_event::meta_service_name, - "meta_service_name", - get_mod_bam_reporting_kpi_col_size( - mod_bam_reporting_kpi_meta_service_name), - mapping::entry::invalid_on_zero), + mapping::entry( + &bam::dimension_kpi_event::meta_service_name, + "meta_service_name", + get_centreon_storage_mod_bam_reporting_kpi_col_size( + centreon_storage_mod_bam_reporting_kpi_meta_service_name), + mapping::entry::invalid_on_zero), mapping::entry(&bam::dimension_kpi_event::boolean_id, "boolean_id", mapping::entry::invalid_on_zero), - mapping::entry( - &bam::dimension_kpi_event::boolean_name, - "boolean_name", - get_mod_bam_reporting_kpi_col_size(mod_bam_reporting_kpi_boolean_name), - mapping::entry::invalid_on_zero), + mapping::entry(&bam::dimension_kpi_event::boolean_name, + "boolean_name", + get_centreon_storage_mod_bam_reporting_kpi_col_size( + centreon_storage_mod_bam_reporting_kpi_boolean_name), + mapping::entry::invalid_on_zero), mapping::entry(&bam::dimension_kpi_event::impact_warning, "impact_warning"), mapping::entry(&bam::dimension_kpi_event::impact_critical, "impact_critical"), diff --git a/bbdo/bam/dimension_timeperiod.cc b/bbdo/bam/dimension_timeperiod.cc index b6177b8bc5b..a3497d1eb7c 100644 --- a/bbdo/bam/dimension_timeperiod.cc +++ b/bbdo/bam/dimension_timeperiod.cc @@ -1,20 +1,20 @@ /** -* Copyright 2014-2015 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2014-2015 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "bbdo/bam/dimension_timeperiod.hh" @@ -36,36 +36,39 @@ mapping::entry const dimension_timeperiod::entries[] = { mapping::entry::invalid_on_zero), mapping::entry(&bam::dimension_timeperiod::name, "name", - get_mod_bam_reporting_timeperiods_col_size( - mod_bam_reporting_timeperiods_name)), + get_centreon_storage_mod_bam_reporting_timeperiods_col_size( + centreon_storage_mod_bam_reporting_timeperiods_name)), mapping::entry(&bam::dimension_timeperiod::monday, "monday", - get_mod_bam_reporting_timeperiods_col_size( - mod_bam_reporting_timeperiods_monday)), + get_centreon_storage_mod_bam_reporting_timeperiods_col_size( + centreon_storage_mod_bam_reporting_timeperiods_monday)), mapping::entry(&bam::dimension_timeperiod::tuesday, "tuesday", - get_mod_bam_reporting_timeperiods_col_size( - mod_bam_reporting_timeperiods_tuesday)), - mapping::entry(&bam::dimension_timeperiod::wednesday, - "wednesday", - get_mod_bam_reporting_timeperiods_col_size( - mod_bam_reporting_timeperiods_wednesday)), - mapping::entry(&bam::dimension_timeperiod::thursday, - "thursday", - get_mod_bam_reporting_timeperiods_col_size( - mod_bam_reporting_timeperiods_thursday)), + get_centreon_storage_mod_bam_reporting_timeperiods_col_size( + centreon_storage_mod_bam_reporting_timeperiods_tuesday)), + mapping::entry( + &bam::dimension_timeperiod::wednesday, + "wednesday", + get_centreon_storage_mod_bam_reporting_timeperiods_col_size( + centreon_storage_mod_bam_reporting_timeperiods_wednesday)), + mapping::entry( + &bam::dimension_timeperiod::thursday, + "thursday", + get_centreon_storage_mod_bam_reporting_timeperiods_col_size( + centreon_storage_mod_bam_reporting_timeperiods_thursday)), mapping::entry(&bam::dimension_timeperiod::friday, "friday", - get_mod_bam_reporting_timeperiods_col_size( - mod_bam_reporting_timeperiods_friday)), - mapping::entry(&bam::dimension_timeperiod::saturday, - "saturday", - get_mod_bam_reporting_timeperiods_col_size( - mod_bam_reporting_timeperiods_saturday)), + get_centreon_storage_mod_bam_reporting_timeperiods_col_size( + centreon_storage_mod_bam_reporting_timeperiods_friday)), + mapping::entry( + &bam::dimension_timeperiod::saturday, + "saturday", + get_centreon_storage_mod_bam_reporting_timeperiods_col_size( + centreon_storage_mod_bam_reporting_timeperiods_saturday)), mapping::entry(&bam::dimension_timeperiod::sunday, "sunday", - get_mod_bam_reporting_timeperiods_col_size( - mod_bam_reporting_timeperiods_sunday)), + get_centreon_storage_mod_bam_reporting_timeperiods_col_size( + centreon_storage_mod_bam_reporting_timeperiods_sunday)), mapping::entry()}; // Operations. diff --git a/bbdo/bam/kpi_event.cc b/bbdo/bam/kpi_event.cc index 3dabcf0ca64..f514c437b1e 100644 --- a/bbdo/bam/kpi_event.cc +++ b/bbdo/bam/kpi_event.cc @@ -1,20 +1,20 @@ /** -* Copyright 2014-2015, 2021 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2014-2015, 2021 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "bbdo/bam/kpi_event.hh" @@ -99,14 +99,16 @@ mapping::entry const kpi_event::entries[] = { mapping::entry(&bam::kpi_event::end_time, "end_time"), mapping::entry(&bam::kpi_event::impact_level, "impact_level"), mapping::entry(&bam::kpi_event::in_downtime, "in_downtime"), - mapping::entry(&bam::kpi_event::output, - "first_output", - get_mod_bam_reporting_kpi_events_col_size( - mod_bam_reporting_kpi_events_first_output)), - mapping::entry(&bam::kpi_event::perfdata, - "first_perfdata", - get_mod_bam_reporting_kpi_events_col_size( - mod_bam_reporting_kpi_events_first_perfdata)), + mapping::entry( + &bam::kpi_event::output, + "first_output", + get_centreon_storage_mod_bam_reporting_kpi_events_col_size( + centreon_storage_mod_bam_reporting_kpi_events_first_output)), + mapping::entry( + &bam::kpi_event::perfdata, + "first_perfdata", + get_centreon_storage_mod_bam_reporting_kpi_events_col_size( + centreon_storage_mod_bam_reporting_kpi_events_first_perfdata)), mapping::entry(&bam::kpi_event::start_time, "start_time"), mapping::entry(&bam::kpi_event::status, "status"), mapping::entry()}; diff --git a/bbdo/storage/metric.cc b/bbdo/storage/metric.cc index 84d9cd89d07..2c2ac1b0971 100644 --- a/bbdo/storage/metric.cc +++ b/bbdo/storage/metric.cc @@ -1,20 +1,20 @@ /** -* Copyright 2009-2013, 2022 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2009-2013, 2022 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "bbdo/storage/metric.hh" @@ -95,7 +95,8 @@ mapping::entry const metric::entries[] = { mapping::entry::invalid_on_zero), mapping::entry(&metric::name, "name", - get_metrics_col_size(metrics_metric_name)), + get_centreon_storage_metrics_col_size( + centreon_storage_metrics_metric_name)), mapping::entry(&metric::rrd_len, "rrd_len"), mapping::entry(&metric::value, "value"), mapping::entry(&metric::value_type, "value_type"), diff --git a/broker/bam/src/availability_thread.cc b/broker/bam/src/availability_thread.cc index 4ce181f5a47..82d52a7ed44 100644 --- a/broker/bam/src/availability_thread.cc +++ b/broker/bam/src/availability_thread.cc @@ -184,8 +184,7 @@ void availability_thread::_build_availabilities(time_t midnight) { if (_should_rebuild_all) { query_str = fmt::format( "SELECT MIN(start_time), MAX(end_time), MIN(IFNULL(end_time, '0'))" - " FROM mod_bam_reporting_ba_events" - " WHERE ba_id IN ({})", + " FROM mod_bam_reporting_ba_events WHERE ba_id IN ({})", _bas_to_rebuild); try { std::promise promise; @@ -200,7 +199,7 @@ void availability_thread::_build_availabilities(time_t midnight) { // If there is opened events, rebuild until midnight of this day. // If not, rebuild until the last closed events. if (res.value_as_i32(2) != 0) - last_day = misc::start_of_day(res.value_as_f64(1)); + last_day = misc::start_of_day(res.value_as_i32(1)); _delete_all_availabilities(); } catch (const std::exception& e) { diff --git a/broker/bam/src/monitoring_stream.cc b/broker/bam/src/monitoring_stream.cc index c22519d688d..4d83c740251 100644 --- a/broker/bam/src/monitoring_stream.cc +++ b/broker/bam/src/monitoring_stream.cc @@ -203,9 +203,9 @@ struct bulk_ba_binder { void operator()(database::mysql_bulk_bind& binder) const { if (event->type() == ba_status::static_type()) { const ba_status& status = *std::static_pointer_cast(event); - binder.set_value_as_f64(0, status.level_nominal); - binder.set_value_as_f64(1, status.level_acknowledgement); - binder.set_value_as_f64(2, status.level_downtime); + binder.set_value_as_f32(0, status.level_nominal); + binder.set_value_as_f32(1, status.level_acknowledgement); + binder.set_value_as_f32(2, status.level_downtime); binder.set_value_as_u32(7, status.ba_id); if (status.last_state_change.is_null()) binder.set_null_u64(3); @@ -217,9 +217,9 @@ struct bulk_ba_binder { } else { const BaStatus& status = static_cast(event.get())->obj(); - binder.set_value_as_f64(0, status.level_nominal()); - binder.set_value_as_f64(1, status.level_acknowledgement()); - binder.set_value_as_f64(2, status.level_downtime()); + binder.set_value_as_f32(0, status.level_nominal()); + binder.set_value_as_f32(1, status.level_acknowledgement()); + binder.set_value_as_f32(2, status.level_downtime()); binder.set_value_as_u32(7, status.ba_id()); if (status.last_state_change() <= 0) binder.set_null_u64(3); @@ -274,32 +274,32 @@ struct bulk_kpi_binder { void operator()(database::mysql_bulk_bind& binder) const { if (event->type() == kpi_status::static_type()) { const kpi_status& status = *std::static_pointer_cast(event); - binder.set_value_as_f64(0, status.level_acknowledgement_hard); + binder.set_value_as_f32(0, status.level_acknowledgement_hard); binder.set_value_as_i32(1, status.state_hard); - binder.set_value_as_f64(2, status.level_downtime_hard); - binder.set_value_as_f64(3, status.level_nominal_hard); + binder.set_value_as_f32(2, status.level_downtime_hard); + binder.set_value_as_f32(3, status.level_nominal_hard); binder.set_value_as_i32(4, 1 + 1); if (status.last_state_change.is_null()) binder.set_null_u64(5); else binder.set_value_as_u64(5, status.last_state_change.get_time_t()); - binder.set_value_as_f64(6, status.last_impact); + binder.set_value_as_f32(6, status.last_impact); binder.set_value_as_bool(7, status.valid); binder.set_value_as_bool(8, status.in_downtime); binder.set_value_as_u32(9, status.kpi_id); } else { const KpiStatus& status( std::static_pointer_cast(event)->obj()); - binder.set_value_as_f64(0, status.level_acknowledgement_hard()); + binder.set_value_as_f32(0, status.level_acknowledgement_hard()); binder.set_value_as_i32(1, status.state_hard()); - binder.set_value_as_f64(2, status.level_downtime_hard()); - binder.set_value_as_f64(3, status.level_nominal_hard()); + binder.set_value_as_f32(2, status.level_downtime_hard()); + binder.set_value_as_f32(3, status.level_nominal_hard()); binder.set_value_as_i32(4, 1 + 1); if (status.last_state_change() <= 0) binder.set_null_u64(5); else binder.set_value_as_u64(5, status.last_state_change()); - binder.set_value_as_f64(6, status.last_impact()); + binder.set_value_as_f32(6, status.last_impact()); binder.set_value_as_bool(7, status.valid()); binder.set_value_as_bool(8, status.in_downtime()); binder.set_value_as_u32(9, status.kpi_id()); diff --git a/broker/bam/src/reporting_stream.cc b/broker/bam/src/reporting_stream.cc index 58ce9a1eeb2..6fd5a8e8903 100644 --- a/broker/bam/src/reporting_stream.cc +++ b/broker/bam/src/reporting_stream.cc @@ -542,47 +542,54 @@ struct bulk_dimension_kpi_binder { binder.set_value_as_i32(0, dk.kpi_id); binder.set_value_as_str( - 1, misc::string::truncate(kpi_name, - get_mod_bam_reporting_kpi_col_size( - mod_bam_reporting_kpi_kpi_name))); + 1, + misc::string::truncate( + kpi_name, get_centreon_storage_mod_bam_reporting_kpi_col_size( + centreon_storage_mod_bam_reporting_kpi_kpi_name))); binder.set_value_as_i32(2, dk.ba_id); binder.set_value_as_str( - 3, misc::string::truncate(dk.ba_name, - get_mod_bam_reporting_kpi_col_size( - mod_bam_reporting_kpi_ba_name))); + 3, + misc::string::truncate( + dk.ba_name, get_centreon_storage_mod_bam_reporting_kpi_col_size( + centreon_storage_mod_bam_reporting_kpi_ba_name))); binder.set_value_as_i32(4, dk.host_id); binder.set_value_as_str( - 5, misc::string::truncate(dk.host_name, - get_mod_bam_reporting_kpi_col_size( - mod_bam_reporting_kpi_host_name))); + 5, misc::string::truncate( + dk.host_name, + get_centreon_storage_mod_bam_reporting_kpi_col_size( + centreon_storage_mod_bam_reporting_kpi_host_name))); binder.set_value_as_i32(6, dk.service_id); binder.set_value_as_str( - 7, misc::string::truncate( - dk.service_description, - get_mod_bam_reporting_kpi_col_size( - mod_bam_reporting_kpi_service_description))); + 7, + misc::string::truncate( + dk.service_description, + get_centreon_storage_mod_bam_reporting_kpi_col_size( + centreon_storage_mod_bam_reporting_kpi_service_description))); if (dk.kpi_ba_id) binder.set_value_as_i32(8, dk.kpi_ba_id); else binder.set_null_i32(8); binder.set_value_as_str( - 9, misc::string::truncate(dk.kpi_ba_name, - get_mod_bam_reporting_kpi_col_size( - mod_bam_reporting_kpi_kpi_ba_name))); + 9, misc::string::truncate( + dk.kpi_ba_name, + get_centreon_storage_mod_bam_reporting_kpi_col_size( + centreon_storage_mod_bam_reporting_kpi_kpi_ba_name))); binder.set_value_as_i32(10, dk.meta_service_id); binder.set_value_as_str( 11, - misc::string::truncate(dk.meta_service_name, - get_mod_bam_reporting_kpi_col_size( - mod_bam_reporting_kpi_meta_service_name))); - binder.set_value_as_f64(12, dk.impact_warning); - binder.set_value_as_f64(13, dk.impact_critical); - binder.set_value_as_f64(14, dk.impact_unknown); + misc::string::truncate( + dk.meta_service_name, + get_centreon_storage_mod_bam_reporting_kpi_col_size( + centreon_storage_mod_bam_reporting_kpi_meta_service_name))); + binder.set_value_as_f32(12, dk.impact_warning); + binder.set_value_as_f32(13, dk.impact_critical); + binder.set_value_as_f32(14, dk.impact_unknown); binder.set_value_as_i32(15, dk.boolean_id); binder.set_value_as_str( - 16, misc::string::truncate(dk.boolean_name, - get_mod_bam_reporting_kpi_col_size( - mod_bam_reporting_kpi_boolean_name))); + 16, misc::string::truncate( + dk.boolean_name, + get_centreon_storage_mod_bam_reporting_kpi_col_size( + centreon_storage_mod_bam_reporting_kpi_boolean_name))); } else { const DimensionKpiEvent& dk = std::static_pointer_cast(event) @@ -604,47 +611,54 @@ struct bulk_dimension_kpi_binder { binder.set_value_as_i32(0, dk.kpi_id()); binder.set_value_as_str( - 1, misc::string::truncate(kpi_name, - get_mod_bam_reporting_kpi_col_size( - mod_bam_reporting_kpi_kpi_name))); + 1, + misc::string::truncate( + kpi_name, get_centreon_storage_mod_bam_reporting_kpi_col_size( + centreon_storage_mod_bam_reporting_kpi_kpi_name))); binder.set_value_as_i32(2, dk.ba_id()); binder.set_value_as_str( - 3, misc::string::truncate(dk.ba_name(), - get_mod_bam_reporting_kpi_col_size( - mod_bam_reporting_kpi_ba_name))); + 3, misc::string::truncate( + dk.ba_name(), + get_centreon_storage_mod_bam_reporting_kpi_col_size( + centreon_storage_mod_bam_reporting_kpi_ba_name))); binder.set_value_as_i32(4, dk.host_id()); binder.set_value_as_str( - 5, misc::string::truncate(dk.host_name(), - get_mod_bam_reporting_kpi_col_size( - mod_bam_reporting_kpi_host_name))); + 5, misc::string::truncate( + dk.host_name(), + get_centreon_storage_mod_bam_reporting_kpi_col_size( + centreon_storage_mod_bam_reporting_kpi_host_name))); binder.set_value_as_i32(6, dk.service_id()); binder.set_value_as_str( - 7, misc::string::truncate( - dk.service_description(), - get_mod_bam_reporting_kpi_col_size( - mod_bam_reporting_kpi_service_description))); + 7, + misc::string::truncate( + dk.service_description(), + get_centreon_storage_mod_bam_reporting_kpi_col_size( + centreon_storage_mod_bam_reporting_kpi_service_description))); if (dk.kpi_ba_id()) binder.set_value_as_i32(8, dk.kpi_ba_id()); else binder.set_null_i32(8); binder.set_value_as_str( - 9, misc::string::truncate(dk.kpi_ba_name(), - get_mod_bam_reporting_kpi_col_size( - mod_bam_reporting_kpi_kpi_ba_name))); + 9, misc::string::truncate( + dk.kpi_ba_name(), + get_centreon_storage_mod_bam_reporting_kpi_col_size( + centreon_storage_mod_bam_reporting_kpi_kpi_ba_name))); binder.set_value_as_i32(10, dk.meta_service_id()); binder.set_value_as_str( 11, - misc::string::truncate(dk.meta_service_name(), - get_mod_bam_reporting_kpi_col_size( - mod_bam_reporting_kpi_meta_service_name))); - binder.set_value_as_f64(12, dk.impact_warning()); - binder.set_value_as_f64(13, dk.impact_critical()); - binder.set_value_as_f64(14, dk.impact_unknown()); + misc::string::truncate( + dk.meta_service_name(), + get_centreon_storage_mod_bam_reporting_kpi_col_size( + centreon_storage_mod_bam_reporting_kpi_meta_service_name))); + binder.set_value_as_f32(12, dk.impact_warning()); + binder.set_value_as_f32(13, dk.impact_critical()); + binder.set_value_as_f32(14, dk.impact_unknown()); binder.set_value_as_i32(15, dk.boolean_id()); binder.set_value_as_str( - 16, misc::string::truncate(dk.boolean_name(), - get_mod_bam_reporting_kpi_col_size( - mod_bam_reporting_kpi_boolean_name))); + 16, misc::string::truncate( + dk.boolean_name(), + get_centreon_storage_mod_bam_reporting_kpi_col_size( + centreon_storage_mod_bam_reporting_kpi_boolean_name))); } binder.next_row(); } @@ -677,34 +691,39 @@ struct dimension_kpi_binder { return fmt::format( "({},'{}',{},'{}',{},'{}',{},'{}',{},'{}',{},'{}',{},{},{},{},'{}')", dk.kpi_id, - misc::string::truncate(kpi_name, get_mod_bam_reporting_kpi_col_size( - mod_bam_reporting_kpi_kpi_name)), + misc::string::truncate( + kpi_name, get_centreon_storage_mod_bam_reporting_kpi_col_size( + centreon_storage_mod_bam_reporting_kpi_kpi_name)), dk.ba_id, - misc::string::truncate(dk.ba_name, - get_mod_bam_reporting_kpi_col_size( - mod_bam_reporting_kpi_ba_name)), + misc::string::truncate( + dk.ba_name, get_centreon_storage_mod_bam_reporting_kpi_col_size( + centreon_storage_mod_bam_reporting_kpi_ba_name)), dk.host_id, - misc::string::truncate(dk.host_name, - get_mod_bam_reporting_kpi_col_size( - mod_bam_reporting_kpi_host_name)), + misc::string::truncate( + dk.host_name, + get_centreon_storage_mod_bam_reporting_kpi_col_size( + centreon_storage_mod_bam_reporting_kpi_host_name)), dk.service_id, misc::string::truncate( dk.service_description, - get_mod_bam_reporting_kpi_col_size( - mod_bam_reporting_kpi_service_description)), + get_centreon_storage_mod_bam_reporting_kpi_col_size( + centreon_storage_mod_bam_reporting_kpi_service_description)), sz_kpi_ba_id, - misc::string::truncate(dk.kpi_ba_name, - get_mod_bam_reporting_kpi_col_size( - mod_bam_reporting_kpi_kpi_ba_name)), + misc::string::truncate( + dk.kpi_ba_name, + get_centreon_storage_mod_bam_reporting_kpi_col_size( + centreon_storage_mod_bam_reporting_kpi_kpi_ba_name)), dk.meta_service_id, - misc::string::truncate(dk.meta_service_name, - get_mod_bam_reporting_kpi_col_size( - mod_bam_reporting_kpi_meta_service_name)), + misc::string::truncate( + dk.meta_service_name, + get_centreon_storage_mod_bam_reporting_kpi_col_size( + centreon_storage_mod_bam_reporting_kpi_meta_service_name)), dk.impact_warning, dk.impact_critical, dk.impact_unknown, dk.boolean_id, - misc::string::truncate(dk.boolean_name, - get_mod_bam_reporting_kpi_col_size( - mod_bam_reporting_kpi_boolean_name))); + misc::string::truncate( + dk.boolean_name, + get_centreon_storage_mod_bam_reporting_kpi_col_size( + centreon_storage_mod_bam_reporting_kpi_boolean_name))); } else { const DimensionKpiEvent& dk = std::static_pointer_cast(event) @@ -728,34 +747,40 @@ struct dimension_kpi_binder { return fmt::format( "({},'{}',{},'{}',{},'{}',{},'{}',{},'{}',{},'{}',{},{},{},{},'{}')", dk.kpi_id(), - misc::string::truncate(kpi_name, get_mod_bam_reporting_kpi_col_size( - mod_bam_reporting_kpi_kpi_name)), + misc::string::truncate( + kpi_name, get_centreon_storage_mod_bam_reporting_kpi_col_size( + centreon_storage_mod_bam_reporting_kpi_kpi_name)), dk.ba_id(), - misc::string::truncate(dk.ba_name(), - get_mod_bam_reporting_kpi_col_size( - mod_bam_reporting_kpi_ba_name)), + misc::string::truncate( + dk.ba_name(), + get_centreon_storage_mod_bam_reporting_kpi_col_size( + centreon_storage_mod_bam_reporting_kpi_ba_name)), dk.host_id(), - misc::string::truncate(dk.host_name(), - get_mod_bam_reporting_kpi_col_size( - mod_bam_reporting_kpi_host_name)), + misc::string::truncate( + dk.host_name(), + get_centreon_storage_mod_bam_reporting_kpi_col_size( + centreon_storage_mod_bam_reporting_kpi_host_name)), dk.service_id(), misc::string::truncate( dk.service_description(), - get_mod_bam_reporting_kpi_col_size( - mod_bam_reporting_kpi_service_description)), + get_centreon_storage_mod_bam_reporting_kpi_col_size( + centreon_storage_mod_bam_reporting_kpi_service_description)), sz_kpi_ba_id, - misc::string::truncate(dk.kpi_ba_name(), - get_mod_bam_reporting_kpi_col_size( - mod_bam_reporting_kpi_kpi_ba_name)), + misc::string::truncate( + dk.kpi_ba_name(), + get_centreon_storage_mod_bam_reporting_kpi_col_size( + centreon_storage_mod_bam_reporting_kpi_kpi_ba_name)), dk.meta_service_id(), - misc::string::truncate(dk.meta_service_name(), - get_mod_bam_reporting_kpi_col_size( - mod_bam_reporting_kpi_meta_service_name)), + misc::string::truncate( + dk.meta_service_name(), + get_centreon_storage_mod_bam_reporting_kpi_col_size( + centreon_storage_mod_bam_reporting_kpi_meta_service_name)), dk.impact_warning(), dk.impact_critical(), dk.impact_unknown(), dk.boolean_id(), - misc::string::truncate(dk.boolean_name(), - get_mod_bam_reporting_kpi_col_size( - mod_bam_reporting_kpi_boolean_name))); + misc::string::truncate( + dk.boolean_name(), + get_centreon_storage_mod_bam_reporting_kpi_col_size( + centreon_storage_mod_bam_reporting_kpi_boolean_name))); } } }; @@ -1431,12 +1456,13 @@ void reporting_stream::_process_dimension_ba( _dimension_ba_insert.bind_value_as_i32(0, dba.ba_id); _dimension_ba_insert.bind_value_as_str( 1, misc::string::truncate( - dba.ba_name, - get_mod_bam_reporting_ba_col_size(mod_bam_reporting_ba_ba_name))); + dba.ba_name, get_centreon_storage_mod_bam_reporting_ba_col_size( + centreon_storage_mod_bam_reporting_ba_ba_name))); _dimension_ba_insert.bind_value_as_str( - 2, misc::string::truncate(dba.ba_description, - get_mod_bam_reporting_ba_col_size( - mod_bam_reporting_ba_ba_description))); + 2, misc::string::truncate( + dba.ba_description, + get_centreon_storage_mod_bam_reporting_ba_col_size( + centreon_storage_mod_bam_reporting_ba_ba_description))); _dimension_ba_insert.bind_value_as_f64(3, dba.sla_month_percent_crit); _dimension_ba_insert.bind_value_as_f64(4, dba.sla_month_percent_warn); _dimension_ba_insert.bind_value_as_f64(5, dba.sla_duration_crit); @@ -1458,13 +1484,15 @@ void reporting_stream::_process_pb_dimension_ba( dba.ba_id(), dba.ba_description()); _dimension_ba_insert.bind_value_as_i32(0, dba.ba_id()); _dimension_ba_insert.bind_value_as_str( - 1, misc::string::truncate( - dba.ba_name(), - get_mod_bam_reporting_ba_col_size(mod_bam_reporting_ba_ba_name))); + 1, + misc::string::truncate( + dba.ba_name(), get_centreon_storage_mod_bam_reporting_ba_col_size( + centreon_storage_mod_bam_reporting_ba_ba_name))); _dimension_ba_insert.bind_value_as_str( - 2, misc::string::truncate(dba.ba_description(), - get_mod_bam_reporting_ba_col_size( - mod_bam_reporting_ba_ba_description))); + 2, misc::string::truncate( + dba.ba_description(), + get_centreon_storage_mod_bam_reporting_ba_col_size( + centreon_storage_mod_bam_reporting_ba_ba_description))); _dimension_ba_insert.bind_value_as_f64(3, dba.sla_month_percent_crit()); _dimension_ba_insert.bind_value_as_f64(4, dba.sla_month_percent_warn()); _dimension_ba_insert.bind_value_as_f64(5, dba.sla_duration_crit()); @@ -1487,12 +1515,13 @@ void reporting_stream::_process_dimension_bv( _dimension_bv_insert.bind_value_as_i32(0, dbv.bv_id); _dimension_bv_insert.bind_value_as_str( 1, misc::string::truncate( - dbv.bv_name, - get_mod_bam_reporting_bv_col_size(mod_bam_reporting_bv_bv_name))); + dbv.bv_name, get_centreon_storage_mod_bam_reporting_bv_col_size( + centreon_storage_mod_bam_reporting_bv_bv_name))); _dimension_bv_insert.bind_value_as_str( - 2, misc::string::truncate(dbv.bv_description, - get_mod_bam_reporting_bv_col_size( - mod_bam_reporting_bv_bv_description))); + 2, misc::string::truncate( + dbv.bv_description, + get_centreon_storage_mod_bam_reporting_bv_col_size( + centreon_storage_mod_bam_reporting_bv_bv_description))); _mysql.run_statement(_dimension_bv_insert, database::mysql_error::insert_bv); } @@ -1511,13 +1540,15 @@ void reporting_stream::_process_pb_dimension_bv( _dimension_bv_insert.bind_value_as_i32(0, dbv.bv_id()); _dimension_bv_insert.bind_value_as_str( - 1, misc::string::truncate( - dbv.bv_name(), - get_mod_bam_reporting_bv_col_size(mod_bam_reporting_bv_bv_name))); + 1, + misc::string::truncate( + dbv.bv_name(), get_centreon_storage_mod_bam_reporting_bv_col_size( + centreon_storage_mod_bam_reporting_bv_bv_name))); _dimension_bv_insert.bind_value_as_str( - 2, misc::string::truncate(dbv.bv_description(), - get_mod_bam_reporting_bv_col_size( - mod_bam_reporting_bv_bv_description))); + 2, misc::string::truncate( + dbv.bv_description(), + get_centreon_storage_mod_bam_reporting_bv_col_size( + centreon_storage_mod_bam_reporting_bv_bv_description))); _mysql.run_statement(_dimension_bv_insert, database::mysql_error::insert_bv); } @@ -1865,37 +1896,45 @@ void reporting_stream::_process_pb_dimension_timeperiod( tp.id(), tp.name()); _dimension_timeperiod_insert.bind_value_as_i32(0, tp.id()); _dimension_timeperiod_insert.bind_value_as_str( - 1, misc::string::truncate(tp.name(), - get_mod_bam_reporting_timeperiods_col_size( - mod_bam_reporting_timeperiods_name))); + 1, misc::string::truncate( + tp.name(), + get_centreon_storage_mod_bam_reporting_timeperiods_col_size( + centreon_storage_mod_bam_reporting_timeperiods_name))); _dimension_timeperiod_insert.bind_value_as_str( - 2, misc::string::truncate(tp.sunday(), - get_mod_bam_reporting_timeperiods_col_size( - mod_bam_reporting_timeperiods_sunday))); + 2, misc::string::truncate( + tp.sunday(), + get_centreon_storage_mod_bam_reporting_timeperiods_col_size( + centreon_storage_mod_bam_reporting_timeperiods_sunday))); _dimension_timeperiod_insert.bind_value_as_str( - 3, misc::string::truncate(tp.monday(), - get_mod_bam_reporting_timeperiods_col_size( - mod_bam_reporting_timeperiods_monday))); + 3, misc::string::truncate( + tp.monday(), + get_centreon_storage_mod_bam_reporting_timeperiods_col_size( + centreon_storage_mod_bam_reporting_timeperiods_monday))); _dimension_timeperiod_insert.bind_value_as_str( - 4, misc::string::truncate(tp.tuesday(), - get_mod_bam_reporting_timeperiods_col_size( - mod_bam_reporting_timeperiods_tuesday))); + 4, misc::string::truncate( + tp.tuesday(), + get_centreon_storage_mod_bam_reporting_timeperiods_col_size( + centreon_storage_mod_bam_reporting_timeperiods_tuesday))); _dimension_timeperiod_insert.bind_value_as_str( - 5, misc::string::truncate(tp.wednesday(), - get_mod_bam_reporting_timeperiods_col_size( - mod_bam_reporting_timeperiods_wednesday))); + 5, misc::string::truncate( + tp.wednesday(), + get_centreon_storage_mod_bam_reporting_timeperiods_col_size( + centreon_storage_mod_bam_reporting_timeperiods_wednesday))); _dimension_timeperiod_insert.bind_value_as_str( - 6, misc::string::truncate(tp.thursday(), - get_mod_bam_reporting_timeperiods_col_size( - mod_bam_reporting_timeperiods_thursday))); + 6, misc::string::truncate( + tp.thursday(), + get_centreon_storage_mod_bam_reporting_timeperiods_col_size( + centreon_storage_mod_bam_reporting_timeperiods_thursday))); _dimension_timeperiod_insert.bind_value_as_str( - 7, misc::string::truncate(tp.friday(), - get_mod_bam_reporting_timeperiods_col_size( - mod_bam_reporting_timeperiods_friday))); + 7, misc::string::truncate( + tp.friday(), + get_centreon_storage_mod_bam_reporting_timeperiods_col_size( + centreon_storage_mod_bam_reporting_timeperiods_friday))); _dimension_timeperiod_insert.bind_value_as_str( - 8, misc::string::truncate(tp.saturday(), - get_mod_bam_reporting_timeperiods_col_size( - mod_bam_reporting_timeperiods_saturday))); + 8, misc::string::truncate( + tp.saturday(), + get_centreon_storage_mod_bam_reporting_timeperiods_col_size( + centreon_storage_mod_bam_reporting_timeperiods_saturday))); _mysql.run_statement(_dimension_timeperiod_insert, database::mysql_error::insert_timeperiod); @@ -1918,37 +1957,45 @@ void reporting_stream::_process_dimension_timeperiod( _dimension_timeperiod_insert.bind_value_as_i32(0, tp.id); _dimension_timeperiod_insert.bind_value_as_str( - 1, misc::string::truncate(tp.name, - get_mod_bam_reporting_timeperiods_col_size( - mod_bam_reporting_timeperiods_name))); + 1, + misc::string::truncate( + tp.name, get_centreon_storage_mod_bam_reporting_timeperiods_col_size( + centreon_storage_mod_bam_reporting_timeperiods_name))); _dimension_timeperiod_insert.bind_value_as_str( - 2, misc::string::truncate(tp.sunday, - get_mod_bam_reporting_timeperiods_col_size( - mod_bam_reporting_timeperiods_sunday))); + 2, misc::string::truncate( + tp.sunday, + get_centreon_storage_mod_bam_reporting_timeperiods_col_size( + centreon_storage_mod_bam_reporting_timeperiods_sunday))); _dimension_timeperiod_insert.bind_value_as_str( - 3, misc::string::truncate(tp.monday, - get_mod_bam_reporting_timeperiods_col_size( - mod_bam_reporting_timeperiods_monday))); + 3, misc::string::truncate( + tp.monday, + get_centreon_storage_mod_bam_reporting_timeperiods_col_size( + centreon_storage_mod_bam_reporting_timeperiods_monday))); _dimension_timeperiod_insert.bind_value_as_str( - 4, misc::string::truncate(tp.tuesday, - get_mod_bam_reporting_timeperiods_col_size( - mod_bam_reporting_timeperiods_tuesday))); + 4, misc::string::truncate( + tp.tuesday, + get_centreon_storage_mod_bam_reporting_timeperiods_col_size( + centreon_storage_mod_bam_reporting_timeperiods_tuesday))); _dimension_timeperiod_insert.bind_value_as_str( - 5, misc::string::truncate(tp.wednesday, - get_mod_bam_reporting_timeperiods_col_size( - mod_bam_reporting_timeperiods_wednesday))); + 5, misc::string::truncate( + tp.wednesday, + get_centreon_storage_mod_bam_reporting_timeperiods_col_size( + centreon_storage_mod_bam_reporting_timeperiods_wednesday))); _dimension_timeperiod_insert.bind_value_as_str( - 6, misc::string::truncate(tp.thursday, - get_mod_bam_reporting_timeperiods_col_size( - mod_bam_reporting_timeperiods_thursday))); + 6, misc::string::truncate( + tp.thursday, + get_centreon_storage_mod_bam_reporting_timeperiods_col_size( + centreon_storage_mod_bam_reporting_timeperiods_thursday))); _dimension_timeperiod_insert.bind_value_as_str( - 7, misc::string::truncate(tp.friday, - get_mod_bam_reporting_timeperiods_col_size( - mod_bam_reporting_timeperiods_friday))); + 7, misc::string::truncate( + tp.friday, + get_centreon_storage_mod_bam_reporting_timeperiods_col_size( + centreon_storage_mod_bam_reporting_timeperiods_friday))); _dimension_timeperiod_insert.bind_value_as_str( - 8, misc::string::truncate(tp.saturday, - get_mod_bam_reporting_timeperiods_col_size( - mod_bam_reporting_timeperiods_saturday))); + 8, misc::string::truncate( + tp.saturday, + get_centreon_storage_mod_bam_reporting_timeperiods_col_size( + centreon_storage_mod_bam_reporting_timeperiods_saturday))); _mysql.run_statement(_dimension_timeperiod_insert, database::mysql_error::insert_timeperiod); DimensionTimeperiod convert; diff --git a/broker/core/inc/com/centreon/broker/misc/perfdata.hh b/broker/core/inc/com/centreon/broker/misc/perfdata.hh index 81ee30bb138..d9e87986a67 100644 --- a/broker/core/inc/com/centreon/broker/misc/perfdata.hh +++ b/broker/core/inc/com/centreon/broker/misc/perfdata.hh @@ -31,50 +31,50 @@ class perfdata { enum data_type { gauge = 0, counter, derive, absolute, automatic }; private: - double _critical; - double _critical_low; + float _critical; + float _critical_low; bool _critical_mode; - double _max; - double _min; + float _max; + float _min; std::string _name; std::string _unit; - double _value; + float _value; int16_t _value_type; - double _warning; - double _warning_low; + float _warning; + float _warning_low; bool _warning_mode; public: perfdata(); perfdata(const perfdata&) = default; perfdata(perfdata&&) = default; - ~perfdata() noexcept; + ~perfdata() noexcept = default; perfdata& operator=(perfdata const& pd); perfdata& operator=(perfdata&& pd); - double critical() const noexcept; - void critical(double c) noexcept; - double critical_low() const noexcept; - void critical_low(double c) noexcept; + float critical() const noexcept; + void critical(float c) noexcept; + float critical_low() const noexcept; + void critical_low(float c) noexcept; bool critical_mode() const noexcept; void critical_mode(bool m) noexcept; - double max() const noexcept; - void max(double m) noexcept; - double min() const noexcept; - void min(double m) noexcept; + float max() const noexcept; + void max(float m) noexcept; + float min() const noexcept; + void min(float m) noexcept; std::string const& name() const noexcept; void name(std::string const& n); void name(std::string&& n); std::string const& unit() const noexcept; void unit(std::string const& u); void unit(std::string&& u); - double value() const noexcept; - void value(double v) noexcept; + float value() const noexcept; + void value(float v) noexcept; int16_t value_type() const noexcept; void value_type(int16_t t) noexcept; - double warning() const noexcept; - void warning(double w) noexcept; - double warning_low() const noexcept; - void warning_low(double w) noexcept; + float warning() const noexcept; + void warning(float w) noexcept; + float warning_low() const noexcept; + void warning_low(float w) noexcept; bool warning_mode() const noexcept; void warning_mode(bool m) noexcept; }; @@ -85,7 +85,9 @@ class perfdata { * @return Metric value. */ // Inlined after profiling for performance. -inline double perfdata::value() const noexcept { return _value; } +inline float perfdata::value() const noexcept { + return _value; +} } // namespace com::centreon::broker::misc bool operator==(com::centreon::broker::misc::perfdata const& left, diff --git a/broker/core/sql/src/table_max_size.py b/broker/core/sql/src/table_max_size.py index f2eb56b8714..c7003355f1a 100644 --- a/broker/core/sql/src/table_max_size.py +++ b/broker/core/sql/src/table_max_size.py @@ -19,11 +19,14 @@ import sys import re +from datetime import datetime +import os dico = {} pattern_ct = re.compile( 'CREATE TABLE( IF NOT EXISTS)? (centreon_storage\.)?`?([^`]*)`? \(') column_ct = re.compile('\s*`?([^`]*)`? (varchar\(([0-9]*)\)|text)') +column_ct_nb = re.compile('\s*`?([^`]*)`? (float|double)') end_ct = re.compile('^\)') debug = False @@ -37,6 +40,7 @@ def print_dbg(s): header_file = sys.argv[1] for sql_file in sys.argv[2:]: with open(sql_file, encoding='utf-8') as fp: + database = os.path.basename(sql_file).split('.')[0] line = fp.readline() in_block = False @@ -45,7 +49,7 @@ def print_dbg(s): m = pattern_ct.match(line) if m: print_dbg("New table {}".format(m.group(3))) - current_table = m.group(3) + current_table = f"{database}_{m.group(3)}" in_block = True else: if end_ct.match(line): @@ -57,13 +61,19 @@ def print_dbg(s): print_dbg("New text column {} of size {}".format( m.group(1), m.group(3))) dico.setdefault(current_table, []).append( - (m.group(1), m.group(3))) + (m.group(1), 'TEXT', m.group(3))) else: print_dbg("New text column {} of 65534".format( m.group(1), m.group(2))) dico.setdefault(current_table, []).append( - (m.group(1), 65534)) - + (m.group(1), 'TEXT', 65534)) + else: + m = column_ct_nb.match(line) + if m: + print_dbg(f"New number column {m.group(1)} of type {m.group(2)}") + dico.setdefault(current_table, []).append( + (m.group(1), 'NUMBER', m.group(2))) + line = fp.readline() fp.close() @@ -72,47 +82,69 @@ def print_dbg(s): for t, content in dico.items(): cols += "enum {}_cols {{\n".format(t) - sizes = "constexpr static uint32_t {}_size[] {{\n".format(t) + sizes = "constexpr static pair_type_size {}_size[] {{\n".format(t) for c in content: - cols += " {}_{},\n".format(t, c[0]) - sizes += " {},\n".format(c[1]) + cols += f" {t}_{c[0]},\n" + if c[1] == 'TEXT': + sizes += f" {{{c[1]}, {c[2]}}}, // {c[0]}\n" + else: + if c[2] == 'double': + s = 8 + else: + s = 4 + sizes += f" {{{c[1]}, {s}}}, // {c[0]}\n" cols += "};\n" sizes += "};\n" cols += sizes - cols += """constexpr uint32_t get_{}_col_size( - {}_cols const& col) {{ - return {}_size[col]; + cols += f"""constexpr uint32_t get_{t}_col_size( + {t}_cols const& col) {{ + return {t}_size[col].size; +}} + +constexpr col_type get_{t}_col_type( + {t}_cols const& col) {{ + return {t}_size[col].type; }} -""".format(t, t, t) +""" with open(header_file, 'w', encoding="utf-8") as fp: - fp.write("""/* -** Copyright 2020 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ + year = datetime.now().year + fp.write(f"""/** + * Copyright 2020-{year} Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef __TABLE_MAX_SIZE_HH__ #define __TABLE_MAX_SIZE_HH__ -namespace com::centreon::broker { +namespace com::centreon::broker {{ + +enum col_type {{ + TEXT, + NUMBER +}}; + +struct pair_type_size {{ + col_type type; + uint32_t size; +}}; """) - # fp.write(enum) fp.write(cols) fp.write("\n\n}\n\n#endif /* __TABLE_MAX_SIZE_HH__ */") diff --git a/broker/core/src/misc/parse_perfdata.cc b/broker/core/src/misc/parse_perfdata.cc index 0dd459170bc..5ea51f8c4e6 100644 --- a/broker/core/src/misc/parse_perfdata.cc +++ b/broker/core/src/misc/parse_perfdata.cc @@ -39,8 +39,8 @@ using log_v2 = com::centreon::common::log_v2::log_v2; * * @return Extracted real value if successful, NaN otherwise. */ -static inline double extract_double(char const** str, bool skip = true) { - double retval; +static inline float extract_float(char const** str, bool skip = true) { + float retval; char* tmp; if (isspace(**str)) retval = NAN; @@ -52,13 +52,13 @@ static inline double extract_double(char const** str, bool skip = true) { size_t t = strcspn(comma, " \t\n\r;"); char* nb = strndup(*str, (comma - *str) + t); nb[comma - *str] = '.'; - retval = strtod(nb, &tmp); + retval = strtof(nb, &tmp); if (nb == tmp) retval = NAN; *str = *str + (tmp - nb); free(nb); } else { - retval = strtod(*str, &tmp); + retval = strtof(*str, &tmp); if (*str == tmp) retval = NAN; *str = tmp; @@ -78,8 +78,8 @@ static inline double extract_double(char const** str, bool skip = true) { * otherwise. * @param[in,out] str Pointer to a perfdata string. */ -static inline void extract_range(double* low, - double* high, +static inline void extract_range(float* low, + float* high, bool* inclusive, char const** str) { // Exclusive range ? @@ -90,15 +90,15 @@ static inline void extract_range(double* low, *inclusive = false; // Low threshold value. - double low_value; + float low_value; if ('~' == **str) { - low_value = -std::numeric_limits::infinity(); + low_value = -std::numeric_limits::infinity(); ++*str; } else - low_value = extract_double(str); + low_value = extract_float(str); // High threshold value. - double high_value; + float high_value; if (**str != ':') { high_value = low_value; if (!std::isnan(low_value)) @@ -106,9 +106,9 @@ static inline void extract_range(double* low, } else { ++*str; char const* ptr(*str); - high_value = extract_double(str); + high_value = extract_float(str); if (std::isnan(high_value) && ((*str == ptr) || (*str == (ptr + 1)))) - high_value = std::numeric_limits::infinity(); + high_value = std::numeric_limits::infinity(); } // Set values. @@ -208,7 +208,8 @@ std::list misc::parse_perfdata( if (end - s + 1 > 0) { std::string name(s, end - s + 1); name.resize(misc::string::adjust_size_utf8( - name, get_metrics_col_size(metrics_metric_name))); + name, get_centreon_storage_metrics_col_size( + centreon_storage_metrics_metric_name))); p.name(std::move(name)); } else { logger->error("In service {}, metric name empty before '{}...'", id(), @@ -235,7 +236,7 @@ std::list misc::parse_perfdata( } // Extract value. - p.value(extract_double(const_cast(&tmp), false)); + p.value(extract_float(const_cast(&tmp), false)); if (std::isnan(p.value())) { int i; for (i = 0; i < 10 && tmp[i]; i++) @@ -255,7 +256,8 @@ std::list misc::parse_perfdata( { std::string unit(tmp, t); unit.resize(misc::string::adjust_size_utf8( - unit, get_metrics_col_size(metrics_unit_name))); + unit, get_centreon_storage_metrics_col_size( + centreon_storage_metrics_unit_name))); p.unit(std::move(unit)); } tmp += t; @@ -264,8 +266,8 @@ std::list misc::parse_perfdata( // Extract warning. { - double warning_high; - double warning_low; + float warning_high; + float warning_low; bool warning_mode; extract_range(&warning_low, &warning_high, &warning_mode, const_cast(&tmp)); @@ -276,8 +278,8 @@ std::list misc::parse_perfdata( // Extract critical. { - double critical_high; - double critical_low; + float critical_high; + float critical_low; bool critical_mode; extract_range(&critical_low, &critical_high, &critical_mode, const_cast(&tmp)); @@ -287,10 +289,10 @@ std::list misc::parse_perfdata( } // Extract minimum. - p.min(extract_double(const_cast(&tmp))); + p.min(extract_float(const_cast(&tmp))); // Extract maximum. - p.max(extract_double(const_cast(&tmp))); + p.max(extract_float(const_cast(&tmp))); // Log new perfdata. logger->debug( diff --git a/broker/core/src/misc/perfdata.cc b/broker/core/src/misc/perfdata.cc index 501c59ba71e..b21d1f66764 100644 --- a/broker/core/src/misc/perfdata.cc +++ b/broker/core/src/misc/perfdata.cc @@ -1,20 +1,20 @@ /** -* Copyright 2011-2013 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2011-2013 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/misc/perfdata.hh" @@ -37,11 +37,6 @@ perfdata::perfdata() _warning_low(NAN), _warning_mode(false) {} -/** - * Destructor. - */ -perfdata::~perfdata() noexcept {} - /** * Move operator. * @@ -97,7 +92,7 @@ perfdata& perfdata::operator=(perfdata const& other) { * * @return Critical value. */ -double perfdata::critical() const noexcept { +float perfdata::critical() const noexcept { return _critical; } @@ -106,7 +101,7 @@ double perfdata::critical() const noexcept { * * @param[in] c New critical value. */ -void perfdata::critical(double c) noexcept { +void perfdata::critical(float c) noexcept { _critical = c; } @@ -115,7 +110,7 @@ void perfdata::critical(double c) noexcept { * * @return Low critical value. */ -double perfdata::critical_low() const noexcept { +float perfdata::critical_low() const noexcept { return _critical_low; } @@ -124,7 +119,7 @@ double perfdata::critical_low() const noexcept { * * @param[in] c Low critical value. */ -void perfdata::critical_low(double c) noexcept { +void perfdata::critical_low(float c) noexcept { _critical_low = c; } @@ -153,7 +148,7 @@ void perfdata::critical_mode(bool m) noexcept { * * @return Maximum value. */ -double perfdata::max() const noexcept { +float perfdata::max() const noexcept { return _max; } @@ -162,7 +157,7 @@ double perfdata::max() const noexcept { * * @param[in] m New maximum value. */ -void perfdata::max(double m) noexcept { +void perfdata::max(float m) noexcept { _max = m; } @@ -171,7 +166,7 @@ void perfdata::max(double m) noexcept { * * @return Minimum value. */ -double perfdata::min() const noexcept { +float perfdata::min() const noexcept { return _min; } @@ -180,7 +175,7 @@ double perfdata::min() const noexcept { * * @param[in] m New minimum value. */ -void perfdata::min(double m) noexcept { +void perfdata::min(float m) noexcept { _min = m; } @@ -233,7 +228,7 @@ void perfdata::unit(std::string&& u) { * * @param[in] v New value. */ -void perfdata::value(double v) noexcept { +void perfdata::value(float v) noexcept { _value = v; } @@ -260,7 +255,7 @@ void perfdata::value_type(int16_t t) noexcept { * * @return Warning value. */ -double perfdata::warning() const noexcept { +float perfdata::warning() const noexcept { return _warning; } @@ -269,7 +264,7 @@ double perfdata::warning() const noexcept { * * @param[in] v New warning value. */ -void perfdata::warning(double w) noexcept { +void perfdata::warning(float w) noexcept { _warning = w; } @@ -278,7 +273,7 @@ void perfdata::warning(double w) noexcept { * * @return Low warning value. */ -double perfdata::warning_low() const noexcept { +float perfdata::warning_low() const noexcept { return _warning_low; } @@ -287,7 +282,7 @@ double perfdata::warning_low() const noexcept { * * @param[in] w Low warning value. */ -void perfdata::warning_low(double w) noexcept { +void perfdata::warning_low(float w) noexcept { _warning_low = w; } @@ -325,7 +320,7 @@ void perfdata::warning_mode(bool m) noexcept { * * @return true if a and b are equal. */ -static inline bool double_equal(double a, double b) { +static inline bool float_equal(float a, float b) { return (std::isnan(a) && std::isnan(b)) || (std::isinf(a) && std::isinf(b) && std::signbit(a) == std::signbit(b)) || @@ -342,16 +337,16 @@ static inline bool double_equal(double a, double b) { * @return true if both objects are equal. */ bool operator==(perfdata const& left, perfdata const& right) { - return double_equal(left.critical(), right.critical()) && - double_equal(left.critical_low(), right.critical_low()) && + return float_equal(left.critical(), right.critical()) && + float_equal(left.critical_low(), right.critical_low()) && left.critical_mode() == right.critical_mode() && - double_equal(left.max(), right.max()) && - double_equal(left.min(), right.min()) && left.name() == right.name() && + float_equal(left.max(), right.max()) && + float_equal(left.min(), right.min()) && left.name() == right.name() && left.unit() == right.unit() && - double_equal(left.value(), right.value()) && + float_equal(left.value(), right.value()) && left.value_type() == right.value_type() && - double_equal(left.warning(), right.warning()) && - double_equal(left.warning_low(), right.warning_low()) && + float_equal(left.warning(), right.warning()) && + float_equal(left.warning_low(), right.warning_low()) && left.warning_mode() == right.warning_mode(); } diff --git a/broker/core/test/misc/perfdata.cc b/broker/core/test/misc/perfdata.cc index bd0169043c9..be3f6071038 100644 --- a/broker/core/test/misc/perfdata.cc +++ b/broker/core/test/misc/perfdata.cc @@ -81,29 +81,29 @@ TEST(MiscPerfdata, Assign) { p1.warning_mode(false); // Check objects properties values. - ASSERT_FALSE(fabs(p1.critical() - 9432.5) > 0.00001); - ASSERT_FALSE(fabs(p1.critical_low() - 1000.0001) > 0.00001); + ASSERT_FALSE(fabs(p1.critical() - 9432.5f) > 0.00001f); + ASSERT_TRUE(fabs(p1.critical_low() - 1000.0001f) < 0.0001f); ASSERT_FALSE(!p1.critical_mode()); - ASSERT_FALSE(fabs(p1.max() - 123.0) > 0.00001); - ASSERT_FALSE(fabs(p1.min() - 843.876) > 0.00001); + ASSERT_FALSE(fabs(p1.max() - 123.0f) > 0.00001f); + ASSERT_TRUE(fabs(p1.min() - 843.876f) < 0.0001f); ASSERT_FALSE(p1.name() != "baz"); ASSERT_FALSE(p1.unit() != "qux"); - ASSERT_FALSE(fabs(p1.value() - 3485.9) > 0.00001); + ASSERT_TRUE(fabs(p1.value() - 3485.9f) < 0.0001f); ASSERT_FALSE(p1.value_type() != misc::perfdata::derive); - ASSERT_FALSE(fabs(p1.warning() - 3612.0) > 0.00001); - ASSERT_FALSE(fabs(p1.warning_low() + 987579.0) > 0.01); + ASSERT_FALSE(fabs(p1.warning() - 3612.0f) > 0.00001f); + ASSERT_FALSE(fabs(p1.warning_low() + 987579.0f) > 0.01f); ASSERT_FALSE(p1.warning_mode()); - ASSERT_FALSE(fabs(p2.critical() - 42.0) > 0.00001); - ASSERT_FALSE(fabs(p2.critical_low() + 456.032) > 0.00001); + ASSERT_FALSE(fabs(p2.critical() - 42.0f) > 0.00001f); + ASSERT_FALSE(fabs(p2.critical_low() + 456.032f) > 0.00001f); ASSERT_FALSE(p2.critical_mode()); - ASSERT_FALSE(fabs(p2.max() - 76.3) > 0.00001); - ASSERT_FALSE(fabs(p2.min() - 567.2) > 0.00001); + ASSERT_FALSE(fabs(p2.max() - 76.3f) > 0.00001f); + ASSERT_FALSE(fabs(p2.min() - 567.2f) > 0.00001f); ASSERT_FALSE(p2.name() != "foo"); ASSERT_FALSE(p2.unit() != "bar"); - ASSERT_FALSE(fabs(p2.value() - 52189.912) > 0.00001); + ASSERT_FALSE(fabs(p2.value() - 52189.912f) > 0.00001f); ASSERT_FALSE(p2.value_type() != misc::perfdata::counter); - ASSERT_FALSE(fabs(p2.warning() - 4548.0) > 0.00001); - ASSERT_FALSE(fabs(p2.warning_low() - 42.42) > 0.00001); + ASSERT_FALSE(fabs(p2.warning() - 4548.0f) > 0.00001f); + ASSERT_FALSE(fabs(p2.warning_low() - 42.42f) > 0.00001f); ASSERT_FALSE(!p2.warning_mode()); } @@ -144,29 +144,29 @@ TEST(MiscPerfdata, CopyCtor) { p1.warning_mode(false); // Check objects properties values. - ASSERT_FALSE(fabs(p1.critical() - 9432.5) > 0.00001); - ASSERT_FALSE(fabs(p1.critical_low() - 1000.0001) > 0.00001); + ASSERT_FALSE(fabs(p1.critical() - 9432.5f) > 0.00001f); + ASSERT_FALSE(fabs(p1.critical_low() - 1000.0001f) > 0.00001f); ASSERT_FALSE(!p1.critical_mode()); - ASSERT_FALSE(fabs(p1.max() - 123.0) > 0.00001); - ASSERT_FALSE(fabs(p1.min() - 843.876) > 0.00001); + ASSERT_FALSE(fabs(p1.max() - 123.0f) > 0.00001f); + ASSERT_FALSE(fabs(p1.min() - 843.876f) > 0.00001f); ASSERT_FALSE(p1.name() != "baz"); ASSERT_FALSE(p1.unit() != "qux"); - ASSERT_FALSE(fabs(p1.value() - 3485.9) > 0.00001); + ASSERT_FALSE(fabs(p1.value() - 3485.9f) > 0.00001f); ASSERT_FALSE(p1.value_type() != misc::perfdata::derive); - ASSERT_FALSE(fabs(p1.warning() - 3612.0) > 0.00001); - ASSERT_FALSE(fabs(p1.warning_low() + 987579.0) > 0.01); + ASSERT_FALSE(fabs(p1.warning() - 3612.0f) > 0.00001f); + ASSERT_FALSE(fabs(p1.warning_low() + 987579.0f) > 0.01f); ASSERT_FALSE(p1.warning_mode()); - ASSERT_FALSE(fabs(p2.critical() - 42.0) > 0.00001); - ASSERT_FALSE(fabs(p2.critical_low() + 456.032) > 0.00001); + ASSERT_FALSE(fabs(p2.critical() - 42.0f) > 0.00001f); + ASSERT_FALSE(fabs(p2.critical_low() + 456.032f) > 0.00001f); ASSERT_FALSE(p2.critical_mode()); - ASSERT_FALSE(fabs(p2.max() - 76.3) > 0.00001); - ASSERT_FALSE(fabs(p2.min() - 567.2) > 0.00001); + ASSERT_FALSE(fabs(p2.max() - 76.3f) > 0.00001f); + ASSERT_FALSE(fabs(p2.min() - 567.2f) > 0.00001f); ASSERT_FALSE(p2.name() != "foo"); ASSERT_FALSE(p2.unit() != "bar"); - ASSERT_FALSE(fabs(p2.value() - 52189.912) > 0.00001); + ASSERT_FALSE(fabs(p2.value() - 52189.912f) > 0.00001f); ASSERT_FALSE(p2.value_type() != misc::perfdata::counter); - ASSERT_FALSE(fabs(p2.warning() - 4548.0) > 0.00001); - ASSERT_FALSE(fabs(p2.warning_low() - 42.42) > 0.00001); + ASSERT_FALSE(fabs(p2.warning() - 4548.0f) > 0.00001f); + ASSERT_FALSE(fabs(p2.warning_low() - 42.42f) > 0.00001f); ASSERT_FALSE(!p2.warning_mode()); } diff --git a/broker/grpc/test/acceptor.cc b/broker/grpc/test/acceptor.cc index 52d1faf06db..34892211d43 100644 --- a/broker/grpc/test/acceptor.cc +++ b/broker/grpc/test/acceptor.cc @@ -51,6 +51,8 @@ static auto read_file = [](const std::string& path) { TEST_F(GrpcTlsTest, TlsStream) { /* Let's prepare certificates */ std::string hostname = misc::exec("hostname --fqdn"); + if (hostname.empty()) + hostname = "localhost"; hostname = misc::string::trim(hostname); if (hostname.empty()) hostname = "localhost"; diff --git a/broker/lua/test/lua.cc b/broker/lua/test/lua.cc index 1be48705879..d002cf5956d 100644 --- a/broker/lua/test/lua.cc +++ b/broker/lua/test/lua.cc @@ -1941,7 +1941,7 @@ TEST_F(LuaTest, ParsePerfdata2) { size_t pos10 = lst.find("\"critical_high\":nan", pos1 + 1); size_t pos11 = lst.find("\"warning_high\":nan", pos1 + 1); size_t pos12 = lst.find("\"critical_low\":nan", pos1 + 1); - size_t pos13 = lst.find("\"value\":94.82", pos1 + 1); + size_t pos13 = lst.find("\"value\":94.8", pos1 + 1); size_t pos14 = lst.find("\"max\":100", pos1 + 1); size_t pos15 = lst.find( "\"metric_fields\":[\"azure\",\"insights\",\"logicaldisk\",\"free\"," @@ -2007,7 +2007,7 @@ TEST_F(LuaTest, ParsePerfdata3) { size_t pos10 = lst.find("\"critical_high\":nan", pos1 + 1); size_t pos11 = lst.find("\"warning_high\":nan", pos1 + 1); size_t pos12 = lst.find("\"critical_low\":nan", pos1 + 1); - size_t pos13 = lst.find("\"value\":94.82", pos1 + 1); + size_t pos13 = lst.find("\"value\":94.8", pos1 + 1); size_t pos14 = lst.find("\"max\":100", pos1 + 1); size_t pos15 = lst.find( "metric_fields\":[\"PingSDWanvdomifName\",\"azure\",\"insights\"," @@ -2072,7 +2072,7 @@ TEST_F(LuaTest, ParsePerfdata4) { size_t pos10 = lst.find("\"critical_high\":nan", pos1 + 1); size_t pos11 = lst.find("\"warning_high\":nan", pos1 + 1); size_t pos12 = lst.find("\"critical_low\":nan", pos1 + 1); - size_t pos13 = lst.find("\"value\":94.82", pos1 + 1); + size_t pos13 = lst.find("\"value\":94.8", pos1 + 1); size_t pos14 = lst.find("\"max\":100", pos1 + 1); size_t pos15 = lst.find( "\"metric_fields\":[\"azure\",\"insights#logicaldisk~free\"," diff --git a/broker/neb/src/acknowledgement.cc b/broker/neb/src/acknowledgement.cc index 049699f1b3c..92f42b14bca 100644 --- a/broker/neb/src/acknowledgement.cc +++ b/broker/neb/src/acknowledgement.cc @@ -1,20 +1,20 @@ /** -* Copyright 2009-2013 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2009-2013 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/neb/acknowledgement.hh" @@ -122,11 +122,12 @@ mapping::entry const acknowledgement::entries[] = { mapping::entry(&acknowledgement::acknowledgement_type, "type"), mapping::entry(&acknowledgement::author, "author", - get_acknowledgements_col_size(acknowledgements_author)), - mapping::entry( - &acknowledgement::comment, - "comment_data", - get_acknowledgements_col_size(acknowledgements_comment_data)), + get_centreon_storage_acknowledgements_col_size( + centreon_storage_acknowledgements_author)), + mapping::entry(&acknowledgement::comment, + "comment_data", + get_centreon_storage_acknowledgements_col_size( + centreon_storage_acknowledgements_comment_data)), mapping::entry(&acknowledgement::deletion_time, "deletion_time", mapping::entry::invalid_on_minus_one), diff --git a/broker/neb/src/comment.cc b/broker/neb/src/comment.cc index 982eb0bdafc..c95958b6e4c 100644 --- a/broker/neb/src/comment.cc +++ b/broker/neb/src/comment.cc @@ -1,20 +1,20 @@ /** -* Copyright 2009-2013,2015,2019-2020 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2009-2013,2015,2019-2020 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/neb/comment.hh" @@ -123,11 +123,13 @@ void comment::_internal_copy(comment const& other) { mapping::entry const comment::entries[] = { mapping::entry(&comment::author, "author", - get_comments_col_size(comments_author)), + get_centreon_storage_comments_col_size( + centreon_storage_comments_author)), mapping::entry(&comment::comment_type, "type"), - mapping::entry(&comment::data, - "data", - get_comments_col_size(comments_data)), + mapping::entry( + &comment::data, + "data", + get_centreon_storage_comments_col_size(centreon_storage_comments_data)), mapping::entry(&comment::deletion_time, "deletion_time", mapping::entry::invalid_on_zero), diff --git a/broker/neb/src/custom_variable.cc b/broker/neb/src/custom_variable.cc index c66a7a00e48..6ec0cda5552 100644 --- a/broker/neb/src/custom_variable.cc +++ b/broker/neb/src/custom_variable.cc @@ -1,20 +1,20 @@ /** -* Copyright 2009-2015 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2009-2015 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/neb/custom_variable.hh" @@ -95,7 +95,8 @@ mapping::entry const custom_variable::entries[] = { mapping::entry(&custom_variable::modified, "modified"), mapping::entry(&custom_variable::name, "name", - get_customvariables_col_size(customvariables_name)), + get_centreon_storage_customvariables_col_size( + centreon_storage_customvariables_name)), mapping::entry(&custom_variable::service_id, "service_id", mapping::entry::invalid_on_zero), @@ -105,10 +106,12 @@ mapping::entry const custom_variable::entries[] = { mapping::entry(&custom_variable::var_type, "type"), mapping::entry(&custom_variable::value, "value", - get_customvariables_col_size(customvariables_value)), + get_centreon_storage_customvariables_col_size( + centreon_storage_customvariables_value)), mapping::entry(&custom_variable::default_value, "default_value", - get_customvariables_col_size(customvariables_default_value)), + get_centreon_storage_customvariables_col_size( + centreon_storage_customvariables_default_value)), mapping::entry()}; // Operations. diff --git a/broker/neb/src/custom_variable_status.cc b/broker/neb/src/custom_variable_status.cc index 7cefe8dcdaa..1a0c6feed09 100644 --- a/broker/neb/src/custom_variable_status.cc +++ b/broker/neb/src/custom_variable_status.cc @@ -1,20 +1,20 @@ /** -* Copyright 2009-2013 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2009-2013 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/neb/custom_variable_status.hh" @@ -100,7 +100,8 @@ mapping::entry const custom_variable_status::entries[] = { mapping::entry(&custom_variable_status::modified, "modified"), mapping::entry(&custom_variable_status::name, "name", - get_customvariables_col_size(customvariables_name)), + get_centreon_storage_customvariables_col_size( + centreon_storage_customvariables_name)), mapping::entry(&custom_variable_status::service_id, "service_id", mapping::entry::invalid_on_zero), @@ -109,7 +110,8 @@ mapping::entry const custom_variable_status::entries[] = { mapping::entry::invalid_on_minus_one), mapping::entry(&custom_variable_status::value, "value", - get_customvariables_col_size(customvariables_value)), + get_centreon_storage_customvariables_col_size( + centreon_storage_customvariables_value)), mapping::entry()}; // Operations. diff --git a/broker/neb/src/downtime.cc b/broker/neb/src/downtime.cc index 47950ce8bcb..66f523d5740 100644 --- a/broker/neb/src/downtime.cc +++ b/broker/neb/src/downtime.cc @@ -1,20 +1,20 @@ /** -* Copyright 2009-2013 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2009-2013 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/neb/downtime.hh" @@ -158,7 +158,8 @@ mapping::entry const downtime::entries[] = { mapping::entry::invalid_on_minus_one), mapping::entry(&downtime::author, "author", - get_downtimes_col_size(downtimes_author)), + get_centreon_storage_downtimes_col_size( + centreon_storage_downtimes_author)), mapping::entry(&downtime::downtime_type, "type"), mapping::entry(&downtime::deletion_time, "deletion_time", @@ -191,7 +192,8 @@ mapping::entry const downtime::entries[] = { mapping::entry(&downtime::was_started, "started"), mapping::entry(&downtime::comment, "comment_data", - get_downtimes_col_size(downtimes_comment_data)), + get_centreon_storage_downtimes_col_size( + centreon_storage_downtimes_comment_data)), mapping::entry(&downtime::come_from, ""), mapping::entry()}; diff --git a/broker/neb/src/host.cc b/broker/neb/src/host.cc index 9b7eb856121..9c283ae3670 100644 --- a/broker/neb/src/host.cc +++ b/broker/neb/src/host.cc @@ -1,20 +1,20 @@ /** -* Copyright 2009-2013,2015 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2009-2013,2015 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/neb/host.hh" @@ -139,20 +139,26 @@ void host::_zero_initialize() { mapping::entry const host::entries[] = { mapping::entry(&host::acknowledged, "acknowledged"), mapping::entry(&host::acknowledgement_type, "acknowledgement_type"), - mapping::entry(static_cast(&host::action_url), - "action_url", - get_hosts_col_size(hosts_action_url)), + mapping::entry( + static_cast(&host::action_url), + "action_url", + get_centreon_storage_hosts_col_size(centreon_storage_hosts_action_url)), mapping::entry(&host::active_checks_enabled, "active_checks"), - mapping::entry(&host::address, - "address", - get_hosts_col_size(hosts_address)), - mapping::entry(&host::alias, "alias", get_hosts_col_size(hosts_alias)), + mapping::entry( + &host::address, + "address", + get_centreon_storage_hosts_col_size(centreon_storage_hosts_address)), + mapping::entry( + &host::alias, + "alias", + get_centreon_storage_hosts_col_size(centreon_storage_hosts_alias)), mapping::entry(static_cast(&host::check_freshness), "check_freshness"), mapping::entry(&host::check_interval, "check_interval"), mapping::entry(&host::check_period, "check_period", - get_hosts_col_size(hosts_check_period)), + get_centreon_storage_hosts_col_size( + centreon_storage_hosts_check_period)), mapping::entry(&host::check_type, "check_type"), mapping::entry(&host::current_check_attempt, "check_attempt"), mapping::entry(&host::current_state, "state"), @@ -174,11 +180,13 @@ mapping::entry const host::entries[] = { mapping::entry(&host::downtime_depth, "scheduled_downtime_depth"), mapping::entry(static_cast(&host::display_name), "display_name", - get_hosts_col_size(hosts_display_name)), + get_centreon_storage_hosts_col_size( + centreon_storage_hosts_display_name)), mapping::entry(&host::enabled, "enabled"), mapping::entry(&host::event_handler, "event_handler", - get_hosts_col_size(hosts_event_handler)), + get_centreon_storage_hosts_col_size( + centreon_storage_hosts_event_handler)), mapping::entry(&host::event_handler_enabled, "event_handler_enabled"), mapping::entry(&host::execution_time, "execution_time"), mapping::entry( @@ -194,14 +202,19 @@ mapping::entry const host::entries[] = { mapping::entry(&host::has_been_checked, "checked"), mapping::entry(static_cast(&host::high_flap_threshold), "high_flap_threshold"), - mapping::entry(&host::host_name, "name", get_hosts_col_size(hosts_name)), + mapping::entry( + &host::host_name, + "name", + get_centreon_storage_hosts_col_size(centreon_storage_hosts_name)), mapping::entry(&host::host_id, "host_id", mapping::entry::invalid_on_zero), - mapping::entry(static_cast(&host::icon_image), - "icon_image", - get_hosts_col_size(hosts_icon_image)), + mapping::entry( + static_cast(&host::icon_image), + "icon_image", + get_centreon_storage_hosts_col_size(centreon_storage_hosts_icon_image)), mapping::entry(static_cast(&host::icon_image_alt), "icon_image_alt", - get_hosts_col_size(hosts_icon_image_alt)), + get_centreon_storage_hosts_col_size( + centreon_storage_hosts_icon_image_alt)), mapping::entry(&host::poller_id, "instance_id", mapping::entry::invalid_on_zero), @@ -242,12 +255,14 @@ mapping::entry const host::entries[] = { "next_host_notification", mapping::entry::invalid_on_zero), mapping::entry(&host::no_more_notifications, "no_more_notifications"), - mapping::entry(static_cast(&host::notes), - "notes", - get_hosts_col_size(hosts_notes)), - mapping::entry(static_cast(&host::notes_url), - "notes_url", - get_hosts_col_size(hosts_notes_url)), + mapping::entry( + static_cast(&host::notes), + "notes", + get_centreon_storage_hosts_col_size(centreon_storage_hosts_notes)), + mapping::entry( + static_cast(&host::notes_url), + "notes_url", + get_centreon_storage_hosts_col_size(centreon_storage_hosts_notes_url)), mapping::entry(static_cast(&host::notification_interval), "notification_interval"), mapping::entry(&host::notification_number, @@ -256,7 +271,8 @@ mapping::entry const host::entries[] = { mapping::entry( static_cast(&host::notification_period), "notification_period", - get_hosts_col_size(hosts_notification_period)), + get_centreon_storage_hosts_col_size( + centreon_storage_hosts_notification_period)), mapping::entry(&host::notifications_enabled, "notify"), mapping::entry(&host::notify_on_down, "notify_on_down"), mapping::entry(static_cast(&host::notify_on_downtime), @@ -276,23 +292,30 @@ mapping::entry const host::entries[] = { mapping::entry(&host::stalk_on_up, "stalk_on_up"), mapping::entry(&host::statusmap_image, "statusmap_image", - get_hosts_col_size(hosts_statusmap_image)), + get_centreon_storage_hosts_col_size( + centreon_storage_hosts_statusmap_image)), mapping::entry(&host::state_type, "state_type"), mapping::entry(&host::check_command, "check_command", - get_hosts_col_size(hosts_check_command)), - mapping::entry(&host::output, "output", get_hosts_col_size(hosts_output)), - mapping::entry(&host::perf_data, - "perfdata", - get_hosts_col_size(hosts_perfdata)), + get_centreon_storage_hosts_col_size( + centreon_storage_hosts_check_command)), + mapping::entry( + &host::output, + "output", + get_centreon_storage_hosts_col_size(centreon_storage_hosts_output)), + mapping::entry( + &host::perf_data, + "perfdata", + get_centreon_storage_hosts_col_size(centreon_storage_hosts_perfdata)), mapping::entry( static_cast(&host::retain_nonstatus_information), "retain_nonstatus_information"), mapping::entry(static_cast(&host::retain_status_information), "retain_status_information"), - mapping::entry(&host::timezone, - "timezone", - get_hosts_col_size(hosts_timezone)), + mapping::entry( + &host::timezone, + "timezone", + get_centreon_storage_hosts_col_size(centreon_storage_hosts_timezone)), mapping::entry()}; // Operations. diff --git a/broker/neb/src/host_check.cc b/broker/neb/src/host_check.cc index 71a71682808..e48ad7b56cd 100644 --- a/broker/neb/src/host_check.cc +++ b/broker/neb/src/host_check.cc @@ -1,20 +1,20 @@ /** -* Copyright 2009-2013 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2009-2013 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/neb/host_check.hh" @@ -68,7 +68,8 @@ mapping::entry const host_check::entries[] = { mapping::entry(&host_check::next_check, ""), mapping::entry(&host_check::command_line, "command_line", - get_hosts_col_size(hosts_command_line)), + get_centreon_storage_hosts_col_size( + centreon_storage_hosts_command_line)), mapping::entry()}; // Operations. diff --git a/broker/neb/src/host_dependency.cc b/broker/neb/src/host_dependency.cc index ee7eaaa7704..352c4e345ca 100644 --- a/broker/neb/src/host_dependency.cc +++ b/broker/neb/src/host_dependency.cc @@ -1,20 +1,20 @@ /** -* Copyright 2009-2013,2015 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2009-2013,2015 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/neb/host_dependency.hh" @@ -68,26 +68,29 @@ host_dependency& host_dependency::operator=(host_dependency const& other) { // Mapping. mapping::entry const host_dependency::entries[] = { - mapping::entry(&host_dependency::dependency_period, - "dependency_period", - get_hosts_hosts_dependencies_col_size( - hosts_hosts_dependencies_dependency_period)), + mapping::entry( + &host_dependency::dependency_period, + "dependency_period", + get_centreon_storage_hosts_hosts_dependencies_col_size( + centreon_storage_hosts_hosts_dependencies_dependency_period)), mapping::entry(&host_dependency::dependent_host_id, "dependent_host_id", mapping::entry::invalid_on_zero), mapping::entry(&host_dependency::enabled, ""), - mapping::entry(&host_dependency::execution_failure_options, - "execution_failure_options", - get_hosts_hosts_dependencies_col_size( - hosts_hosts_dependencies_execution_failure_options)), + mapping::entry( + &host_dependency::execution_failure_options, + "execution_failure_options", + get_centreon_storage_hosts_hosts_dependencies_col_size( + centreon_storage_hosts_hosts_dependencies_execution_failure_options)), mapping::entry(&host_dependency::inherits_parent, "inherits_parent"), mapping::entry(&host_dependency::host_id, "host_id", mapping::entry::invalid_on_zero), - mapping::entry(&host_dependency::notification_failure_options, - "notification_failure_options", - get_hosts_hosts_dependencies_col_size( - hosts_hosts_dependencies_notification_failure_options)), + mapping::entry( + &host_dependency::notification_failure_options, + "notification_failure_options", + get_centreon_storage_hosts_hosts_dependencies_col_size( + centreon_storage_hosts_hosts_dependencies_notification_failure_options)), mapping::entry()}; // Operations. diff --git a/broker/neb/src/host_group.cc b/broker/neb/src/host_group.cc index f70661becbe..41f8c6be955 100644 --- a/broker/neb/src/host_group.cc +++ b/broker/neb/src/host_group.cc @@ -1,20 +1,20 @@ /** -* Copyright 2009-2013,2015 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2009-2013,2015 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/neb/host_group.hh" @@ -71,7 +71,8 @@ mapping::entry const host_group::entries[] = { mapping::entry::invalid_on_zero), mapping::entry(&host_group::name, "name", - get_hostgroups_col_size(hostgroups_name)), + get_centreon_storage_hostgroups_col_size( + centreon_storage_hostgroups_name)), mapping::entry(&host_group::enabled, nullptr), mapping::entry(&host_group::poller_id, nullptr, diff --git a/broker/neb/src/host_status.cc b/broker/neb/src/host_status.cc index 1bc906da795..bb338cdf5c2 100644 --- a/broker/neb/src/host_status.cc +++ b/broker/neb/src/host_status.cc @@ -1,20 +1,20 @@ /** -* Copyright 2009-2013,2015 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2009-2013,2015 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/neb/host_status.hh" @@ -104,7 +104,8 @@ mapping::entry const host_status::entries[] = { mapping::entry(&host_status::check_interval, "check_interval"), mapping::entry(&host_status::check_period, "check_period", - get_hosts_col_size(hosts_check_period)), + get_centreon_storage_hosts_col_size( + centreon_storage_hosts_check_period)), mapping::entry(&host_status::check_type, "check_type"), mapping::entry(&host_status::current_check_attempt, "check_attempt"), mapping::entry(&host_status::current_state, "state"), @@ -112,7 +113,8 @@ mapping::entry const host_status::entries[] = { mapping::entry(&host_status::enabled, "enabled"), mapping::entry(&host_status::event_handler, "event_handler", - get_hosts_col_size(hosts_event_handler)), + get_centreon_storage_hosts_col_size( + centreon_storage_hosts_event_handler)), mapping::entry(&host_status::event_handler_enabled, "event_handler_enabled"), mapping::entry(&host_status::execution_time, "execution_time"), @@ -171,13 +173,16 @@ mapping::entry const host_status::entries[] = { mapping::entry(&host_status::state_type, "state_type"), mapping::entry(&host_status::check_command, "check_command", - get_hosts_col_size(hosts_check_command)), - mapping::entry(&host_status::output, - "output", - get_hosts_col_size(hosts_output)), - mapping::entry(&host_status::perf_data, - "perfdata", - get_hosts_col_size(hosts_perfdata)), + get_centreon_storage_hosts_col_size( + centreon_storage_hosts_check_command)), + mapping::entry( + &host_status::output, + "output", + get_centreon_storage_hosts_col_size(centreon_storage_hosts_output)), + mapping::entry( + &host_status::perf_data, + "perfdata", + get_centreon_storage_hosts_col_size(centreon_storage_hosts_perfdata)), mapping::entry()}; // Operations. diff --git a/broker/neb/src/instance.cc b/broker/neb/src/instance.cc index 5cd50113597..c2752ee5833 100644 --- a/broker/neb/src/instance.cc +++ b/broker/neb/src/instance.cc @@ -1,20 +1,20 @@ /** -* Copyright 2009-2013,2015 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2009-2013,2015 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/neb/instance.hh" @@ -103,13 +103,15 @@ void instance::_internal_copy(instance const& other) { mapping::entry const instance::entries[] = { mapping::entry(&instance::engine, "engine", - get_instances_col_size(instances_engine)), + get_centreon_storage_instances_col_size( + centreon_storage_instances_engine)), mapping::entry(&instance::poller_id, "instance_id", mapping::entry::invalid_on_zero), mapping::entry(&instance::name, "name", - get_instances_col_size(instances_name)), + get_centreon_storage_instances_col_size( + centreon_storage_instances_name)), mapping::entry(&instance::is_running, "running"), mapping::entry(&instance::pid, "pid"), mapping::entry(&instance::program_end, @@ -120,7 +122,8 @@ mapping::entry const instance::entries[] = { mapping::entry::invalid_on_minus_one), mapping::entry(&instance::version, "version", - get_instances_col_size(instances_version)), + get_centreon_storage_instances_col_size( + centreon_storage_instances_version)), mapping::entry()}; // Operations. diff --git a/broker/neb/src/instance_status.cc b/broker/neb/src/instance_status.cc index e9f70e8c3c7..d83da7dbded 100644 --- a/broker/neb/src/instance_status.cc +++ b/broker/neb/src/instance_status.cc @@ -1,20 +1,20 @@ /** -* Copyright 2009-2013,2015 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2009-2013,2015 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/neb/instance_status.hh" @@ -141,11 +141,13 @@ mapping::entry const instance_status::entries[] = { "passive_service_checks"), mapping::entry(&instance_status::global_host_event_handler, "global_host_event_handler", - get_instances_col_size(instances_global_host_event_handler)), + get_centreon_storage_instances_col_size( + centreon_storage_instances_global_host_event_handler)), mapping::entry( &instance_status::global_service_event_handler, "global_service_event_handler", - get_instances_col_size(instances_global_service_event_handler)), + get_centreon_storage_instances_col_size( + centreon_storage_instances_global_service_event_handler)), mapping::entry()}; // Operations. diff --git a/broker/neb/src/log_entry.cc b/broker/neb/src/log_entry.cc index 3ea0f300313..d3470142bd6 100644 --- a/broker/neb/src/log_entry.cc +++ b/broker/neb/src/log_entry.cc @@ -1,20 +1,20 @@ /** -* Copyright 2009-2013,2015 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2009-2013,2015 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/neb/log_entry.hh" @@ -114,12 +114,14 @@ mapping::entry const log_entry::entries[] = { mapping::entry(&log_entry::host_id, "host_id", mapping::entry::invalid_on_zero), - mapping::entry(&log_entry::host_name, - "host_name", - get_logs_col_size(logs_host_name)), + mapping::entry( + &log_entry::host_name, + "host_name", + get_centreon_storage_logs_col_size(centreon_storage_logs_host_name)), mapping::entry(&log_entry::poller_name, "instance_name", - get_logs_col_size(logs_instance_name)), + get_centreon_storage_logs_col_size( + centreon_storage_logs_instance_name)), mapping::entry(&log_entry::issue_start_time, "", mapping::entry::invalid_on_minus_one), @@ -127,22 +129,26 @@ mapping::entry const log_entry::entries[] = { mapping::entry(&log_entry::msg_type, "msg_type"), mapping::entry(&log_entry::notification_cmd, "notification_cmd", - get_logs_col_size(logs_notification_cmd)), + get_centreon_storage_logs_col_size( + centreon_storage_logs_notification_cmd)), mapping::entry(&log_entry::notification_contact, "notification_contact", - get_logs_col_size(logs_notification_contact)), + get_centreon_storage_logs_col_size( + centreon_storage_logs_notification_contact)), mapping::entry(&log_entry::retry, "retry"), mapping::entry(&log_entry::service_description, "service_description", - get_logs_col_size(logs_service_description), + get_centreon_storage_logs_col_size( + centreon_storage_logs_service_description), mapping::entry::invalid_on_zero), mapping::entry(&log_entry::service_id, "service_id", mapping::entry::invalid_on_zero), mapping::entry(&log_entry::status, "status"), - mapping::entry(&log_entry::output, - "output", - get_logs_col_size(logs_output)), + mapping::entry( + &log_entry::output, + "output", + get_centreon_storage_logs_col_size(centreon_storage_logs_output)), mapping::entry()}; // Operations. diff --git a/broker/neb/src/service.cc b/broker/neb/src/service.cc index a4158a79022..734cb1f5020 100644 --- a/broker/neb/src/service.cc +++ b/broker/neb/src/service.cc @@ -1,20 +1,20 @@ /** -* Copyright 2009-2013,2015 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2009-2013,2015 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/neb/service.hh" @@ -144,14 +144,16 @@ mapping::entry const service::entries[] = { mapping::entry(&service::acknowledgement_type, "acknowledgement_type"), mapping::entry(static_cast(&service::action_url), "action_url", - get_services_col_size(services_action_url)), + get_centreon_storage_services_col_size( + centreon_storage_services_action_url)), mapping::entry(&service::active_checks_enabled, "active_checks"), mapping::entry(static_cast(&service::check_freshness), "check_freshness"), mapping::entry(&service::check_interval, "check_interval"), mapping::entry(&service::check_period, "check_period", - get_services_col_size(services_check_period)), + get_centreon_storage_services_col_size( + centreon_storage_services_check_period)), mapping::entry(&service::check_type, "check_type"), mapping::entry(&service::current_check_attempt, "check_attempt"), mapping::entry(&service::current_state, "state"), @@ -173,11 +175,13 @@ mapping::entry const service::entries[] = { mapping::entry(&service::downtime_depth, "scheduled_downtime_depth"), mapping::entry(static_cast(&service::display_name), "display_name", - get_services_col_size(services_display_name)), + get_centreon_storage_services_col_size( + centreon_storage_services_display_name)), mapping::entry(&service::enabled, "enabled"), mapping::entry(&service::event_handler, "event_handler", - get_services_col_size(services_event_handler)), + get_centreon_storage_services_col_size( + centreon_storage_services_event_handler)), mapping::entry(&service::event_handler_enabled, "event_handler_enabled"), mapping::entry(&service::execution_time, "execution_time"), mapping::entry( @@ -204,11 +208,13 @@ mapping::entry const service::entries[] = { mapping::entry(&service::host_name, nullptr, 0), mapping::entry(static_cast(&service::icon_image), "icon_image", - get_services_col_size(services_icon_image)), + get_centreon_storage_services_col_size( + centreon_storage_services_icon_image)), mapping::entry( static_cast(&service::icon_image_alt), "icon_image_alt", - get_services_col_size(services_icon_image_alt)), + get_centreon_storage_services_col_size( + centreon_storage_services_icon_image_alt)), mapping::entry(&service::service_id, "service_id", mapping::entry::invalid_on_zero), @@ -256,10 +262,12 @@ mapping::entry const service::entries[] = { mapping::entry(&service::no_more_notifications, "no_more_notifications"), mapping::entry(static_cast(&service::notes), "notes", - get_services_col_size(services_notes)), + get_centreon_storage_services_col_size( + centreon_storage_services_notes)), mapping::entry(static_cast(&service::notes_url), "notes_url", - get_services_col_size(services_notes_url)), + get_centreon_storage_services_col_size( + centreon_storage_services_notes_url)), mapping::entry( static_cast(&service::notification_interval), "notification_interval"), @@ -269,7 +277,8 @@ mapping::entry const service::entries[] = { mapping::entry( static_cast(&service::notification_period), "notification_period", - get_services_col_size(services_notification_period)), + get_centreon_storage_services_col_size( + centreon_storage_services_notification_period)), mapping::entry(&service_status::notifications_enabled, "notify"), mapping::entry(&service::notify_on_critical, "notify_on_critical"), mapping::entry(static_cast(&service::notify_on_downtime), @@ -286,7 +295,8 @@ mapping::entry const service::entries[] = { mapping::entry(&service::retry_interval, "retry_interval"), mapping::entry(&service::service_description, "description", - get_services_col_size(services_description)), + get_centreon_storage_services_col_size( + centreon_storage_services_description)), mapping::entry(&service::should_be_scheduled, "should_be_scheduled"), mapping::entry(&service::stalk_on_critical, "stalk_on_critical"), mapping::entry(&service::stalk_on_ok, "stalk_on_ok"), @@ -295,13 +305,16 @@ mapping::entry const service::entries[] = { mapping::entry(&service::state_type, "state_type"), mapping::entry(&service::check_command, "check_command", - get_services_col_size(services_check_command)), + get_centreon_storage_services_col_size( + centreon_storage_services_check_command)), mapping::entry(&service::output, "output", - get_services_col_size(services_output)), + get_centreon_storage_services_col_size( + centreon_storage_services_output)), mapping::entry(&service::perf_data, "perfdata", - get_services_col_size(services_perfdata)), + get_centreon_storage_services_col_size( + centreon_storage_services_perfdata)), mapping::entry( static_cast(&service::retain_nonstatus_information), "retain_nonstatus_information"), diff --git a/broker/neb/src/service_check.cc b/broker/neb/src/service_check.cc index adc6941bae7..8f2a27796a4 100644 --- a/broker/neb/src/service_check.cc +++ b/broker/neb/src/service_check.cc @@ -1,20 +1,20 @@ /** -* Copyright 2009-2013 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2009-2013 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/neb/service_check.hh" @@ -74,7 +74,8 @@ mapping::entry const service_check::entries[] = { mapping::entry::invalid_on_zero), mapping::entry(&service_check::command_line, "command_line", - get_services_col_size(services_command_line)), + get_centreon_storage_services_col_size( + centreon_storage_services_command_line)), mapping::entry()}; // Operations. diff --git a/broker/neb/src/service_dependency.cc b/broker/neb/src/service_dependency.cc index b2ff6f58641..8357aa1df2a 100644 --- a/broker/neb/src/service_dependency.cc +++ b/broker/neb/src/service_dependency.cc @@ -1,20 +1,20 @@ /** -* Copyright 2009-2013,2015 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2009-2013,2015 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/neb/service_dependency.hh" @@ -86,10 +86,11 @@ void service_dependency::_internal_copy(service_dependency const& sd) { // Mapping. mapping::entry const service_dependency::entries[] = { - mapping::entry(&service_dependency::dependency_period, - "dependency_period", - get_services_services_dependencies_col_size( - services_services_dependencies_dependency_period)), + mapping::entry( + &service_dependency::dependency_period, + "dependency_period", + get_centreon_storage_services_services_dependencies_col_size( + centreon_storage_services_services_dependencies_dependency_period)), mapping::entry(&service_dependency::dependent_host_id, "dependent_host_id", mapping::entry::invalid_on_zero), @@ -100,8 +101,8 @@ mapping::entry const service_dependency::entries[] = { mapping::entry( &service_dependency::execution_failure_options, "execution_failure_options", - get_services_services_dependencies_col_size( - services_services_dependencies_execution_failure_options)), + get_centreon_storage_services_services_dependencies_col_size( + centreon_storage_services_services_dependencies_execution_failure_options)), mapping::entry(&service_dependency::host_id, "host_id", mapping::entry::invalid_on_zero), @@ -109,8 +110,8 @@ mapping::entry const service_dependency::entries[] = { mapping::entry( &service_dependency::notification_failure_options, "notification_failure_options", - get_services_services_dependencies_col_size( - services_services_dependencies_notification_failure_options)), + get_centreon_storage_services_services_dependencies_col_size( + centreon_storage_services_services_dependencies_notification_failure_options)), mapping::entry(&service_dependency::service_id, "service_id", mapping::entry::invalid_on_zero), diff --git a/broker/neb/src/service_group.cc b/broker/neb/src/service_group.cc index 38a7bb56cb2..e2fc3c9194d 100644 --- a/broker/neb/src/service_group.cc +++ b/broker/neb/src/service_group.cc @@ -1,20 +1,20 @@ /** -* Copyright 2009-2013,2015 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2009-2013,2015 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/neb/service_group.hh" @@ -73,7 +73,8 @@ mapping::entry const service_group::entries[] = { mapping::entry::invalid_on_zero), mapping::entry(&service_group::name, "name", - get_servicegroups_col_size(servicegroups_name)), + get_centreon_storage_servicegroups_col_size( + centreon_storage_servicegroups_name)), mapping::entry(&service_group::enabled, nullptr), mapping::entry(&service_group::poller_id, nullptr, diff --git a/broker/neb/src/service_status.cc b/broker/neb/src/service_status.cc index 9575a163e59..c9617fa8f5a 100644 --- a/broker/neb/src/service_status.cc +++ b/broker/neb/src/service_status.cc @@ -1,20 +1,20 @@ /** -* Copyright 2009-2013,2015,2019-2021 Centreon -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* For more information : contact@centreon.com -*/ + * Copyright 2009-2013,2015,2019-2021 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #include "com/centreon/broker/neb/service_status.hh" @@ -99,7 +99,8 @@ mapping::entry const service_status::entries[] = { mapping::entry(&service_status::check_interval, "check_interval"), mapping::entry(&service_status::check_period, "check_period", - get_services_col_size(services_check_period)), + get_centreon_storage_services_col_size( + centreon_storage_services_check_period)), mapping::entry(&service_status::check_type, "check_type"), mapping::entry(&service_status::current_check_attempt, "check_attempt"), mapping::entry(&service_status::current_state, "state"), @@ -107,7 +108,8 @@ mapping::entry const service_status::entries[] = { mapping::entry(&service_status::enabled, "enabled"), mapping::entry(&service_status::event_handler, "event_handler", - get_services_col_size(services_event_handler)), + get_centreon_storage_services_col_size( + centreon_storage_services_event_handler)), mapping::entry(&service_status::event_handler_enabled, "event_handler_enabled"), mapping::entry(&service_status::execution_time, "execution_time"), @@ -173,13 +175,16 @@ mapping::entry const service_status::entries[] = { mapping::entry(&service_status::state_type, "state_type"), mapping::entry(&service_status::check_command, "check_command", - get_services_col_size(services_check_command)), + get_centreon_storage_services_col_size( + centreon_storage_services_check_command)), mapping::entry(&service_status::output, "output", - get_services_col_size(services_output)), + get_centreon_storage_services_col_size( + centreon_storage_services_output)), mapping::entry(&service_status::perf_data, "perfdata", - get_services_col_size(services_perfdata)), + get_centreon_storage_services_col_size( + centreon_storage_services_perfdata)), mapping::entry()}; // Operations. diff --git a/broker/neb/test/service.cc b/broker/neb/test/service.cc index 992023a4576..d774aa7849e 100644 --- a/broker/neb/test/service.cc +++ b/broker/neb/test/service.cc @@ -177,6 +177,7 @@ TEST_F(ServiceTest, DefaultCtor) { ASSERT_EQ(entry.get_type(), mapping::source::STRING); size_t max_len; std::string str(entry.get_string(s, &max_len)); - ASSERT_EQ(max_len, get_services_col_size(services_action_url)); + ASSERT_EQ(max_len, get_centreon_storage_services_col_size( + centreon_storage_services_action_url)); ASSERT_TRUE(str.empty()); } diff --git a/broker/storage/src/conflict_manager_sql.cc b/broker/storage/src/conflict_manager_sql.cc index faafa601c0f..3192190688f 100644 --- a/broker/storage/src/conflict_manager_sql.cc +++ b/broker/storage/src/conflict_manager_sql.cc @@ -462,15 +462,18 @@ void conflict_manager::_process_custom_variable( std::get<2>(t), fmt::format( "('{}',{},{},'{}',{},{},{},'{}')", - misc::string::escape( - cv.name, get_customvariables_col_size(customvariables_name)), + misc::string::escape(cv.name, + get_centreon_storage_customvariables_col_size( + centreon_storage_customvariables_name)), cv.host_id, cv.service_id, misc::string::escape( cv.default_value, - get_customvariables_col_size(customvariables_default_value)), + get_centreon_storage_customvariables_col_size( + centreon_storage_customvariables_default_value)), cv.modified ? 1 : 0, cv.var_type, cv.update_time, - misc::string::escape(cv.value, get_customvariables_col_size( - customvariables_value)))); + misc::string::escape(cv.value, + get_centreon_storage_customvariables_col_size( + centreon_storage_customvariables_value)))); /* Here, we do not update the custom variable boolean ack flag, because * it will be updated later when the bulk query will be done: * conflict_manager::_update_customvariables() */ @@ -508,13 +511,15 @@ void conflict_manager::_process_custom_variable_status( _cvs_queue.emplace_back( std::get<2>(t), - fmt::format( - "('{}',{},{},{},{},'{}')", - misc::string::escape( - cv.name, get_customvariables_col_size(customvariables_name)), - cv.host_id, cv.service_id, cv.modified ? 1 : 0, cv.update_time, - misc::string::escape( - cv.value, get_customvariables_col_size(customvariables_value)))); + fmt::format("('{}',{},{},{},{},'{}')", + misc::string::escape( + cv.name, get_centreon_storage_customvariables_col_size( + centreon_storage_customvariables_name)), + cv.host_id, cv.service_id, cv.modified ? 1 : 0, + cv.update_time, + misc::string::escape( + cv.value, get_centreon_storage_customvariables_col_size( + centreon_storage_customvariables_value)))); _logger_sql->info("SQL: updating custom variable '{}' of ({}, {})", cv.name, cv.host_id, cv.service_id); @@ -558,7 +563,8 @@ void conflict_manager::_process_downtime( ? "NULL" : fmt::format("{}", dd.actual_start_time), misc::string::escape(dd.author, - get_downtimes_col_size(downtimes_author)), + get_centreon_storage_downtimes_col_size( + centreon_storage_downtimes_author)), dd.downtime_type, dd.deletion_time.is_null() ? "NULL" : fmt::format("{}", dd.deletion_time), @@ -570,7 +576,8 @@ void conflict_manager::_process_downtime( dd.triggered_by == 0 ? "NULL" : fmt::format("{}", dd.triggered_by), dd.was_cancelled, dd.was_started, misc::string::escape( - dd.comment, get_downtimes_col_size(downtimes_comment_data)))); + dd.comment, get_centreon_storage_downtimes_col_size( + centreon_storage_downtimes_comment_data)))); } } @@ -1108,19 +1115,26 @@ void conflict_manager::_process_log( fmt::format( "({},{},{},'{}','{}',{},{},'{}','{}',{},'{}',{},'{}')", le.c_time, le.host_id, le.service_id, - misc::string::escape(le.host_name, get_logs_col_size(logs_host_name)), + misc::string::escape(le.host_name, + get_centreon_storage_logs_col_size( + centreon_storage_logs_host_name)), misc::string::escape(le.poller_name, - get_logs_col_size(logs_instance_name)), + get_centreon_storage_logs_col_size( + centreon_storage_logs_instance_name)), le.log_type, le.msg_type, misc::string::escape(le.notification_cmd, - get_logs_col_size(logs_notification_cmd)), + get_centreon_storage_logs_col_size( + centreon_storage_logs_notification_cmd)), misc::string::escape(le.notification_contact, - get_logs_col_size(logs_notification_contact)), + get_centreon_storage_logs_col_size( + centreon_storage_logs_notification_contact)), le.retry, misc::string::escape(le.service_description, - get_logs_col_size(logs_service_description)), + get_centreon_storage_logs_col_size( + centreon_storage_logs_service_description)), le.status, - misc::string::escape(le.output, get_logs_col_size(logs_output))))); + misc::string::escape(le.output, get_centreon_storage_logs_col_size( + centreon_storage_logs_output))))); } /** diff --git a/broker/storage/src/conflict_manager_storage.cc b/broker/storage/src/conflict_manager_storage.cc index ba0733dbcde..5a75a31042f 100644 --- a/broker/storage/src/conflict_manager_storage.cc +++ b/broker/storage/src/conflict_manager_storage.cc @@ -136,10 +136,12 @@ void conflict_manager::_storage_process_service_status( "special) VALUES (?,?,?,?,?,?)"); fmt::string_view hv(misc::string::truncate( - ss.host_name, get_index_data_col_size(index_data_host_name))); + ss.host_name, get_centreon_storage_index_data_col_size( + centreon_storage_index_data_host_name))); fmt::string_view sv(misc::string::truncate( ss.service_description, - get_index_data_col_size(index_data_service_description))); + get_centreon_storage_index_data_col_size( + centreon_storage_index_data_service_description))); _index_data_insert.bind_value_as_i32(0, host_id); _index_data_insert.bind_value_as_str(1, hv); _index_data_insert.bind_value_as_i32(2, service_id); @@ -326,16 +328,14 @@ void conflict_manager::_storage_process_service_status( _metric_cache[{index_id, pd.name()}] = info; } catch (const std::exception& e) { _logger_storage->error( - "conflict_manager: failed to create metric {} with type {}, " + "conflict_manager: failed to create metric '{}' with type {}, " "value {}, unit_name {}, warn {}, warn_low {}, warn_mode {}, " "crit {}, crit_low {}, crit_mode {}, min {} and max {}", - metric_id, type, pd.value(), pd.unit(), pd.warning(), + pd.name(), type, pd.value(), pd.unit(), pd.warning(), pd.warning_low(), pd.warning_mode(), pd.critical(), pd.critical_low(), pd.critical_mode(), pd.min(), pd.max()); - throw msg_fmt( - "storage: insertion of metric '{}" - "' of index {} failed: {}", - pd.name(), index_id, e.what()); + // The metric creation failed, we pass to the next metric. + continue; } } else { std::lock_guard lock(_metric_cache_m); @@ -434,7 +434,8 @@ void conflict_manager::_update_metrics() { m.emplace_back(fmt::format( "({},'{}',{},{},'{}',{},{},'{}',{},{},{})", metric->metric_id, misc::string::escape(metric->unit_name, - get_metrics_col_size(metrics_unit_name)), + get_centreon_storage_metrics_col_size( + centreon_storage_metrics_unit_name)), std::isnan(metric->warn) || std::isinf(metric->warn) ? "NULL" : fmt::format("{}", metric->warn), diff --git a/broker/unified_sql/src/stream_sql.cc b/broker/unified_sql/src/stream_sql.cc index 42cd3ef6852..af662996366 100644 --- a/broker/unified_sql/src/stream_sql.cc +++ b/broker/unified_sql/src/stream_sql.cc @@ -418,7 +418,9 @@ void stream::_prepare_pb_hg_insupdate_statement() { _mysql, "hostgroups ", /*space is mandatory to avoid conflict with _host_group_insupdate*/ {{3, "hostgroup_id", io::protobuf_base::invalid_on_zero, 0}, - {4, "name", 0, get_hostgroups_col_size(hostgroups_name)}}); + {4, "name", 0, + get_centreon_storage_hostgroups_col_size( + centreon_storage_hostgroups_name)}}); } } @@ -440,7 +442,9 @@ void stream::_prepare_pb_sg_insupdate_statement() { _mysql, "servicegroups ", /*space is mandatory to avoid conflict with _service_group_insupdate*/ {{3, "servicegroup_id", io::protobuf_base::invalid_on_zero, 0}, - {4, "name", 0, get_servicegroups_col_size(servicegroups_name)}}); + {4, "name", 0, + get_centreon_storage_servicegroups_col_size( + centreon_storage_servicegroups_name)}}); } } @@ -525,9 +529,11 @@ void stream::_process_pb_acknowledgement(const std::shared_ptr& d) { {3, "instance_id", io::protobuf_base::invalid_on_zero, 0}, {4, "type", 0, 0}, {5, "author", 0, - get_acknowledgements_col_size(acknowledgements_author)}, + get_centreon_storage_acknowledgements_col_size( + centreon_storage_acknowledgements_author)}, {6, "comment_data", 0, - get_acknowledgements_col_size(acknowledgements_comment_data)}, + get_centreon_storage_acknowledgements_col_size( + centreon_storage_acknowledgements_comment_data)}, {7, "sticky", 0, 0}, {8, "notify_contacts", 0, 0}, {9, "entry_time", 0, 0}, @@ -572,11 +578,13 @@ void stream::_process_comment(const std::shared_ptr& d) { auto binder = [&](database::mysql_bulk_bind& b) { b.set_value_as_str( 0, misc::string::escape(cmmnt.author, - get_comments_col_size(comments_author))); + get_centreon_storage_comments_col_size( + centreon_storage_comments_author))); b.set_value_as_i32(1, cmmnt.comment_type); b.set_value_as_str( 2, misc::string::escape(cmmnt.data, - get_comments_col_size(comments_data))); + get_centreon_storage_comments_col_size( + centreon_storage_comments_data))); if (cmmnt.deletion_time.is_null()) b.set_null_i64(3); else @@ -604,9 +612,11 @@ void stream::_process_comment(const std::shared_ptr& d) { _comments->add_multi_row(fmt::format( "('{}',{},'{}',{},{},{},{},{},{},{},{},{},{},{})", misc::string::escape(cmmnt.author, - get_comments_col_size(comments_author)), + get_centreon_storage_comments_col_size( + centreon_storage_comments_author)), cmmnt.comment_type, - misc::string::escape(cmmnt.data, get_comments_col_size(comments_data)), + misc::string::escape(cmmnt.data, get_centreon_storage_comments_col_size( + centreon_storage_comments_data)), cmmnt.deletion_time, cmmnt.entry_time, cmmnt.entry_type, cmmnt.expire_time, cmmnt.expires, int64_not_minus_one{cmmnt.host_id}, cmmnt.internal_id, int(cmmnt.persistent), @@ -643,15 +653,18 @@ void stream::_process_pb_custom_variable(const std::shared_ptr& d) { std::lock_guard lck(_queues_m); _cv.push_query(fmt::format( "('{}',{},{},'{}',{},{},{},'{}')", - misc::string::escape( - cv.name(), get_customvariables_col_size(customvariables_name)), + misc::string::escape(cv.name(), + get_centreon_storage_customvariables_col_size( + centreon_storage_customvariables_name)), cv.host_id(), cv.service_id(), misc::string::escape( cv.default_value(), - get_customvariables_col_size(customvariables_default_value)), + get_centreon_storage_customvariables_col_size( + centreon_storage_customvariables_default_value)), cv.modified() ? 1 : 0, cv.type(), cv.update_time(), - misc::string::escape( - cv.value(), get_customvariables_col_size(customvariables_value)))); + misc::string::escape(cv.value(), + get_centreon_storage_customvariables_col_size( + centreon_storage_customvariables_value)))); } else { int conn = special_conn::custom_variable % _mysql.connections_count(); _finish_action(-1, actions::custom_variables); @@ -690,11 +703,13 @@ void stream::_process_pb_comment(const std::shared_ptr& d) { auto binder = [&](database::mysql_bulk_bind& b) { b.set_value_as_str( 0, misc::string::escape(cmmnt.author(), - get_comments_col_size(comments_author))); + get_centreon_storage_comments_col_size( + centreon_storage_comments_author))); b.set_value_as_i32(1, int(cmmnt.type())); b.set_value_as_str( 2, misc::string::escape(cmmnt.data(), - get_comments_col_size(comments_data))); + get_centreon_storage_comments_col_size( + centreon_storage_comments_data))); b.set_value_as_i64(3, cmmnt.deletion_time(), mapping::entry::invalid_on_minus_one | mapping::entry::invalid_on_zero); @@ -719,10 +734,12 @@ void stream::_process_pb_comment(const std::shared_ptr& d) { _comments->add_multi_row(fmt::format( "('{}',{},'{}',{},{},{},{},{},{},{},{},{},{},{})", misc::string::escape(cmmnt.author(), - get_comments_col_size(comments_author)), + get_centreon_storage_comments_col_size( + centreon_storage_comments_author)), cmmnt.type(), misc::string::escape(cmmnt.data(), - get_comments_col_size(comments_data)), + get_centreon_storage_comments_col_size( + centreon_storage_comments_data)), uint64_not_null_not_neg_1{cmmnt.deletion_time()}, uint64_not_null_not_neg_1{cmmnt.entry_time()}, cmmnt.entry_type(), uint64_not_null_not_neg_1{cmmnt.expire_time()}, cmmnt.expires(), @@ -759,15 +776,18 @@ void stream::_process_custom_variable(const std::shared_ptr& d) { std::lock_guard lck(_queues_m); _cv.push_query(fmt::format( "('{}',{},{},'{}',{},{},{},'{}')", - misc::string::escape( - cv.name, get_customvariables_col_size(customvariables_name)), + misc::string::escape(cv.name, + get_centreon_storage_customvariables_col_size( + centreon_storage_customvariables_name)), cv.host_id, cv.service_id, misc::string::escape( cv.default_value, - get_customvariables_col_size(customvariables_default_value)), + get_centreon_storage_customvariables_col_size( + centreon_storage_customvariables_default_value)), cv.modified ? 1 : 0, cv.var_type, cv.update_time, - misc::string::escape( - cv.value, get_customvariables_col_size(customvariables_value)))); + misc::string::escape(cv.value, + get_centreon_storage_customvariables_col_size( + centreon_storage_customvariables_value)))); /* Here, we do not update the custom variable boolean ack flag, * because it will be updated later when the bulk query will be * done: stream::_update_customvariables() */ @@ -804,10 +824,12 @@ void stream::_process_custom_variable_status( _cvs.push_query(fmt::format( "('{}',{},{},{},{},'{}')", misc::string::escape(cv.name, - get_customvariables_col_size(customvariables_name)), + get_centreon_storage_customvariables_col_size( + centreon_storage_customvariables_name)), cv.host_id, cv.service_id, cv.modified ? 1 : 0, cv.update_time, - misc::string::escape( - cv.value, get_customvariables_col_size(customvariables_value)))); + misc::string::escape(cv.value, + get_centreon_storage_customvariables_col_size( + centreon_storage_customvariables_value)))); SPDLOG_LOGGER_INFO(_logger_sql, "unified_sql: updating custom variable '{}' of ({}, {})", @@ -831,11 +853,13 @@ void stream::_process_pb_custom_variable_status( _cvs.push_query(fmt::format( "('{}',{},{},{},{},'{}')", misc::string::escape(data.name(), - get_customvariables_col_size(customvariables_name)), + get_centreon_storage_customvariables_col_size( + centreon_storage_customvariables_name)), data.host_id(), data.service_id(), data.modified() ? 1 : 0, data.update_time(), - misc::string::escape( - data.value(), get_customvariables_col_size(customvariables_value)))); + misc::string::escape(data.value(), + get_centreon_storage_customvariables_col_size( + centreon_storage_customvariables_value)))); SPDLOG_LOGGER_INFO(_logger_sql, "unified_sql: updating custom variable '{}' of ({}, {})", @@ -879,7 +903,8 @@ void stream::_process_downtime(const std::shared_ptr& d) { b.set_value_as_i64(1, dd.actual_start_time); b.set_value_as_str( 2, misc::string::escape(dd.author, - get_downtimes_col_size(downtimes_author))); + get_centreon_storage_downtimes_col_size( + centreon_storage_downtimes_author))); b.set_value_as_i32(3, dd.downtime_type); if (dd.deletion_time.is_null()) b.set_null_i64(4); @@ -910,8 +935,9 @@ void stream::_process_downtime(const std::shared_ptr& d) { b.set_value_as_tiny(15, int(dd.was_cancelled)); b.set_value_as_tiny(16, int(dd.was_started)); b.set_value_as_str( - 17, misc::string::escape(dd.comment, get_downtimes_col_size( - downtimes_comment_data))); + 17, misc::string::escape( + dd.comment, get_centreon_storage_downtimes_col_size( + centreon_storage_downtimes_comment_data))); b.next_row(); }; _downtimes->add_bulk_row(binder); @@ -924,14 +950,16 @@ void stream::_process_downtime(const std::shared_ptr& d) { "({},{},'{}',{},{},{},{},{},{},{},{},{},{},{},{},{},{},'{}')", dd.actual_end_time.to_string(), dd.actual_start_time.to_string(), misc::string::escape(dd.author, - get_downtimes_col_size(downtimes_author)), + get_centreon_storage_downtimes_col_size( + centreon_storage_downtimes_author)), dd.downtime_type, dd.deletion_time.to_string(), dd.duration, dd.end_time.to_string(), dd.entry_time.to_string(), dd.fixed, dd.host_id, dd.poller_id, dd.internal_id, dd.service_id, dd.start_time, int64_not_minus_one{dd.triggered_by}, dd.was_cancelled, dd.was_started, - misc::string::escape( - dd.comment, get_downtimes_col_size(downtimes_comment_data)))); + misc::string::escape(dd.comment, + get_centreon_storage_downtimes_col_size( + centreon_storage_downtimes_comment_data)))); } } } @@ -972,7 +1000,8 @@ void stream::_process_pb_downtime(const std::shared_ptr& d) { mapping::entry::invalid_on_minus_one); b.set_value_as_str( 2, misc::string::escape(dt_obj.author(), - get_downtimes_col_size(downtimes_author))); + get_centreon_storage_downtimes_col_size( + centreon_storage_downtimes_author))); b.set_value_as_i32(3, int(dt_obj.type())); b.set_value_as_i64(4, dt_obj.deletion_time(), mapping::entry::invalid_on_minus_one); @@ -994,10 +1023,11 @@ void stream::_process_pb_downtime(const std::shared_ptr& d) { b.set_value_as_i32(14, dt_obj.triggered_by()); b.set_value_as_tiny(15, int(dt_obj.cancelled())); b.set_value_as_tiny(16, int(dt_obj.started())); - b.set_value_as_str(17, - misc::string::escape( - dt_obj.comment_data(), - get_downtimes_col_size(downtimes_comment_data))); + b.set_value_as_str( + 17, + misc::string::escape(dt_obj.comment_data(), + get_centreon_storage_downtimes_col_size( + centreon_storage_downtimes_comment_data))); b.next_row(); }; _downtimes->add_bulk_row(binder); @@ -1010,7 +1040,8 @@ void stream::_process_pb_downtime(const std::shared_ptr& d) { uint64_not_null_not_neg_1{dt_obj.actual_end_time()}, uint64_not_null_not_neg_1{dt_obj.actual_start_time()}, misc::string::escape(dt_obj.author(), - get_downtimes_col_size(downtimes_author)), + get_centreon_storage_downtimes_col_size( + centreon_storage_downtimes_author)), dt_obj.type(), uint64_not_null_not_neg_1{dt_obj.deletion_time()}, dt_obj.duration(), uint64_not_null_not_neg_1{dt_obj.end_time()}, int64_not_minus_one{dt_obj.entry_time()}, dt_obj.fixed(), @@ -1018,9 +1049,9 @@ void stream::_process_pb_downtime(const std::shared_ptr& d) { dt_obj.service_id(), uint64_not_null_not_neg_1{dt_obj.start_time()}, uint64_not_null{dt_obj.triggered_by()}, dt_obj.cancelled(), dt_obj.started(), - misc::string::escape( - dt_obj.comment_data(), - get_downtimes_col_size(downtimes_comment_data)))); + misc::string::escape(dt_obj.comment_data(), + get_centreon_storage_downtimes_col_size( + centreon_storage_downtimes_comment_data)))); } } } @@ -1151,7 +1182,9 @@ void stream::_process_pb_host_check(const std::shared_ptr& d) { _mysql, "hosts ", /*space is mandatory to avoid conflict with _process_host_check request*/ {{5, "host_id", io::protobuf_base::invalid_on_zero, 0}, - {4, "command_line", 0, get_hosts_col_size(hosts_command_line)}}); + {4, "command_line", 0, + get_centreon_storage_hosts_col_size( + centreon_storage_hosts_command_line)}}); } // Processing. @@ -1933,15 +1966,19 @@ void stream::_process_pb_host(const std::shared_ptr& d) { {5, "enabled", 0, 0}, {6, "scheduled_downtime_depth", 0, 0}, {7, "check_command", 0, - get_hosts_col_size(hosts_check_command)}, + get_centreon_storage_hosts_col_size( + centreon_storage_hosts_check_command)}, {8, "check_interval", 0, 0}, - {9, "check_period", 0, get_hosts_col_size(hosts_check_period)}, + {9, "check_period", 0, + get_centreon_storage_hosts_col_size( + centreon_storage_hosts_check_period)}, {10, "check_type", 0, 0}, {11, "check_attempt", 0, 0}, {12, "state", 0, 0}, {13, "event_handler_enabled", 0, 0}, {14, "event_handler", 0, - get_hosts_col_size(hosts_event_handler)}, + get_centreon_storage_hosts_col_size( + centreon_storage_hosts_event_handler)}, {15, "execution_time", 0, 0}, {16, "flap_detection", 0, 0}, {17, "checked", 0, 0}, @@ -1967,41 +2004,63 @@ void stream::_process_pb_host(const std::shared_ptr& d) { io::protobuf_base::invalid_on_zero, 0}, {33, "no_more_notifications", 0, 0}, {34, "notify", 0, 0}, - {35, "output", 0, get_hosts_col_size(hosts_output)}, + {35, "output", 0, + get_centreon_storage_hosts_col_size( + centreon_storage_hosts_output)}, {36, "passive_checks", 0, 0}, {37, "percent_state_change", 0, 0}, - {38, "perfdata", 0, get_hosts_col_size(hosts_perfdata)}, + {38, "perfdata", 0, + get_centreon_storage_hosts_col_size( + centreon_storage_hosts_perfdata)}, {39, "retry_interval", 0, 0}, {40, "should_be_scheduled", 0, 0}, {41, "obsess_over_host", 0, 0}, {42, "state_type", 0, 0}, - {43, "action_url", 0, get_hosts_col_size(hosts_action_url)}, - {44, "address", 0, get_hosts_col_size(hosts_address)}, - {45, "alias", 0, get_hosts_col_size(hosts_alias)}, + {43, "action_url", 0, + get_centreon_storage_hosts_col_size( + centreon_storage_hosts_action_url)}, + {44, "address", 0, + get_centreon_storage_hosts_col_size( + centreon_storage_hosts_address)}, + {45, "alias", 0, + get_centreon_storage_hosts_col_size( + centreon_storage_hosts_alias)}, {46, "check_freshness", 0, 0}, {47, "default_active_checks", 0, 0}, {48, "default_event_handler_enabled", 0, 0}, {49, "default_flap_detection", 0, 0}, {50, "default_notify", 0, 0}, {51, "default_passive_checks", 0, 0}, - {52, "display_name", 0, get_hosts_col_size(hosts_display_name)}, + {52, "display_name", 0, + get_centreon_storage_hosts_col_size( + centreon_storage_hosts_display_name)}, {53, "first_notification_delay", 0, 0}, {54, "flap_detection_on_down", 0, 0}, {55, "flap_detection_on_unreachable", 0, 0}, {56, "flap_detection_on_up", 0, 0}, {57, "freshness_threshold", 0, 0}, {58, "high_flap_threshold", 0, 0}, - {59, "name", 0, get_hosts_col_size(hosts_name)}, - {60, "icon_image", 0, get_hosts_col_size(hosts_icon_image)}, + {59, "name", 0, + get_centreon_storage_hosts_col_size( + centreon_storage_hosts_name)}, + {60, "icon_image", 0, + get_centreon_storage_hosts_col_size( + centreon_storage_hosts_icon_image)}, {61, "icon_image_alt", 0, - get_hosts_col_size(hosts_icon_image_alt)}, + get_centreon_storage_hosts_col_size( + centreon_storage_hosts_icon_image_alt)}, {62, "instance_id", mapping::entry::invalid_on_zero, 0}, {63, "low_flap_threshold", 0, 0}, - {64, "notes", 0, get_hosts_col_size(hosts_notes)}, - {65, "notes_url", 0, get_hosts_col_size(hosts_notes_url)}, + {64, "notes", 0, + get_centreon_storage_hosts_col_size( + centreon_storage_hosts_notes)}, + {65, "notes_url", 0, + get_centreon_storage_hosts_col_size( + centreon_storage_hosts_notes_url)}, {66, "notification_interval", 0, 0}, {67, "notification_period", 0, - get_hosts_col_size(hosts_notification_period)}, + get_centreon_storage_hosts_col_size( + centreon_storage_hosts_notification_period)}, {68, "notify_on_down", 0, 0}, {69, "notify_on_downtime", 0, 0}, {70, "notify_on_flapping", 0, 0}, @@ -2011,10 +2070,13 @@ void stream::_process_pb_host(const std::shared_ptr& d) { {74, "stalk_on_unreachable", 0, 0}, {75, "stalk_on_up", 0, 0}, {76, "statusmap_image", 0, - get_hosts_col_size(hosts_statusmap_image)}, + get_centreon_storage_hosts_col_size( + centreon_storage_hosts_statusmap_image)}, {77, "retain_nonstatus_information", 0, 0}, {78, "retain_status_information", 0, 0}, - {79, "timezone", 0, get_hosts_col_size(hosts_timezone)}, + {79, "timezone", 0, + get_centreon_storage_hosts_col_size( + centreon_storage_hosts_timezone)}, }); if (_store_in_resources) { _resources_host_insert = _mysql.prepare_query( @@ -2093,19 +2155,26 @@ uint64_t stream::_process_pb_host_in_resources(const Host& h, int32_t conn) { if (h.enabled()) { uint64_t sid = 0; fmt::string_view name{misc::string::truncate( - h.name(), get_resources_col_size(resources_name))}; + h.name(), get_centreon_storage_resources_col_size( + centreon_storage_resources_name))}; fmt::string_view address{misc::string::truncate( - h.address(), get_resources_col_size(resources_address))}; + h.address(), get_centreon_storage_resources_col_size( + centreon_storage_resources_address))}; fmt::string_view alias{misc::string::truncate( - h.alias(), get_resources_col_size(resources_alias))}; + h.alias(), get_centreon_storage_resources_col_size( + centreon_storage_resources_alias))}; fmt::string_view parent_name{misc::string::truncate( - h.name(), get_resources_col_size(resources_parent_name))}; + h.name(), get_centreon_storage_resources_col_size( + centreon_storage_resources_parent_name))}; fmt::string_view notes_url{misc::string::truncate( - h.notes_url(), get_resources_col_size(resources_notes_url))}; + h.notes_url(), get_centreon_storage_resources_col_size( + centreon_storage_resources_notes_url))}; fmt::string_view notes{misc::string::truncate( - h.notes(), get_resources_col_size(resources_notes))}; + h.notes(), get_centreon_storage_resources_col_size( + centreon_storage_resources_notes))}; fmt::string_view action_url{misc::string::truncate( - h.action_url(), get_resources_col_size(resources_action_url))}; + h.action_url(), get_centreon_storage_resources_col_size( + centreon_storage_resources_action_url))}; // INSERT if (found == _resource_cache.end()) { @@ -2378,12 +2447,14 @@ void stream::_process_pb_adaptive_host(const std::shared_ptr& d) { query += fmt::format( " event_handler='{}',", misc::string::escape(ah.event_handler(), - get_hosts_col_size(hosts_event_handler))); + get_centreon_storage_hosts_col_size( + centreon_storage_hosts_event_handler))); if (ah.has_check_command()) query += fmt::format( " check_command='{}',", misc::string::escape(ah.check_command(), - get_hosts_col_size(hosts_check_command))); + get_centreon_storage_hosts_col_size( + centreon_storage_hosts_check_command))); if (ah.has_check_interval()) query += fmt::format(" check_interval={},", ah.check_interval()); if (ah.has_retry_interval()) @@ -2397,13 +2468,15 @@ void stream::_process_pb_adaptive_host(const std::shared_ptr& d) { query += fmt::format( " check_period='{}',", misc::string::escape(ah.check_period(), - get_hosts_col_size(hosts_check_period))); + get_centreon_storage_hosts_col_size( + centreon_storage_hosts_check_period))); if (ah.has_notification_period()) query += fmt::format(" notification_period='{}',", misc::string::escape( ah.notification_period(), - get_services_col_size(services_notification_period))); + get_centreon_storage_services_col_size( + centreon_storage_services_notification_period))); // If nothing was added to query, we can exit immediately. if (query.size() > buf.size()) { @@ -2509,10 +2582,12 @@ void stream::_process_pb_host_status(const std::shared_ptr& d) { std::string full_output{ fmt::format("{}\n{}", hscr.output(), hscr.long_output())}; size_t size = misc::string::adjust_size_utf8( - full_output, get_hosts_col_size(hosts_output)); + full_output, + get_centreon_storage_hosts_col_size(centreon_storage_hosts_output)); b->set_value_as_str(10, fmt::string_view(full_output.data(), size)); size = misc::string::adjust_size_utf8( - hscr.perfdata(), get_hosts_col_size(hosts_perfdata)); + hscr.perfdata(), get_centreon_storage_hosts_col_size( + centreon_storage_hosts_perfdata)); b->set_value_as_str(11, fmt::string_view(hscr.perfdata().data(), size)); b->set_value_as_bool(12, hscr.flapping()); b->set_value_as_f64(13, hscr.percent_state_change()); @@ -2558,11 +2633,13 @@ void stream::_process_pb_host_status(const std::shared_ptr& d) { std::string full_output{ fmt::format("{}\n{}", hscr.output(), hscr.long_output())}; size_t size = misc::string::adjust_size_utf8( - full_output, get_hosts_col_size(hosts_output)); + full_output, + get_centreon_storage_hosts_col_size(centreon_storage_hosts_output)); _hscr_update->bind_value_as_str( 10, fmt::string_view(full_output.data(), size)); size = misc::string::adjust_size_utf8( - hscr.perfdata(), get_hosts_col_size(hosts_perfdata)); + hscr.perfdata(), get_centreon_storage_hosts_col_size( + centreon_storage_hosts_perfdata)); _hscr_update->bind_value_as_str( 11, fmt::string_view(hscr.perfdata().data(), size)); _hscr_update->bind_value_as_bool(12, hscr.flapping()); @@ -2750,14 +2827,20 @@ void stream::_process_pb_instance(const std::shared_ptr& d) { query_preparator qp(neb::pb_instance::static_type(), unique); _pb_instance_insupdate = qp.prepare_insert_or_update_table( _mysql, "instances ", - {{2, "engine", 0, get_instances_col_size(instances_engine)}, + {{2, "engine", 0, + get_centreon_storage_instances_col_size( + centreon_storage_instances_engine)}, {3, "running", 0, 0}, - {4, "name", 0, get_instances_col_size(instances_name)}, + {4, "name", 0, + get_centreon_storage_instances_col_size( + centreon_storage_instances_name)}, {5, "pid", io::protobuf_base::invalid_on_zero, 0}, {6, "instance_id", io::protobuf_base::invalid_on_zero, 0}, {7, "end_time", 0, 0}, {8, "start_time", 0, 0}, - {9, "version", 0, get_instances_col_size(instances_version)}}); + {9, "version", 0, + get_centreon_storage_instances_col_size( + centreon_storage_instances_version)}}); } // Process object. @@ -2853,9 +2936,11 @@ void stream::_process_pb_instance_status(const std::shared_ptr& d) { {7, "check_hosts_freshness", 0, 0}, {8, "check_services_freshness", 0, 0}, {9, "global_host_event_handler", 0, - get_instances_col_size(instances_global_host_event_handler)}, + get_centreon_storage_instances_col_size( + centreon_storage_instances_global_host_event_handler)}, {10, "global_service_event_handler", 0, - get_instances_col_size(instances_global_service_event_handler)}, + get_centreon_storage_instances_col_size( + centreon_storage_instances_global_service_event_handler)}, {11, "last_alive", 0, 0}, {12, "last_command_check", 0, 0}, {13, "obsess_over_hosts", 0, 0}, @@ -2897,25 +2982,33 @@ void stream::_process_log(const std::shared_ptr& d) { b.set_value_as_i64(2, le.service_id); b.set_value_as_str( 3, misc::string::escape(le.host_name, - get_logs_col_size(logs_host_name))); + get_centreon_storage_logs_col_size( + centreon_storage_logs_host_name))); b.set_value_as_str( 4, misc::string::escape(le.poller_name, - get_logs_col_size(logs_instance_name))); + get_centreon_storage_logs_col_size( + centreon_storage_logs_instance_name))); b.set_value_as_i32(5, le.log_type); b.set_value_as_i32(6, le.msg_type); b.set_value_as_str( 7, misc::string::escape(le.notification_cmd, - get_logs_col_size(logs_notification_cmd))); - b.set_value_as_str(8, misc::string::escape( - le.notification_contact, - get_logs_col_size(logs_notification_contact))); + get_centreon_storage_logs_col_size( + centreon_storage_logs_notification_cmd))); + b.set_value_as_str(8, + misc::string::escape( + le.notification_contact, + get_centreon_storage_logs_col_size( + centreon_storage_logs_notification_contact))); b.set_value_as_i32(9, le.retry); - b.set_value_as_str(10, misc::string::escape( - le.service_description, - get_logs_col_size(logs_service_description))); - b.set_value_as_tiny(11, le.status); b.set_value_as_str( - 12, misc::string::escape(le.output, get_logs_col_size(logs_output))); + 10, + misc::string::escape(le.service_description, + get_centreon_storage_logs_col_size( + centreon_storage_logs_service_description))); + b.set_value_as_tiny(11, le.status); + b.set_value_as_str(12, misc::string::escape( + le.output, get_centreon_storage_logs_col_size( + centreon_storage_logs_output))); b.next_row(); }; _logs->add_bulk_row(binder); @@ -2923,19 +3016,26 @@ void stream::_process_log(const std::shared_ptr& d) { _logs->add_multi_row(fmt::format( "({},{},{},'{}','{}',{},{},'{}','{}',{},'{}',{},'{}')", le.c_time, le.host_id, le.service_id, - misc::string::escape(le.host_name, get_logs_col_size(logs_host_name)), + misc::string::escape(le.host_name, + get_centreon_storage_logs_col_size( + centreon_storage_logs_host_name)), misc::string::escape(le.poller_name, - get_logs_col_size(logs_instance_name)), + get_centreon_storage_logs_col_size( + centreon_storage_logs_instance_name)), le.log_type, le.msg_type, misc::string::escape(le.notification_cmd, - get_logs_col_size(logs_notification_cmd)), + get_centreon_storage_logs_col_size( + centreon_storage_logs_notification_cmd)), misc::string::escape(le.notification_contact, - get_logs_col_size(logs_notification_contact)), + get_centreon_storage_logs_col_size( + centreon_storage_logs_notification_contact)), le.retry, misc::string::escape(le.service_description, - get_logs_col_size(logs_service_description)), + get_centreon_storage_logs_col_size( + centreon_storage_logs_service_description)), le.status, - misc::string::escape(le.output, get_logs_col_size(logs_output)))); + misc::string::escape(le.output, get_centreon_storage_logs_col_size( + centreon_storage_logs_output)))); } } @@ -2964,26 +3064,34 @@ void stream::_process_pb_log(const std::shared_ptr& d) { b.set_value_as_i64(2, le_obj.service_id()); b.set_value_as_str( 3, misc::string::escape(le_obj.host_name(), - get_logs_col_size(logs_host_name))); + get_centreon_storage_logs_col_size( + centreon_storage_logs_host_name))); b.set_value_as_str( 4, misc::string::escape(le_obj.instance_name(), - get_logs_col_size(logs_instance_name))); + get_centreon_storage_logs_col_size( + centreon_storage_logs_instance_name))); b.set_value_as_i32(5, le_obj.type()); b.set_value_as_i32(6, le_obj.msg_type()); b.set_value_as_str( 7, misc::string::escape(le_obj.notification_cmd(), - get_logs_col_size(logs_notification_cmd))); - b.set_value_as_str(8, misc::string::escape( - le_obj.notification_contact(), - get_logs_col_size(logs_notification_contact))); + get_centreon_storage_logs_col_size( + centreon_storage_logs_notification_cmd))); + b.set_value_as_str(8, + misc::string::escape( + le_obj.notification_contact(), + get_centreon_storage_logs_col_size( + centreon_storage_logs_notification_contact))); b.set_value_as_i32(9, le_obj.retry()); - b.set_value_as_str(10, misc::string::escape( - le_obj.service_description(), - get_logs_col_size(logs_service_description))); + b.set_value_as_str( + 10, + misc::string::escape(le_obj.service_description(), + get_centreon_storage_logs_col_size( + centreon_storage_logs_service_description))); b.set_value_as_tiny(11, le_obj.status()); - b.set_value_as_str(12, - misc::string::escape(le_obj.output(), - get_logs_col_size(logs_output))); + b.set_value_as_str( + 12, misc::string::escape(le_obj.output(), + get_centreon_storage_logs_col_size( + centreon_storage_logs_output))); b.next_row(); }; _logs->add_bulk_row(binder); @@ -2992,19 +3100,26 @@ void stream::_process_pb_log(const std::shared_ptr& d) { "({},{},{},'{}','{}',{},{},'{}','{}',{},'{}',{},'{}')", le_obj.ctime(), le_obj.host_id(), le_obj.service_id(), misc::string::escape(le_obj.host_name(), - get_logs_col_size(logs_host_name)), + get_centreon_storage_logs_col_size( + centreon_storage_logs_host_name)), misc::string::escape(le_obj.instance_name(), - get_logs_col_size(logs_instance_name)), + get_centreon_storage_logs_col_size( + centreon_storage_logs_instance_name)), le_obj.type(), le_obj.msg_type(), misc::string::escape(le_obj.notification_cmd(), - get_logs_col_size(logs_notification_cmd)), + get_centreon_storage_logs_col_size( + centreon_storage_logs_notification_cmd)), misc::string::escape(le_obj.notification_contact(), - get_logs_col_size(logs_notification_contact)), + get_centreon_storage_logs_col_size( + centreon_storage_logs_notification_contact)), le_obj.retry(), misc::string::escape(le_obj.service_description(), - get_logs_col_size(logs_service_description)), + get_centreon_storage_logs_col_size( + centreon_storage_logs_service_description)), le_obj.status(), - misc::string::escape(le_obj.output(), get_logs_col_size(logs_output)))); + misc::string::escape( + le_obj.output(), + get_centreon_storage_logs_col_size(centreon_storage_logs_output)))); } } @@ -3134,7 +3249,8 @@ void stream::_process_pb_service_check(const std::shared_ptr& d) { {{5, "host_id", io::protobuf_base::invalid_on_zero, 0}, {7, "service_id", io::protobuf_base::invalid_on_zero, 0}, {4, "command_line", 0, - get_services_col_size(services_command_line)}}); + get_centreon_storage_services_col_size( + centreon_storage_services_command_line)}}); } // Processing. @@ -3265,15 +3381,15 @@ void stream::_process_pb_service_dependency( {3, "dependent_host_id", io::protobuf_base::invalid_on_zero, 0}, {9, "dependent_service_id", io::protobuf_base::invalid_on_zero, 0}, {2, "dependency_period", 0, - get_services_services_dependencies_col_size( - services_services_dependencies_dependency_period)}, + get_centreon_storage_services_services_dependencies_col_size( + centreon_storage_services_services_dependencies_dependency_period)}, {5, "execution_failure_options", 0, - get_services_services_dependencies_col_size( - services_services_dependencies_execution_failure_options)}, + get_centreon_storage_services_services_dependencies_col_size( + centreon_storage_services_services_dependencies_execution_failure_options)}, {7, "inherits_parent", 0, 0}, {8, "notification_failure_options", 0, - get_services_services_dependencies_col_size( - services_services_dependencies_notification_failure_options)}}); + get_centreon_storage_services_services_dependencies_col_size( + centreon_storage_services_services_dependencies_notification_failure_options)}}); } // Process object. @@ -3741,16 +3857,19 @@ void stream::_process_pb_service(const std::shared_ptr& d) { {6, "enabled", 0, 0}, {7, "scheduled_downtime_depth", 0, 0}, {8, "check_command", 0, - get_services_col_size(services_check_command)}, + get_centreon_storage_services_col_size( + centreon_storage_services_check_command)}, {9, "check_interval", 0, 0}, {10, "check_period", 0, - get_services_col_size(services_check_period)}, + get_centreon_storage_services_col_size( + centreon_storage_services_check_period)}, {11, "check_type", 0, 0}, {12, "check_attempt", 0, 0}, {13, "state", 0, 0}, {14, "event_handler_enabled", 0, 0}, {15, "event_handler", 0, - get_services_col_size(services_event_handler)}, + get_centreon_storage_services_col_size( + centreon_storage_services_event_handler)}, {16, "execution_time", 0, 0}, {17, "flap_detection", 0, 0}, {18, "checked", 0, 0}, @@ -3773,19 +3892,26 @@ void stream::_process_pb_service(const std::shared_ptr& d) { {34, "next_notification", io::protobuf_base::invalid_on_zero, 0}, {35, "no_more_notifications", 0, 0}, {36, "notify", 0, 0}, - {37, "output", 0, get_services_col_size(services_output)}, + {37, "output", 0, + get_centreon_storage_services_col_size( + centreon_storage_services_output)}, {39, "passive_checks", 0, 0}, {40, "percent_state_change", 0, 0}, - {41, "perfdata", 0, get_services_col_size(services_perfdata)}, + {41, "perfdata", 0, + get_centreon_storage_services_col_size( + centreon_storage_services_perfdata)}, {42, "retry_interval", 0, 0}, {44, "description", 0, - get_services_col_size(services_description)}, + get_centreon_storage_services_col_size( + centreon_storage_services_description)}, {45, "should_be_scheduled", 0, 0}, {46, "obsess_over_service", 0, 0}, {47, "state_type", 0, 0}, - {48, "action_url", 0, get_services_col_size(services_action_url)}, + {48, "action_url", 0, + get_centreon_storage_services_col_size( + centreon_storage_services_action_url)}, {49, "check_freshness", 0, 0}, {50, "default_active_checks", 0, 0}, {51, "default_event_handler_enabled", 0, 0}, @@ -3793,7 +3919,8 @@ void stream::_process_pb_service(const std::shared_ptr& d) { {53, "default_notify", 0, 0}, {54, "default_passive_checks", 0, 0}, {55, "display_name", 0, - get_services_col_size(services_display_name)}, + get_centreon_storage_services_col_size( + centreon_storage_services_display_name)}, {56, "first_notification_delay", 0, 0}, {57, "flap_detection_on_critical", 0, 0}, {58, "flap_detection_on_ok", 0, 0}, @@ -3801,16 +3928,24 @@ void stream::_process_pb_service(const std::shared_ptr& d) { {60, "flap_detection_on_warning", 0, 0}, {61, "freshness_threshold", 0, 0}, {62, "high_flap_threshold", 0, 0}, - {63, "icon_image", 0, get_services_col_size(services_icon_image)}, + {63, "icon_image", 0, + get_centreon_storage_services_col_size( + centreon_storage_services_icon_image)}, {64, "icon_image_alt", 0, - get_services_col_size(services_icon_image_alt)}, + get_centreon_storage_services_col_size( + centreon_storage_services_icon_image_alt)}, {65, "volatile", 0, 0}, {66, "low_flap_threshold", 0, 0}, - {67, "notes", 0, get_services_col_size(services_notes)}, - {68, "notes_url", 0, get_services_col_size(services_notes_url)}, + {67, "notes", 0, + get_centreon_storage_services_col_size( + centreon_storage_services_notes)}, + {68, "notes_url", 0, + get_centreon_storage_services_col_size( + centreon_storage_services_notes_url)}, {69, "notification_interval", 0, 0}, {70, "notification_period", 0, - get_services_col_size(services_notification_period)}, + get_centreon_storage_services_col_size( + centreon_storage_services_notification_period)}, {71, "notify_on_critical", 0, 0}, {72, "notify_on_downtime", 0, 0}, {73, "notify_on_flapping", 0, 0}, @@ -3897,15 +4032,20 @@ uint64_t stream::_process_pb_service_in_resources(const Service& s, if (s.enabled()) { uint64_t sid = 0; fmt::string_view name{misc::string::truncate( - s.display_name(), get_resources_col_size(resources_name))}; + s.display_name(), get_centreon_storage_resources_col_size( + centreon_storage_resources_name))}; fmt::string_view parent_name{misc::string::truncate( - s.host_name(), get_resources_col_size(resources_parent_name))}; + s.host_name(), get_centreon_storage_resources_col_size( + centreon_storage_resources_parent_name))}; fmt::string_view notes_url{misc::string::truncate( - s.notes_url(), get_resources_col_size(resources_notes_url))}; + s.notes_url(), get_centreon_storage_resources_col_size( + centreon_storage_resources_notes_url))}; fmt::string_view notes{misc::string::truncate( - s.notes(), get_resources_col_size(resources_notes))}; + s.notes(), get_centreon_storage_resources_col_size( + centreon_storage_resources_notes))}; fmt::string_view action_url{misc::string::truncate( - s.action_url(), get_resources_col_size(resources_action_url))}; + s.action_url(), get_centreon_storage_resources_col_size( + centreon_storage_resources_action_url))}; // INSERT if (found == _resource_cache.end()) { @@ -4179,12 +4319,14 @@ void stream::_process_pb_adaptive_service(const std::shared_ptr& d) { query += fmt::format( " event_handler='{}',", misc::string::escape(as.event_handler(), - get_services_col_size(services_event_handler))); + get_centreon_storage_services_col_size( + centreon_storage_services_event_handler))); if (as.has_check_command()) query += fmt::format( " check_command='{}',", misc::string::escape(as.check_command(), - get_services_col_size(services_check_command))); + get_centreon_storage_services_col_size( + centreon_storage_services_check_command))); if (as.has_check_interval()) query += fmt::format(" check_interval={},", as.check_interval()); if (as.has_retry_interval()) @@ -4198,13 +4340,15 @@ void stream::_process_pb_adaptive_service(const std::shared_ptr& d) { query += fmt::format( " check_period='{}',", misc::string::escape(as.check_period(), - get_services_col_size(services_check_period))); + get_centreon_storage_services_col_size( + centreon_storage_services_check_period))); if (as.has_notification_period()) query += fmt::format(" notification_period='{}',", misc::string::escape( as.notification_period(), - get_services_col_size(services_notification_period))); + get_centreon_storage_services_col_size( + centreon_storage_services_notification_period))); // If nothing was added to query, we can exit immediately. if (query.size() > buf.size()) { @@ -4258,10 +4402,11 @@ void stream::_check_and_update_index_cache(const Service& ss) { auto it_index_cache = _index_cache.find({ss.host_id(), ss.service_id()}); fmt::string_view hv(misc::string::truncate( - ss.host_name(), get_index_data_col_size(index_data_host_name))); + ss.host_name(), get_centreon_storage_index_data_col_size( + centreon_storage_index_data_host_name))); fmt::string_view sv(misc::string::truncate( - ss.description(), - get_index_data_col_size(index_data_service_description))); + ss.description(), get_centreon_storage_index_data_col_size( + centreon_storage_index_data_service_description))); bool special = ss.type() == BA; int32_t conn = @@ -4505,10 +4650,12 @@ void stream::_process_pb_service_status(const std::shared_ptr& d) { std::string full_output{ fmt::format("{}\n{}", sscr.output(), sscr.long_output())}; size_t size = misc::string::adjust_size_utf8( - full_output, get_services_col_size(services_output)); + full_output, get_centreon_storage_services_col_size( + centreon_storage_services_output)); b->set_value_as_str(11, fmt::string_view(full_output.data(), size)); size = misc::string::adjust_size_utf8( - sscr.perfdata(), get_services_col_size(services_perfdata)); + sscr.perfdata(), get_centreon_storage_services_col_size( + centreon_storage_services_perfdata)); b->set_value_as_str(12, fmt::string_view(sscr.perfdata().data(), size)); b->set_value_as_bool(13, sscr.flapping()); b->set_value_as_f64(14, sscr.percent_state_change()); @@ -4557,11 +4704,13 @@ void stream::_process_pb_service_status(const std::shared_ptr& d) { std::string full_output{ fmt::format("{}\n{}", sscr.output(), sscr.long_output())}; size_t size = misc::string::adjust_size_utf8( - full_output, get_services_col_size(services_output)); + full_output, get_centreon_storage_services_col_size( + centreon_storage_services_output)); _sscr_update->bind_value_as_str( 11, fmt::string_view(full_output.data(), size)); size = misc::string::adjust_size_utf8( - sscr.perfdata(), get_services_col_size(services_perfdata)); + sscr.perfdata(), get_centreon_storage_services_col_size( + centreon_storage_services_perfdata)); _sscr_update->bind_value_as_str( 12, fmt::string_view(sscr.perfdata().data(), size)); _sscr_update->bind_value_as_bool(13, sscr.flapping()); @@ -4597,7 +4746,8 @@ void stream::_process_pb_service_status(const std::shared_ptr& d) { int32_t conn = _mysql.choose_connection_by_instance( _cache_host_instance[static_cast(sscr.host_id())]); size_t output_size = misc::string::adjust_size_utf8( - sscr.output(), get_resources_col_size(resources_output)); + sscr.output(), get_centreon_storage_resources_col_size( + centreon_storage_resources_output)); _logger_sql->debug( "unified_sql: pb service status ({}, {}) {} in resources", sscr.host_id(), sscr.service_id(), sscr.state()); diff --git a/broker/unified_sql/src/stream_storage.cc b/broker/unified_sql/src/stream_storage.cc index 46ca5ccb972..806540f1f15 100644 --- a/broker/unified_sql/src/stream_storage.cc +++ b/broker/unified_sql/src/stream_storage.cc @@ -222,16 +222,15 @@ void stream::_unified_sql_process_pb_service_status( _metric_cache[{index_id, pd.name()}] = info; } catch (std::exception const& e) { _logger_sto->error( - "unified sql: failed to create metric {} with type {}, " + "unified sql: failed to create metric '{}' with type {}, " "value {}, unit_name {}, warn {}, warn_low {}, warn_mode {}, " "crit {}, crit_low {}, crit_mode {}, min {} and max {}", - metric_id, type, pd.value(), pd.unit(), pd.warning(), + pd.name(), type, pd.value(), pd.unit(), pd.warning(), pd.warning_low(), pd.warning_mode(), pd.critical(), pd.critical_low(), pd.critical_mode(), pd.min(), pd.max()); - throw msg_fmt( - "unified_sql: insertion of metric '{}" - "' of index {} failed: {}", - pd.name(), index_id, e.what()); + + // The metric creation failed, we pass to the next metric. + continue; } } else { rlck.unlock(); @@ -455,10 +454,12 @@ void stream::_unified_sql_process_service_status( _index_data_insert = _mysql.prepare_query(_index_data_insert_request); fmt::string_view hv(misc::string::truncate( - ss.host_name, get_index_data_col_size(index_data_host_name))); + ss.host_name, get_centreon_storage_index_data_col_size( + centreon_storage_index_data_host_name))); fmt::string_view sv(misc::string::truncate( ss.service_description, - get_index_data_col_size(index_data_service_description))); + get_centreon_storage_index_data_col_size( + centreon_storage_index_data_service_description))); _index_data_insert.bind_value_as_i32(0, host_id); _index_data_insert.bind_value_as_str(1, hv); _index_data_insert.bind_value_as_i32(2, service_id); @@ -591,16 +592,15 @@ void stream::_unified_sql_process_service_status( _metric_cache[{index_id, pd.name()}] = info; } catch (std::exception const& e) { _logger_sto->error( - "unified sql: failed to create metric {} with type {}, " + "unified sql: failed to create metric '{}' with type {}, " "value {}, unit_name {}, warn {}, warn_low {}, warn_mode {}, " "crit {}, crit_low {}, crit_mode {}, min {} and max {}", - metric_id, type, pd.value(), pd.unit(), pd.warning(), + pd.name(), type, pd.value(), pd.unit(), pd.warning(), pd.warning_low(), pd.warning_mode(), pd.critical(), pd.critical_low(), pd.critical_mode(), pd.min(), pd.max()); - throw msg_fmt( - "unified_sql: insertion of metric '{}" - "' of index {} failed: {}", - pd.name(), index_id, e.what()); + + // The metric creation failed, we pass to the next metric. + continue; } } else { rlck.unlock(); @@ -740,7 +740,8 @@ void stream::_update_metrics() { m.emplace_back(fmt::format( "({},'{}',{},{},'{}',{},{},'{}',{},{},{})", metric.metric_id, misc::string::escape(metric.unit_name, - get_metrics_col_size(metrics_unit_name)), + get_centreon_storage_metrics_col_size( + centreon_storage_metrics_unit_name)), std::isnan(metric.warn) || std::isinf(metric.warn) ? "NULL" : fmt::format("{}", metric.warn), diff --git a/tests/broker-engine/big-metrics.robot b/tests/broker-engine/big-metrics.robot new file mode 100644 index 00000000000..84e3176550b --- /dev/null +++ b/tests/broker-engine/big-metrics.robot @@ -0,0 +1,50 @@ +*** Settings *** +Documentation There tests are about big metric values + +Resource ../resources/import.resource + +Suite Setup Ctn Clean Before Suite +Suite Teardown Ctn Clean After Suite +Test Setup Ctn Stop Processes +Test Teardown Ctn Test Clean + + +*** Test Cases *** +EBBM1 + [Documentation] A service status contains metrics that do not fit in a float number. + [Tags] broker engine services unified_sql + Ctn Config Engine ${1} ${1} ${1} + # We want all the services to be passive to avoid parasite checks during our test. + Ctn Set Services Passive ${0} service_.* + Ctn Config Broker rrd + Ctn Config Broker central + Ctn Config Broker module ${1} + Ctn Config BBDO3 1 + Ctn Broker Config Log central core info + Ctn Broker Config Log central tcp error + Ctn Broker Config Log central sql trace + Ctn Broker Config Log central perfdata trace + Ctn Config Broker Sql Output central unified_sql + Ctn Clear Retention + ${start} Get Current Date + ${start_broker} Get Current Date + Ctn Start Broker + Ctn Start engine + Ctn Wait For Engine To Be Ready ${1} + + FOR ${i} IN RANGE ${10} + Ctn Process Service Check Result With Big Metrics + ... host_1 service_1 1 + ... Big Metrics ${10} + END + ${content} Create List + ... Out of range value for column 'current_value' + ${result} Ctn Find In Log With Timeout ${centralLog} ${start} ${content} 30 + Should Be True not ${result} It shouldn't be forbidden to store big metrics in the database. + + +*** Keywords *** +Ctn Test Clean + Ctn Stop Engine + Ctn Kindly Stop Broker + Ctn Save Logs If Failed diff --git a/tests/resources/Engine.py b/tests/resources/Engine.py index b95617aa091..b30ef3a99e6 100755 --- a/tests/resources/Engine.py +++ b/tests/resources/Engine.py @@ -2757,6 +2757,33 @@ def ctn_process_service_check_result_with_metrics(hst: str, svc: str, state: int ctn_process_service_check_result(hst, svc, state, full_output, config) +def ctn_process_service_check_result_with_big_metrics(hst: str, svc: str, state: int, output: str, metrics: int, config='config0', metric_name='metric'): + """ + Send a service check result with metrics but their values are to big to fit into a float. + + Args: + hst (str): Host name of the service. + svc (str): Service description of the service. + state (int): State of the check to set. + output (str): An output message for the check. + metrics (int): The number of metrics that should appear in the result. + config (str, optional): Defaults to 'config0' (useful in case of several Engine running). + metric_name (str): The base name of metrics. They will appear followed by an integer (for example metric0, metric1, metric2, ...). + + Returns: + 0 on success. + """ + now = int(time.time()) + pd = [output + " | "] + for m in range(metrics): + mx = 3.40282e+039 + v = mx + abs(math.sin((now + m) / 1000) * 5) + pd.append(f"{metric_name}{m}={v}") + logger.trace(f"{metric_name}{m}={v}") + full_output = " ".join(pd) + ctn_process_service_check_result(hst, svc, state, full_output, config) + + def ctn_process_service_check_result(hst: str, svc: str, state: int, output: str, config='config0', use_grpc=0, nb_check=1): """ Send a service check result. From 837eaf7406cad8f49111245f5263b54d19e74f9c Mon Sep 17 00:00:00 2001 From: tuntoja <58987095+tuntoja@users.noreply.github.com> Date: Wed, 12 Jun 2024 08:40:22 +0200 Subject: [PATCH 34/60] fix(release): fix release action divergence (#1422) * fix(release): fix release action divergence * Remove variable duplicate --- .github/actions/release/action.yml | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/.github/actions/release/action.yml b/.github/actions/release/action.yml index f527522462f..1fcb0b03a98 100644 --- a/.github/actions/release/action.yml +++ b/.github/actions/release/action.yml @@ -38,7 +38,10 @@ runs: declare -a PREVIOUS_STABLE_TAGS=() SCOPE_VERSION="COLLECT" MINOR_VERSION_FILE_PATH=".version" - RELEASE_CLOUD=0 + RELEASE_CLOUD=0 # (0 = not a release cloud, 1 = release cloud) + MAJOR_VERSION="" + MINOR_VERSION="" + CURRENT_STABLE_BRANCH_MAJOR_VERSION="" # Get current stable branch name # If MASTER, use root .version @@ -138,9 +141,9 @@ runs: fi # Rebuild NEW_STABLE_TAGS as an array - for i in ${NEW_STABLE_TAGS[@]}; do - NEW_RELEASE_TAGS+=("$i") - done + # for i in ${NEW_STABLE_TAGS[@]}; do + # NEW_RELEASE_TAGS+=("$i") + # done # Create GITHUB release for each release components # Abort if no tags @@ -200,7 +203,7 @@ runs: # Send to JIRA API release echo "Sending to JIRA API release: $JIRA_RELEASE_DATA" curl --fail --request POST \ - --url 'https://${{ inputs.jira_base_url }}/rest/api/3/version' \ + --url "${{ inputs.jira_base_url }}/rest/api/3/version" \ --user '${{ inputs.jira_user_email }}:${{ inputs.jira_api_token }}' \ --header 'Accept: application/json' \ --header 'Content-Type: application/json' \ From 4af9f85e4ebe08dad69d81da27816e44c7d9e086 Mon Sep 17 00:00:00 2001 From: jean-christophe81 <98889244+jean-christophe81@users.noreply.github.com> Date: Wed, 12 Jun 2024 17:14:33 +0200 Subject: [PATCH 35/60] enh(broker/common): asio process class, move perfdata to common (#1326) REFS: MON-34009 --- broker/CMakeLists.txt | 3 - .../core/inc/com/centreon/broker/misc/misc.hh | 7 +- .../inc/com/centreon/broker/misc/perfdata.hh | 98 ----- broker/core/src/misc/perfdata.cc | 363 ------------------ broker/lua/src/broker_utils.cc | 15 +- broker/rrd/src/creator.cc | 8 +- broker/rrd/src/output.cc | 18 +- .../broker/storage/conflict_manager.hh | 2 +- broker/storage/src/conflict_manager.cc | 2 +- .../storage/src/conflict_manager_storage.cc | 15 +- broker/storage/src/stream.cc | 2 +- broker/storage/test/metric.cc | 4 +- broker/storage/test/perfdata.cc | 158 ++++---- broker/test/CMakeLists.txt | 1 - .../com/centreon/broker/unified_sql/stream.hh | 2 +- broker/unified_sql/src/stream.cc | 5 +- broker/unified_sql/src/stream_storage.cc | 26 +- broker/unified_sql/test/metric.cc | 4 +- broker/unified_sql/test/perfdata.cc | 157 ++++---- common/CMakeLists.txt | 2 + common/doc/common-doc.md | 66 ++++ common/inc/com/centreon/common/perfdata.hh | 86 +++++ common/inc/com/centreon/common/process.hh | 194 ++++++++++ common/precomp_inc/precomp.hh | 5 +- .../src/perfdata.cc | 175 ++++++--- common/src/process.cc | 321 ++++++++++++++++ common/tests/CMakeLists.txt | 2 + .../tests/perfdata_test.cc | 267 +++++++------ common/tests/process_test.cc | 174 +++++++++ common/tests/test_main.cc | 1 + .../modules/opentelemetry/src/otl_config.cc | 4 + engine/tests/checks/anomalydetection.cc | 2 + vcpkg.json | 3 +- 33 files changed, 1335 insertions(+), 857 deletions(-) delete mode 100644 broker/core/inc/com/centreon/broker/misc/perfdata.hh delete mode 100644 broker/core/src/misc/perfdata.cc create mode 100644 common/inc/com/centreon/common/perfdata.hh create mode 100644 common/inc/com/centreon/common/process.hh rename broker/core/src/misc/parse_perfdata.cc => common/src/perfdata.cc (64%) create mode 100644 common/src/process.cc rename broker/core/test/misc/perfdata.cc => common/tests/perfdata_test.cc (63%) create mode 100644 common/tests/process_test.cc diff --git a/broker/CMakeLists.txt b/broker/CMakeLists.txt index aa6ab735390..e3f564ffa9e 100644 --- a/broker/CMakeLists.txt +++ b/broker/CMakeLists.txt @@ -342,8 +342,6 @@ set(LIBROKER_SOURCES ${SRC_DIR}/misc/diagnostic.cc ${SRC_DIR}/misc/filesystem.cc ${SRC_DIR}/misc/misc.cc - ${SRC_DIR}/misc/parse_perfdata.cc - ${SRC_DIR}/misc/perfdata.cc ${SRC_DIR}/misc/processing_speed_computer.cc ${SRC_DIR}/misc/string.cc ${SRC_DIR}/misc/time.cc @@ -411,7 +409,6 @@ set(LIBROKER_SOURCES ${INC_DIR}/misc/diagnostic.hh ${INC_DIR}/misc/filesystem.hh ${INC_DIR}/misc/misc.hh - ${INC_DIR}/misc/perfdata.hh ${INC_DIR}/misc/processing_speed_computer.hh ${INC_DIR}/misc/shared_mutex.hh ${INC_DIR}/misc/string.hh diff --git a/broker/core/inc/com/centreon/broker/misc/misc.hh b/broker/core/inc/com/centreon/broker/misc/misc.hh index a8ccb9f64d0..58aa1b9f020 100644 --- a/broker/core/inc/com/centreon/broker/misc/misc.hh +++ b/broker/core/inc/com/centreon/broker/misc/misc.hh @@ -19,7 +19,6 @@ #ifndef CCB_MISC_MISC_HH #define CCB_MISC_MISC_HH -#include "com/centreon/broker/misc/perfdata.hh" #include "com/centreon/broker/multiplexing/muxer_filter.hh" namespace com::centreon::broker::misc { @@ -30,11 +29,7 @@ std::string exec(std::string const& cmd); int32_t exec_process(char const** argv, bool wait_for_completion); std::vector from_hex(std::string const& str); std::string dump_filters(const multiplexing::muxer_filter& filters); -std::list parse_perfdata( - uint32_t host_id, - uint32_t service_id, - const char* str, - const std::shared_ptr& logger); + #if DEBUG_ROBOT void debug(const std::string& content); #endif diff --git a/broker/core/inc/com/centreon/broker/misc/perfdata.hh b/broker/core/inc/com/centreon/broker/misc/perfdata.hh deleted file mode 100644 index d9e87986a67..00000000000 --- a/broker/core/inc/com/centreon/broker/misc/perfdata.hh +++ /dev/null @@ -1,98 +0,0 @@ -/** - * Copyright 2011-2023 Centreon - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * For more information : contact@centreon.com - */ - -#ifndef CCB_MISC_PERFDATA_HH -#define CCB_MISC_PERFDATA_HH - -namespace com::centreon::broker::misc { -/** - * @class perfdata perfdata.hh "com/centreon/broker/misc/perfdata.hh" - * @brief Store perfdata values. - * - * Store perfdata values. - */ -class perfdata { - public: - enum data_type { gauge = 0, counter, derive, absolute, automatic }; - - private: - float _critical; - float _critical_low; - bool _critical_mode; - float _max; - float _min; - std::string _name; - std::string _unit; - float _value; - int16_t _value_type; - float _warning; - float _warning_low; - bool _warning_mode; - - public: - perfdata(); - perfdata(const perfdata&) = default; - perfdata(perfdata&&) = default; - ~perfdata() noexcept = default; - perfdata& operator=(perfdata const& pd); - perfdata& operator=(perfdata&& pd); - float critical() const noexcept; - void critical(float c) noexcept; - float critical_low() const noexcept; - void critical_low(float c) noexcept; - bool critical_mode() const noexcept; - void critical_mode(bool m) noexcept; - float max() const noexcept; - void max(float m) noexcept; - float min() const noexcept; - void min(float m) noexcept; - std::string const& name() const noexcept; - void name(std::string const& n); - void name(std::string&& n); - std::string const& unit() const noexcept; - void unit(std::string const& u); - void unit(std::string&& u); - float value() const noexcept; - void value(float v) noexcept; - int16_t value_type() const noexcept; - void value_type(int16_t t) noexcept; - float warning() const noexcept; - void warning(float w) noexcept; - float warning_low() const noexcept; - void warning_low(float w) noexcept; - bool warning_mode() const noexcept; - void warning_mode(bool m) noexcept; -}; - -/** - * Get the value. - * - * @return Metric value. - */ -// Inlined after profiling for performance. -inline float perfdata::value() const noexcept { - return _value; -} -} // namespace com::centreon::broker::misc - -bool operator==(com::centreon::broker::misc::perfdata const& left, - com::centreon::broker::misc::perfdata const& right); -bool operator!=(com::centreon::broker::misc::perfdata const& left, - com::centreon::broker::misc::perfdata const& right); - -#endif // !CCB_MISC_PERFDATA_HH diff --git a/broker/core/src/misc/perfdata.cc b/broker/core/src/misc/perfdata.cc deleted file mode 100644 index b21d1f66764..00000000000 --- a/broker/core/src/misc/perfdata.cc +++ /dev/null @@ -1,363 +0,0 @@ -/** - * Copyright 2011-2013 Centreon - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * For more information : contact@centreon.com - */ - -#include "com/centreon/broker/misc/perfdata.hh" - -#include - -using namespace com::centreon::broker::misc; - -/** - * Default constructor. - */ -perfdata::perfdata() - : _critical(NAN), - _critical_low(NAN), - _critical_mode(false), - _max(NAN), - _min(NAN), - _value(NAN), - _value_type(0), // gauge - _warning(NAN), - _warning_low(NAN), - _warning_mode(false) {} - -/** - * Move operator. - * - * @param[in] other Object to copy. - * - * @return This object. - */ -perfdata& perfdata::operator=(perfdata&& other) { - if (this != &other) { - _critical = other._critical; - _critical_low = other._critical_low; - _critical_mode = other._critical_mode; - _max = other._max; - _min = other._min; - _name = std::move(other._name); - _unit = std::move(other._unit); - _value = other._value; - _value_type = other._value_type; - _warning = other._warning; - _warning_low = other._warning_low; - _warning_mode = other._warning_mode; - } - return *this; -} - -/** - * Assignment operator. - * - * @param[in] other Object to copy. - * - * @return This object. - */ -perfdata& perfdata::operator=(perfdata const& other) { - if (this != &other) { - _critical = other._critical; - _critical_low = other._critical_low; - _critical_mode = other._critical_mode; - _max = other._max; - _min = other._min; - _name = other._name; - _unit = other._unit; - _value = other._value; - _value_type = other._value_type; - _warning = other._warning; - _warning_low = other._warning_low; - _warning_mode = other._warning_mode; - } - return *this; -} - -/** - * Get the critical value. - * - * @return Critical value. - */ -float perfdata::critical() const noexcept { - return _critical; -} - -/** - * Set the critical value. - * - * @param[in] c New critical value. - */ -void perfdata::critical(float c) noexcept { - _critical = c; -} - -/** - * Get the low critical threshold. - * - * @return Low critical value. - */ -float perfdata::critical_low() const noexcept { - return _critical_low; -} - -/** - * Set the low critical threshold. - * - * @param[in] c Low critical value. - */ -void perfdata::critical_low(float c) noexcept { - _critical_low = c; -} - -/** - * Get the critical threshold mode. - * - * @return false if an alert is generated if the value is outside the - * range, true otherwise. - */ -bool perfdata::critical_mode() const noexcept { - return _critical_mode; -} - -/** - * Set the critical threshold mode. - * - * @param[in] m false if an alert is generated if the value is outside - * the range, true otherwise. - */ -void perfdata::critical_mode(bool m) noexcept { - _critical_mode = m; -} - -/** - * Get the maximum value. - * - * @return Maximum value. - */ -float perfdata::max() const noexcept { - return _max; -} - -/** - * Set the maximum value. - * - * @param[in] m New maximum value. - */ -void perfdata::max(float m) noexcept { - _max = m; -} - -/** - * Get the minimum value. - * - * @return Minimum value. - */ -float perfdata::min() const noexcept { - return _min; -} - -/** - * Set the minimum value. - * - * @param[in] m New minimum value. - */ -void perfdata::min(float m) noexcept { - _min = m; -} - -/** - * Get the name of the metric. - * - * @return Name of the metric. - */ -std::string const& perfdata::name() const noexcept { - return _name; -} - -/** - * Set the name of the metric. - * - * @param[in] n New name of the metric. - */ -void perfdata::name(std::string const& n) { - _name = n; -} - -void perfdata::name(std::string&& n) { - _name = n; -} - -/** - * Get the unit. - * - * @return Unit. - */ -std::string const& perfdata::unit() const noexcept { - return _unit; -} - -/** - * Set the unit. - * - * @param[in] u New unit. - */ -void perfdata::unit(std::string const& u) { - _unit = u; -} - -void perfdata::unit(std::string&& u) { - _unit = u; -} - -/** - * Set the value. - * - * @param[in] v New value. - */ -void perfdata::value(float v) noexcept { - _value = v; -} - -/** - * Get the type of the value. - * - * @return Type of the value. - */ -int16_t perfdata::value_type() const noexcept { - return _value_type; -} - -/** - * Set the type of the value. - * - * @param[in] t New type. - */ -void perfdata::value_type(int16_t t) noexcept { - _value_type = t; -} - -/** - * Get the warning value. - * - * @return Warning value. - */ -float perfdata::warning() const noexcept { - return _warning; -} - -/** - * Set the warning value. - * - * @param[in] v New warning value. - */ -void perfdata::warning(float w) noexcept { - _warning = w; -} - -/** - * Get the low warning threshold. - * - * @return Low warning value. - */ -float perfdata::warning_low() const noexcept { - return _warning_low; -} - -/** - * Set the low warning threshold. - * - * @param[in] w Low warning value. - */ -void perfdata::warning_low(float w) noexcept { - _warning_low = w; -} - -/** - * Get the warning threshold mode. - * - * @return false if an alert is generated if the value is outside the - * range, true otherwise. - */ -bool perfdata::warning_mode() const noexcept { - return _warning_mode; -} - -/** - * Set the warning threshold mode. - * - * @param[in] m false if an alert is generated if the value it outside - * the range, true otherwise. - */ -void perfdata::warning_mode(bool m) noexcept { - _warning_mode = m; -} - -/************************************** - * * - * Global Functions * - * * - **************************************/ - -/** - * Comparison helper. - * - * @param[in] a First value. - * @param[in] b Second value. - * - * @return true if a and b are equal. - */ -static inline bool float_equal(float a, float b) { - return (std::isnan(a) && std::isnan(b)) || - (std::isinf(a) && std::isinf(b) && - std::signbit(a) == std::signbit(b)) || - (std::isfinite(a) && std::isfinite(b) && - fabs(a - b) <= 0.01 * fabs(a)); -} - -/** - * Compare two perfdata objects. - * - * @param[in] left First object. - * @param[in] right Second object. - * - * @return true if both objects are equal. - */ -bool operator==(perfdata const& left, perfdata const& right) { - return float_equal(left.critical(), right.critical()) && - float_equal(left.critical_low(), right.critical_low()) && - left.critical_mode() == right.critical_mode() && - float_equal(left.max(), right.max()) && - float_equal(left.min(), right.min()) && left.name() == right.name() && - left.unit() == right.unit() && - float_equal(left.value(), right.value()) && - left.value_type() == right.value_type() && - float_equal(left.warning(), right.warning()) && - float_equal(left.warning_low(), right.warning_low()) && - left.warning_mode() == right.warning_mode(); -} - -/** - * Compare two perfdata objects. - * - * @param[in] left First object. - * @param[in] right Second object. - * - * @return true if both objects are inequal. - */ -bool operator!=(perfdata const& left, perfdata const& right) { - return !(left == right); -} diff --git a/broker/lua/src/broker_utils.cc b/broker/lua/src/broker_utils.cc index 53b751fd691..e5a7f9792af 100644 --- a/broker/lua/src/broker_utils.cc +++ b/broker/lua/src/broker_utils.cc @@ -36,7 +36,10 @@ #include "com/centreon/broker/io/protobuf.hh" #include "com/centreon/broker/mapping/entry.hh" #include "com/centreon/broker/misc/misc.hh" +#include "com/centreon/broker/misc/string.hh" +#include "com/centreon/broker/sql/table_max_size.hh" #include "com/centreon/common/hex_dump.hh" +#include "com/centreon/common/perfdata.hh" #include "com/centreon/exceptions/msg_fmt.hh" #include "common/log_v2/log_v2.hh" @@ -647,9 +650,17 @@ static int l_broker_parse_perfdata(lua_State* L) { char const* perf_data(lua_tostring(L, 1)); int full(lua_toboolean(L, 2)); auto logger = log_v2::instance().get(log_v2::LUA); - std::list pds{misc::parse_perfdata(0, 0, perf_data, logger)}; + std::list pds{ + com::centreon::common::perfdata::parse_perfdata(0, 0, perf_data, logger)}; lua_createtable(L, 0, pds.size()); - for (auto const& pd : pds) { + for (auto& pd : pds) { + pd.resize_name(misc::string::adjust_size_utf8( + pd.name(), get_centreon_storage_metrics_col_size( + centreon_storage_metrics_metric_name))); + pd.resize_unit(misc::string::adjust_size_utf8( + pd.unit(), get_centreon_storage_metrics_col_size( + centreon_storage_metrics_unit_name))); + lua_pushlstring(L, pd.name().c_str(), pd.name().size()); if (full) { std::string_view name{pd.name()}; diff --git a/broker/rrd/src/creator.cc b/broker/rrd/src/creator.cc index d15259eb08f..af60807bfaa 100644 --- a/broker/rrd/src/creator.cc +++ b/broker/rrd/src/creator.cc @@ -30,9 +30,9 @@ #include #include "bbdo/storage/metric.hh" -#include "com/centreon/broker/misc/perfdata.hh" #include "com/centreon/broker/rrd/creator.hh" #include "com/centreon/broker/rrd/exceptions/open.hh" +#include "com/centreon/common/perfdata.hh" #include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; @@ -235,13 +235,13 @@ void creator::_open(std::string const& filename, { const char* tt; switch (value_type) { - case misc::perfdata::absolute: + case common::perfdata::absolute: tt = "ABSOLUTE"; break; - case misc::perfdata::counter: + case common::perfdata::counter: tt = "COUNTER"; break; - case misc::perfdata::derive: + case common::perfdata::derive: tt = "DERIVE"; break; default: diff --git a/broker/rrd/src/output.cc b/broker/rrd/src/output.cc index 17175958d2b..8bd15e38ac2 100644 --- a/broker/rrd/src/output.cc +++ b/broker/rrd/src/output.cc @@ -31,9 +31,9 @@ #include "bbdo/storage/status.hh" #include "com/centreon/broker/exceptions/shutdown.hh" #include "com/centreon/broker/io/events.hh" -#include "com/centreon/broker/misc/perfdata.hh" #include "com/centreon/broker/rrd/exceptions/open.hh" #include "com/centreon/broker/rrd/exceptions/update.hh" +#include "com/centreon/common/perfdata.hh" #include "common/log_v2/log_v2.hh" using namespace com::centreon::broker; @@ -285,25 +285,25 @@ int output::write(std::shared_ptr const& d) { } std::string v; switch (e->value_type) { - case misc::perfdata::gauge: + case common::perfdata::gauge: v = fmt::format("{:f}", e->value); SPDLOG_LOGGER_TRACE(_logger, "RRD: update metric {} of type GAUGE with {}", e->metric_id, v); break; - case misc::perfdata::counter: + case common::perfdata::counter: v = fmt::format("{}", static_cast(e->value)); SPDLOG_LOGGER_TRACE( _logger, "RRD: update metric {} of type COUNTER with {}", e->metric_id, v); break; - case misc::perfdata::derive: + case common::perfdata::derive: v = fmt::format("{}", static_cast(e->value)); SPDLOG_LOGGER_TRACE( _logger, "RRD: update metric {} of type DERIVE with {}", e->metric_id, v); break; - case misc::perfdata::absolute: + case common::perfdata::absolute: v = fmt::format("{}", static_cast(e->value)); SPDLOG_LOGGER_TRACE( _logger, "RRD: update metric {} of type ABSOLUTE with {}", @@ -588,15 +588,15 @@ void output::_rebuild_data(const RebuildMessage& rm) { int32_t data_source_type = p.second.data_source_type(); switch (data_source_type) { - case misc::perfdata::gauge: + case common::perfdata::gauge: for (auto& pt : p.second.pts()) { query.emplace_back(fmt::format("{}:{:f}", pt.ctime(), pt.value())); fill_status_request(index_id, p.second.check_interval(), p.second.rrd_retention(), pt); } break; - case misc::perfdata::counter: - case misc::perfdata::absolute: + case common::perfdata::counter: + case common::perfdata::absolute: for (auto& pt : p.second.pts()) { query.emplace_back(fmt::format("{}:{}", pt.ctime(), static_cast(pt.value()))); @@ -604,7 +604,7 @@ void output::_rebuild_data(const RebuildMessage& rm) { p.second.rrd_retention(), pt); } break; - case misc::perfdata::derive: + case common::perfdata::derive: for (auto& pt : p.second.pts()) { query.emplace_back(fmt::format("{}:{}", pt.ctime(), static_cast(pt.value()))); diff --git a/broker/storage/inc/com/centreon/broker/storage/conflict_manager.hh b/broker/storage/inc/com/centreon/broker/storage/conflict_manager.hh index 2a71612cc93..6a8a1330519 100644 --- a/broker/storage/inc/com/centreon/broker/storage/conflict_manager.hh +++ b/broker/storage/inc/com/centreon/broker/storage/conflict_manager.hh @@ -22,10 +22,10 @@ #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/io/stream.hh" #include "com/centreon/broker/misc/mfifo.hh" -#include "com/centreon/broker/misc/perfdata.hh" #include "com/centreon/broker/sql/mysql.hh" #include "com/centreon/broker/storage/rebuilder.hh" #include "com/centreon/broker/storage/stored_timestamp.hh" +#include "com/centreon/common/perfdata.hh" namespace com::centreon::broker { /* Forward declarations */ diff --git a/broker/storage/src/conflict_manager.cc b/broker/storage/src/conflict_manager.cc index 7b66949af06..2978cbc1cb7 100644 --- a/broker/storage/src/conflict_manager.cc +++ b/broker/storage/src/conflict_manager.cc @@ -22,11 +22,11 @@ #include "bbdo/events.hh" #include "bbdo/storage/index_mapping.hh" #include "com/centreon/broker/config/applier/init.hh" -#include "com/centreon/broker/misc/perfdata.hh" #include "com/centreon/broker/multiplexing/publisher.hh" #include "com/centreon/broker/neb/events.hh" #include "com/centreon/broker/sql/mysql_result.hh" #include "com/centreon/broker/storage/internal.hh" +#include "com/centreon/common/perfdata.hh" #include "com/centreon/exceptions/msg_fmt.hh" #include "common/log_v2/log_v2.hh" diff --git a/broker/storage/src/conflict_manager_storage.cc b/broker/storage/src/conflict_manager_storage.cc index 5a75a31042f..6b66c1a5b8c 100644 --- a/broker/storage/src/conflict_manager_storage.cc +++ b/broker/storage/src/conflict_manager_storage.cc @@ -26,11 +26,11 @@ #include "bbdo/storage/remove_graph.hh" #include "bbdo/storage/status.hh" #include "com/centreon/broker/misc/misc.hh" -#include "com/centreon/broker/misc/perfdata.hh" #include "com/centreon/broker/misc/string.hh" #include "com/centreon/broker/neb/events.hh" #include "com/centreon/broker/sql/table_max_size.hh" #include "com/centreon/broker/storage/conflict_manager.hh" +#include "com/centreon/common/perfdata.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon::exceptions; @@ -259,11 +259,17 @@ void conflict_manager::_storage_process_service_status( /* Parse perfdata. */ _finish_action(-1, actions::metrics); - std::list pds{misc::parse_perfdata( + std::list pds{common::perfdata::parse_perfdata( ss.host_id, ss.service_id, ss.perf_data.c_str(), _logger_storage)}; std::deque> to_publish; for (auto& pd : pds) { + pd.resize_name(misc::string::adjust_size_utf8( + pd.name(), get_centreon_storage_metrics_col_size( + centreon_storage_metrics_metric_name))); + pd.resize_unit(misc::string::adjust_size_utf8( + pd.unit(), get_centreon_storage_metrics_col_size( + centreon_storage_metrics_unit_name))); auto it_index_cache = _metric_cache.find({index_id, pd.name()}); /* The cache does not contain this metric */ @@ -346,7 +352,8 @@ void conflict_manager::_storage_process_service_status( else need_metric_mapping = false; - pd.value_type(it_index_cache->second.type); + pd.value_type(static_cast( + it_index_cache->second.type)); _logger_storage->debug( "conflict_manager: metric {} concerning index {}, perfdata " @@ -409,7 +416,7 @@ void conflict_manager::_storage_process_service_status( ss.host_id, ss.service_id, pd.name(), ss.last_check, static_cast(ss.check_interval * _interval_length), false, metric_id, rrd_len, pd.value(), - static_cast(pd.value_type()))}; + static_cast(pd.value_type()))}; _logger_storage->debug( "conflict_manager: generating perfdata event for metric {} " "(name '{}', time {}, value {}, rrd_len {}, data_type {})", diff --git a/broker/storage/src/stream.cc b/broker/storage/src/stream.cc index cc4d0905ef5..43944a940b6 100644 --- a/broker/storage/src/stream.cc +++ b/broker/storage/src/stream.cc @@ -29,13 +29,13 @@ #include "com/centreon/broker/exceptions/shutdown.hh" #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/misc/misc.hh" -#include "com/centreon/broker/misc/perfdata.hh" #include "com/centreon/broker/multiplexing/publisher.hh" #include "com/centreon/broker/neb/host.hh" #include "com/centreon/broker/neb/instance.hh" #include "com/centreon/broker/neb/internal.hh" #include "com/centreon/broker/neb/service_status.hh" #include "com/centreon/broker/storage/conflict_manager.hh" +#include "com/centreon/common/perfdata.hh" #include "com/centreon/exceptions/msg_fmt.hh" #include "common/log_v2/log_v2.hh" diff --git a/broker/storage/test/metric.cc b/broker/storage/test/metric.cc index 8685e0edc1b..dbe4ea46401 100644 --- a/broker/storage/test/metric.cc +++ b/broker/storage/test/metric.cc @@ -21,7 +21,7 @@ #include #include #include "com/centreon/broker/io/events.hh" -#include "com/centreon/broker/misc/perfdata.hh" +#include "com/centreon/common/perfdata.hh" using namespace com::centreon::broker; @@ -60,6 +60,6 @@ TEST(StorageMetric, DefaultCtor) { ASSERT_FALSE(!m.name.empty()); ASSERT_FALSE(m.rrd_len != 0); ASSERT_FALSE(!std::isnan(m.value)); - ASSERT_FALSE(m.value_type != misc::perfdata::gauge); + ASSERT_FALSE(m.value_type != com::centreon::common::perfdata::gauge); ASSERT_FALSE(m.type() != val); } diff --git a/broker/storage/test/perfdata.cc b/broker/storage/test/perfdata.cc index 53da8f7d50e..6e3b16f40de 100644 --- a/broker/storage/test/perfdata.cc +++ b/broker/storage/test/perfdata.cc @@ -25,7 +25,7 @@ #include "com/centreon/broker/config/applier/init.hh" #include "com/centreon/broker/misc/misc.hh" -#include "com/centreon/broker/misc/perfdata.hh" +#include "com/centreon/common/perfdata.hh" using namespace com::centreon::broker; @@ -34,7 +34,7 @@ using namespace com::centreon::broker; */ TEST(StoragePerfdata, Assign) { // First object. - misc::perfdata p1; + common::perfdata p1; p1.critical(42.0); p1.critical_low(-456.032); p1.critical_mode(false); @@ -43,13 +43,13 @@ TEST(StoragePerfdata, Assign) { p1.name("foo"); p1.unit("bar"); p1.value(52189.912); - p1.value_type(misc::perfdata::counter); + p1.value_type(common::perfdata::counter); p1.warning(4548.0); p1.warning_low(42.42); p1.warning_mode(true); // Second object. - misc::perfdata p2; + common::perfdata p2; p2.critical(2345678.9672374); p2.critical_low(-3284523786.8923); p2.critical_mode(true); @@ -58,7 +58,7 @@ TEST(StoragePerfdata, Assign) { p2.name("merethis"); p2.unit("centreon"); p2.value(8374598345.234); - p2.value_type(misc::perfdata::absolute); + p2.value_type(common::perfdata::absolute); p2.warning(0.823745784); p2.warning_low(NAN); p2.warning_mode(false); @@ -75,7 +75,7 @@ TEST(StoragePerfdata, Assign) { p1.name("baz"); p1.unit("qux"); p1.value(3485.9); - p1.value_type(misc::perfdata::derive); + p1.value_type(common::perfdata::derive); p1.warning(3612.0); p1.warning_low(-987579.0); p1.warning_mode(false); @@ -89,7 +89,7 @@ TEST(StoragePerfdata, Assign) { ASSERT_FALSE(p1.name() != "baz"); ASSERT_FALSE(p1.unit() != "qux"); ASSERT_FALSE(fabs(p1.value() - 3485.9) > 0.00001); - ASSERT_FALSE(p1.value_type() != misc::perfdata::derive); + ASSERT_FALSE(p1.value_type() != common::perfdata::derive); ASSERT_FALSE(fabs(p1.warning() - 3612.0) > 0.00001); ASSERT_FALSE(fabs(p1.warning_low() + 987579.0) > 0.01); ASSERT_FALSE(p1.warning_mode()); @@ -101,7 +101,7 @@ TEST(StoragePerfdata, Assign) { ASSERT_FALSE(p2.name() != "foo"); ASSERT_FALSE(p2.unit() != "bar"); ASSERT_FALSE(fabs(p2.value() - 52189.912) > 0.00001); - ASSERT_FALSE(p2.value_type() != misc::perfdata::counter); + ASSERT_FALSE(p2.value_type() != common::perfdata::counter); ASSERT_FALSE(fabs(p2.warning() - 4548.0) > 0.00001); ASSERT_FALSE(fabs(p2.warning_low() - 42.42) > 0.00001); ASSERT_FALSE(!p2.warning_mode()); @@ -112,7 +112,7 @@ TEST(StoragePerfdata, Assign) { */ TEST(StoragePerfdata, CopyCtor) { // First object. - misc::perfdata p1; + common::perfdata p1; p1.critical(42.0); p1.critical_low(-456.032); p1.critical_mode(false); @@ -121,13 +121,13 @@ TEST(StoragePerfdata, CopyCtor) { p1.name("foo"); p1.unit("bar"); p1.value(52189.912); - p1.value_type(misc::perfdata::counter); + p1.value_type(common::perfdata::counter); p1.warning(4548.0); p1.warning_low(42.42); p1.warning_mode(true); // Second object. - misc::perfdata p2(p1); + common::perfdata p2(p1); // Change first object. p1.critical(9432.5); @@ -138,7 +138,7 @@ TEST(StoragePerfdata, CopyCtor) { p1.name("baz"); p1.unit("qux"); p1.value(3485.9); - p1.value_type(misc::perfdata::derive); + p1.value_type(common::perfdata::derive); p1.warning(3612.0); p1.warning_low(-987579.0); p1.warning_mode(false); @@ -152,7 +152,7 @@ TEST(StoragePerfdata, CopyCtor) { ASSERT_FALSE(p1.name() != "baz"); ASSERT_FALSE(p1.unit() != "qux"); ASSERT_FALSE(fabs(p1.value() - 3485.9) > 0.00001); - ASSERT_FALSE(p1.value_type() != misc::perfdata::derive); + ASSERT_FALSE(p1.value_type() != common::perfdata::derive); ASSERT_FALSE(fabs(p1.warning() - 3612.0) > 0.00001); ASSERT_FALSE(fabs(p1.warning_low() + 987579.0) > 0.01); ASSERT_FALSE(p1.warning_mode()); @@ -164,7 +164,7 @@ TEST(StoragePerfdata, CopyCtor) { ASSERT_FALSE(p2.name() != "foo"); ASSERT_FALSE(p2.unit() != "bar"); ASSERT_FALSE(fabs(p2.value() - 52189.912) > 0.00001); - ASSERT_FALSE(p2.value_type() != misc::perfdata::counter); + ASSERT_FALSE(p2.value_type() != common::perfdata::counter); ASSERT_FALSE(fabs(p2.warning() - 4548.0) > 0.00001); ASSERT_FALSE(fabs(p2.warning_low() - 42.42) > 0.00001); ASSERT_FALSE(!p2.warning_mode()); @@ -177,7 +177,7 @@ TEST(StoragePerfdata, CopyCtor) { */ TEST(StoragePerfdata, DefaultCtor) { // Build object. - misc::perfdata p; + common::perfdata p; // Check properties values. ASSERT_FALSE(!std::isnan(p.critical())); @@ -188,7 +188,7 @@ TEST(StoragePerfdata, DefaultCtor) { ASSERT_FALSE(!p.name().empty()); ASSERT_FALSE(!p.unit().empty()); ASSERT_FALSE(!std::isnan(p.value())); - ASSERT_FALSE(p.value_type() != misc::perfdata::gauge); + ASSERT_FALSE(p.value_type() != common::perfdata::gauge); ASSERT_FALSE(!std::isnan(p.warning())); ASSERT_FALSE(!std::isnan(p.warning_low())); ASSERT_FALSE(p.warning_mode()); @@ -196,9 +196,7 @@ TEST(StoragePerfdata, DefaultCtor) { class StorageParserParsePerfdata : public testing::Test { public: - void SetUp() override { - config::applier::init(0, "test_broker", 0); - } + void SetUp() override { config::applier::init(0, "test_broker", 0); } void TearDown() override { config::applier::deinit(); }; }; @@ -207,15 +205,15 @@ class StorageParserParsePerfdata : public testing::Test { // Then perfdata are returned in a list TEST_F(StorageParserParsePerfdata, Simple1) { // Parse perfdata. - std::list lst{misc::parse_perfdata( + std::list lst{common::perfdata::parse_perfdata( 0, 0, "time=2.45698s;2.000000;5.000000;0.000000;10.000000")}; // Assertions. ASSERT_EQ(lst.size(), 1u); - std::list::const_iterator it(lst.begin()); - misc::perfdata expected; + std::list::const_iterator it(lst.begin()); + common::perfdata expected; expected.name("time"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(common::perfdata::gauge); expected.value(2.45698); expected.unit("s"); expected.warning(2.0); @@ -229,15 +227,15 @@ TEST_F(StorageParserParsePerfdata, Simple1) { TEST_F(StorageParserParsePerfdata, Simple2) { // Parse perfdata. - std::list list{ - misc::parse_perfdata(0, 0, "'ABCD12E'=18.00%;15:;10:;0;100")}; + std::list list{ + common::perfdata::parse_perfdata(0, 0, "'ABCD12E'=18.00%;15:;10:;0;100")}; // Assertions. ASSERT_EQ(list.size(), 1u); - std::list::const_iterator it(list.begin()); - misc::perfdata expected; + std::list::const_iterator it(list.begin()); + common::perfdata expected; expected.name("ABCD12E"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(common::perfdata::gauge); expected.value(18.0); expected.unit("%"); expected.warning(std::numeric_limits::infinity()); @@ -251,7 +249,7 @@ TEST_F(StorageParserParsePerfdata, Simple2) { TEST_F(StorageParserParsePerfdata, Complex1) { // Parse perfdata. - std::list list{misc::parse_perfdata( + std::list list{common::perfdata::parse_perfdata( 0, 0, "time=2.45698s;;nan;;inf d[metric]=239765B/s;5;;-inf; " "infotraffic=18x;;;; a[foo]=1234;10;11: c[bar]=1234;~:10;20:30 " @@ -259,12 +257,12 @@ TEST_F(StorageParserParsePerfdata, Complex1) { // Assertions. ASSERT_EQ(list.size(), 7u); - std::list::const_iterator it(list.begin()); - misc::perfdata expected; + std::list::const_iterator it(list.begin()); + common::perfdata expected; // #1. expected.name("time"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(common::perfdata::gauge); expected.value(2.45698); expected.unit("s"); expected.max(std::numeric_limits::infinity()); @@ -272,9 +270,9 @@ TEST_F(StorageParserParsePerfdata, Complex1) { ++it; // #2. - expected = misc::perfdata(); + expected = common::perfdata(); expected.name("metric"); - expected.value_type(misc::perfdata::derive); + expected.value_type(common::perfdata::derive); expected.value(239765); expected.unit("B/s"); expected.warning(5.0); @@ -284,18 +282,18 @@ TEST_F(StorageParserParsePerfdata, Complex1) { ++it; // #3. - expected = misc::perfdata(); + expected = common::perfdata(); expected.name("infotraffic"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(common::perfdata::gauge); expected.value(18.0); expected.unit("x"); ASSERT_TRUE(expected == *it); ++it; // #4. - expected = misc::perfdata(); + expected = common::perfdata(); expected.name("foo"); - expected.value_type(misc::perfdata::absolute); + expected.value_type(common::perfdata::absolute); expected.value(1234.0); expected.warning(10.0); expected.warning_low(0.0); @@ -305,9 +303,9 @@ TEST_F(StorageParserParsePerfdata, Complex1) { ++it; // #5. - expected = misc::perfdata(); + expected = common::perfdata(); expected.name("bar"); - expected.value_type(misc::perfdata::counter); + expected.value_type(common::perfdata::counter); expected.value(1234.0); expected.warning(10.0); expected.warning_low(-std::numeric_limits::infinity()); @@ -317,9 +315,9 @@ TEST_F(StorageParserParsePerfdata, Complex1) { ++it; // #6. - expected = misc::perfdata(); + expected = common::perfdata(); expected.name("baz"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(common::perfdata::gauge); expected.value(1234.0); expected.warning(20.0); expected.warning_low(10.0); @@ -328,9 +326,9 @@ TEST_F(StorageParserParsePerfdata, Complex1) { ++it; // #7. - expected = misc::perfdata(); + expected = common::perfdata(); expected.name("q u x"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(common::perfdata::gauge); expected.value(9.0); expected.unit("queries_per_second"); expected.warning(std::numeric_limits::infinity()); @@ -349,20 +347,20 @@ TEST_F(StorageParserParsePerfdata, Complex1) { // Then the corresponding perfdata list is returned TEST_F(StorageParserParsePerfdata, Loop) { // Objects. - std::list list; + std::list list; // Loop. for (uint32_t i(0); i < 10000; ++i) { // Parse perfdata string. - list = misc::parse_perfdata( + list = common::perfdata::parse_perfdata( 0, 0, "c[time]=2.45698s;2.000000;5.000000;0.000000;10.000000"); // Assertions. ASSERT_EQ(list.size(), 1u); - std::list::const_iterator it(list.begin()); - misc::perfdata expected; + std::list::const_iterator it(list.begin()); + common::perfdata expected; expected.name("time"); - expected.value_type(misc::perfdata::counter); + expected.value_type(common::perfdata::counter); expected.value(2.45698); expected.unit("s"); expected.warning(2.0); @@ -380,7 +378,7 @@ TEST_F(StorageParserParsePerfdata, Loop) { // When parse_perfdata() is called with an invalid string TEST_F(StorageParserParsePerfdata, Incorrect1) { // Attempt to parse perfdata. - auto list{misc::parse_perfdata(0, 0, "metric1= 10 metric2=42")}; + auto list{common::perfdata::parse_perfdata(0, 0, "metric1= 10 metric2=42")}; ASSERT_EQ(list.size(), 1u); ASSERT_EQ(list.back().name(), "metric2"); ASSERT_EQ(list.back().value(), 42); @@ -390,20 +388,20 @@ TEST_F(StorageParserParsePerfdata, Incorrect1) { // When parse_perfdata() is called with a metric without value but with unit TEST_F(StorageParserParsePerfdata, Incorrect2) { // Then - auto list{misc::parse_perfdata(0, 0, "metric=kb/s")}; + auto list{common::perfdata::parse_perfdata(0, 0, "metric=kb/s")}; ASSERT_TRUE(list.empty()); } TEST_F(StorageParserParsePerfdata, LabelWithSpaces) { // Parse perfdata. - auto lst{misc::parse_perfdata(0, 0, " 'foo bar '=2s;2;5;;")}; + auto lst{common::perfdata::parse_perfdata(0, 0, " 'foo bar '=2s;2;5;;")}; // Assertions. ASSERT_EQ(lst.size(), 1u); - std::list::const_iterator it(lst.begin()); - misc::perfdata expected; + std::list::const_iterator it(lst.begin()); + common::perfdata expected; expected.name("foo bar"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(common::perfdata::gauge); expected.value(2); expected.unit("s"); expected.warning(2.0); @@ -415,14 +413,14 @@ TEST_F(StorageParserParsePerfdata, LabelWithSpaces) { TEST_F(StorageParserParsePerfdata, LabelWithSpacesMultiline) { // Parse perfdata. - auto lst{misc::parse_perfdata(0, 0, " 'foo bar '=2s;2;5;;")}; + auto lst{common::perfdata::parse_perfdata(0, 0, " 'foo bar '=2s;2;5;;")}; // Assertions. ASSERT_EQ(lst.size(), 1u); - std::list::const_iterator it(lst.begin()); - misc::perfdata expected; + std::list::const_iterator it(lst.begin()); + common::perfdata expected; expected.name("foo bar"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(common::perfdata::gauge); expected.value(2); expected.unit("s"); expected.warning(2.0); @@ -434,7 +432,7 @@ TEST_F(StorageParserParsePerfdata, LabelWithSpacesMultiline) { TEST_F(StorageParserParsePerfdata, Complex2) { // Parse perfdata. - auto list{misc::parse_perfdata( + auto list{common::perfdata::parse_perfdata( 0, 0, "' \n time'=2,45698s;;nan;;inf d[metric]=239765B/s;5;;-inf; " "g[test]=8x;;;;" @@ -443,12 +441,12 @@ TEST_F(StorageParserParsePerfdata, Complex2) { // Assertions. ASSERT_EQ(list.size(), 6u); - std::list::const_iterator it(list.begin()); - misc::perfdata expected; + std::list::const_iterator it(list.begin()); + common::perfdata expected; // #1. expected.name("time"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(common::perfdata::gauge); expected.value(2.45698); expected.unit("s"); expected.max(std::numeric_limits::infinity()); @@ -457,9 +455,9 @@ TEST_F(StorageParserParsePerfdata, Complex2) { ++it; // #2. - expected = misc::perfdata(); + expected = common::perfdata(); expected.name("metric"); - expected.value_type(misc::perfdata::derive); + expected.value_type(common::perfdata::derive); expected.value(239765); expected.unit("B/s"); expected.warning(5.0); @@ -470,9 +468,9 @@ TEST_F(StorageParserParsePerfdata, Complex2) { ++it; // #3. - expected = misc::perfdata(); + expected = common::perfdata(); expected.name("test"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(common::perfdata::gauge); expected.value(8); expected.unit("x"); ASSERT_TRUE(expected == *it); @@ -480,9 +478,9 @@ TEST_F(StorageParserParsePerfdata, Complex2) { ++it; // #4. - expected = misc::perfdata(); + expected = common::perfdata(); expected.name("infotraffic"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(common::perfdata::gauge); expected.value(18.6); expected.unit("x"); ASSERT_TRUE(expected == *it); @@ -490,9 +488,9 @@ TEST_F(StorageParserParsePerfdata, Complex2) { ++it; // #5. - expected = misc::perfdata(); + expected = common::perfdata(); expected.name("foo"); - expected.value_type(misc::perfdata::absolute); + expected.value_type(common::perfdata::absolute); expected.value(1234.17); expected.warning(10.0); expected.warning_low(0.0); @@ -503,9 +501,9 @@ TEST_F(StorageParserParsePerfdata, Complex2) { ++it; // #6. - expected = misc::perfdata(); + expected = common::perfdata(); expected.name("bar"); - expected.value_type(misc::perfdata::counter); + expected.value_type(common::perfdata::counter); expected.value(1234.147); expected.warning(10.0); expected.warning_low(-std::numeric_limits::infinity()); @@ -520,14 +518,14 @@ TEST_F(StorageParserParsePerfdata, Complex2) { // When parse_perfdata() is called with a valid perfdata string // Then perfdata are returned in a list TEST_F(StorageParserParsePerfdata, SimpleWithR) { - auto lst{misc::parse_perfdata(0, 0, "'total'=5;;;0;\r")}; + auto lst{common::perfdata::parse_perfdata(0, 0, "'total'=5;;;0;\r")}; // Assertions. ASSERT_EQ(lst.size(), 1u); - std::list::const_iterator it(lst.begin()); - misc::perfdata expected; + std::list::const_iterator it(lst.begin()); + common::perfdata expected; expected.name("total"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(common::perfdata::gauge); expected.value(5); expected.unit(""); expected.warning(NAN); @@ -543,7 +541,8 @@ TEST_F(StorageParserParsePerfdata, SimpleWithR) { // When parse_perfdata() is called with a valid perfdata string // Then perfdata are returned in a list TEST_F(StorageParserParsePerfdata, BadMetric) { - auto lst{misc::parse_perfdata(0, 0, "user1=1 user2=2 =1 user3=3")}; + auto lst{ + common::perfdata::parse_perfdata(0, 0, "user1=1 user2=2 =1 user3=3")}; // Assertions. ASSERT_EQ(lst.size(), 3u); @@ -556,7 +555,8 @@ TEST_F(StorageParserParsePerfdata, BadMetric) { } TEST_F(StorageParserParsePerfdata, BadMetric1) { - auto lst{misc::parse_perfdata(0, 0, "user1=1 user2=2 user4= user3=3")}; + auto lst{ + common::perfdata::parse_perfdata(0, 0, "user1=1 user2=2 user4= user3=3")}; // Assertions. ASSERT_EQ(lst.size(), 3u); diff --git a/broker/test/CMakeLists.txt b/broker/test/CMakeLists.txt index 7f74fab7779..489f1b60832 100644 --- a/broker/test/CMakeLists.txt +++ b/broker/test/CMakeLists.txt @@ -121,7 +121,6 @@ add_executable( ${TESTS_DIR}/misc/filesystem.cc ${TESTS_DIR}/misc/math.cc ${TESTS_DIR}/misc/misc.cc - ${TESTS_DIR}/misc/perfdata.cc ${TESTS_DIR}/misc/string.cc ${TESTS_DIR}/modules/module.cc ${TESTS_DIR}/processing/acceptor.cc diff --git a/broker/unified_sql/inc/com/centreon/broker/unified_sql/stream.hh b/broker/unified_sql/inc/com/centreon/broker/unified_sql/stream.hh index 45563a1d8cc..67a2e27fc4f 100644 --- a/broker/unified_sql/inc/com/centreon/broker/unified_sql/stream.hh +++ b/broker/unified_sql/inc/com/centreon/broker/unified_sql/stream.hh @@ -31,13 +31,13 @@ #include "bbdo/neb.pb.h" #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/io/stream.hh" -#include "com/centreon/broker/misc/perfdata.hh" #include "com/centreon/broker/misc/shared_mutex.hh" #include "com/centreon/broker/sql/mysql_multi_insert.hh" #include "com/centreon/broker/unified_sql/bulk_bind.hh" #include "com/centreon/broker/unified_sql/bulk_queries.hh" #include "com/centreon/broker/unified_sql/rebuilder.hh" #include "com/centreon/broker/unified_sql/stored_timestamp.hh" +#include "com/centreon/common/perfdata.hh" namespace com::centreon::broker { namespace unified_sql { diff --git a/broker/unified_sql/src/stream.cc b/broker/unified_sql/src/stream.cc index 63d8423f646..eaaa899f879 100644 --- a/broker/unified_sql/src/stream.cc +++ b/broker/unified_sql/src/stream.cc @@ -29,13 +29,13 @@ #include "com/centreon/broker/cache/global_cache.hh" #include "com/centreon/broker/config/applier/state.hh" #include "com/centreon/broker/exceptions/shutdown.hh" -#include "com/centreon/broker/misc/perfdata.hh" #include "com/centreon/broker/multiplexing/publisher.hh" #include "com/centreon/broker/neb/events.hh" #include "com/centreon/broker/sql/mysql_bulk_stmt.hh" #include "com/centreon/broker/sql/mysql_result.hh" #include "com/centreon/broker/stats/center.hh" #include "com/centreon/broker/unified_sql/internal.hh" +#include "com/centreon/common/perfdata.hh" #include "com/centreon/exceptions/msg_fmt.hh" #include "common/log_v2/log_v2.hh" @@ -909,7 +909,8 @@ void stream::process_stop(const std::shared_ptr& d) { */ void stream::remove_graphs(const std::shared_ptr& d) { SPDLOG_LOGGER_INFO(_logger_sql, "remove graphs call"); - asio::post(com::centreon::common::pool::instance().io_context(), [this, data = d] { + asio::post(com::centreon::common::pool::instance().io_context(), [this, + data = d] { mysql ms(_dbcfg); bbdo::pb_remove_graphs* ids = static_cast(data.get()); diff --git a/broker/unified_sql/src/stream_storage.cc b/broker/unified_sql/src/stream_storage.cc index 806540f1f15..9a0e8333756 100644 --- a/broker/unified_sql/src/stream_storage.cc +++ b/broker/unified_sql/src/stream_storage.cc @@ -31,13 +31,13 @@ #include "bbdo/storage/status.hh" #include "com/centreon/broker/cache/global_cache.hh" #include "com/centreon/broker/misc/misc.hh" -#include "com/centreon/broker/misc/perfdata.hh" #include "com/centreon/broker/misc/shared_mutex.hh" #include "com/centreon/broker/misc/string.hh" #include "com/centreon/broker/neb/events.hh" #include "com/centreon/broker/sql/table_max_size.hh" #include "com/centreon/broker/unified_sql/internal.hh" #include "com/centreon/broker/unified_sql/stream.hh" +#include "com/centreon/common/perfdata.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon::exceptions; @@ -150,12 +150,19 @@ void stream::_unified_sql_process_pb_service_status( /* Parse perfdata. */ _finish_action(-1, actions::metrics); - std::list pds{misc::parse_perfdata( + std::list pds{common::perfdata::parse_perfdata( ss.host_id(), ss.service_id(), ss.perfdata().c_str(), _logger_sto)}; std::deque> to_publish; for (auto& pd : pds) { misc::read_lock rlck(_metric_cache_m); + pd.resize_name(misc::string::adjust_size_utf8( + pd.name(), get_centreon_storage_metrics_col_size( + centreon_storage_metrics_metric_name))); + pd.resize_unit(misc::string::adjust_size_utf8( + pd.unit(), get_centreon_storage_metrics_col_size( + centreon_storage_metrics_unit_name))); + auto it_index_cache = _metric_cache.find({index_id, pd.name()}); /* The cache does not contain this metric */ @@ -242,7 +249,7 @@ void stream::_unified_sql_process_pb_service_status( else need_metric_mapping = false; - pd.value_type(static_cast( + pd.value_type(static_cast( it_index_cache->second.type)); SPDLOG_LOGGER_DEBUG( @@ -520,12 +527,19 @@ void stream::_unified_sql_process_service_status( /* Parse perfdata. */ _finish_action(-1, actions::metrics); - std::list pds{misc::parse_perfdata( + std::list pds{common::perfdata::parse_perfdata( ss.host_id, ss.service_id, ss.perf_data.c_str(), _logger_sto)}; std::deque> to_publish; for (auto& pd : pds) { misc::read_lock rlck(_metric_cache_m); + pd.resize_name(misc::string::adjust_size_utf8( + pd.name(), get_centreon_storage_metrics_col_size( + centreon_storage_metrics_metric_name))); + pd.resize_unit(misc::string::adjust_size_utf8( + pd.unit(), get_centreon_storage_metrics_col_size( + centreon_storage_metrics_unit_name))); + auto it_index_cache = _metric_cache.find({index_id, pd.name()}); /* The cache does not contain this metric */ @@ -612,7 +626,7 @@ void stream::_unified_sql_process_service_status( else need_metric_mapping = false; - pd.value_type(static_cast( + pd.value_type(static_cast( it_index_cache->second.type)); SPDLOG_LOGGER_DEBUG( @@ -711,7 +725,7 @@ void stream::_unified_sql_process_service_status( ss.host_id, ss.service_id, pd.name(), ss.last_check, static_cast(ss.check_interval * _interval_length), false, metric_id, rrd_len, pd.value(), - static_cast(pd.value_type()))}; + static_cast(pd.value_type()))}; SPDLOG_LOGGER_DEBUG( _logger_sto, "unified sql: generating perfdata event for metric {} " diff --git a/broker/unified_sql/test/metric.cc b/broker/unified_sql/test/metric.cc index 23d778c065a..dfd449d54fd 100644 --- a/broker/unified_sql/test/metric.cc +++ b/broker/unified_sql/test/metric.cc @@ -21,8 +21,8 @@ #include #include #include "com/centreon/broker/io/events.hh" -#include "com/centreon/broker/misc/perfdata.hh" #include "com/centreon/broker/unified_sql/internal.hh" +#include "com/centreon/common/perfdata.hh" using namespace com::centreon::broker; @@ -61,6 +61,6 @@ TEST(UnifiedSqlMetric, DefaultCtor) { ASSERT_FALSE(!m.name.empty()); ASSERT_FALSE(m.rrd_len != 0); ASSERT_FALSE(!std::isnan(m.value)); - ASSERT_FALSE(m.value_type != misc::perfdata::gauge); + ASSERT_FALSE(m.value_type != com::centreon::common::perfdata::gauge); ASSERT_FALSE(m.type() != val); } diff --git a/broker/unified_sql/test/perfdata.cc b/broker/unified_sql/test/perfdata.cc index 474c3bd37be..f2edbb234ea 100644 --- a/broker/unified_sql/test/perfdata.cc +++ b/broker/unified_sql/test/perfdata.cc @@ -25,7 +25,7 @@ #include "com/centreon/broker/config/applier/init.hh" #include "com/centreon/broker/misc/misc.hh" -#include "com/centreon/broker/misc/perfdata.hh" +#include "com/centreon/common/perfdata.hh" using namespace com::centreon::broker; @@ -34,7 +34,7 @@ using namespace com::centreon::broker; */ TEST(UnifiedSqlPerfdata, Assign) { // First object. - misc::perfdata p1; + common::perfdata p1; p1.critical(42.0); p1.critical_low(-456.032); p1.critical_mode(false); @@ -43,13 +43,13 @@ TEST(UnifiedSqlPerfdata, Assign) { p1.name("foo"); p1.unit("bar"); p1.value(52189.912); - p1.value_type(misc::perfdata::counter); + p1.value_type(common::perfdata::counter); p1.warning(4548.0); p1.warning_low(42.42); p1.warning_mode(true); // Second object. - misc::perfdata p2; + common::perfdata p2; p2.critical(2345678.9672374); p2.critical_low(-3284523786.8923); p2.critical_mode(true); @@ -58,7 +58,7 @@ TEST(UnifiedSqlPerfdata, Assign) { p2.name("merethis"); p2.unit("centreon"); p2.value(8374598345.234); - p2.value_type(misc::perfdata::absolute); + p2.value_type(common::perfdata::absolute); p2.warning(0.823745784); p2.warning_low(NAN); p2.warning_mode(false); @@ -75,7 +75,7 @@ TEST(UnifiedSqlPerfdata, Assign) { p1.name("baz"); p1.unit("qux"); p1.value(3485.9); - p1.value_type(misc::perfdata::derive); + p1.value_type(common::perfdata::derive); p1.warning(3612.0); p1.warning_low(-987579.0); p1.warning_mode(false); @@ -89,7 +89,7 @@ TEST(UnifiedSqlPerfdata, Assign) { ASSERT_FALSE(p1.name() != "baz"); ASSERT_FALSE(p1.unit() != "qux"); ASSERT_FALSE(fabs(p1.value() - 3485.9) > 0.00001); - ASSERT_FALSE(p1.value_type() != misc::perfdata::derive); + ASSERT_FALSE(p1.value_type() != common::perfdata::derive); ASSERT_FALSE(fabs(p1.warning() - 3612.0) > 0.00001); ASSERT_FALSE(fabs(p1.warning_low() + 987579.0) > 0.01); ASSERT_FALSE(p1.warning_mode()); @@ -101,7 +101,7 @@ TEST(UnifiedSqlPerfdata, Assign) { ASSERT_FALSE(p2.name() != "foo"); ASSERT_FALSE(p2.unit() != "bar"); ASSERT_FALSE(fabs(p2.value() - 52189.912) > 0.00001); - ASSERT_FALSE(p2.value_type() != misc::perfdata::counter); + ASSERT_FALSE(p2.value_type() != common::perfdata::counter); ASSERT_FALSE(fabs(p2.warning() - 4548.0) > 0.00001); ASSERT_FALSE(fabs(p2.warning_low() - 42.42) > 0.00001); ASSERT_FALSE(!p2.warning_mode()); @@ -112,7 +112,7 @@ TEST(UnifiedSqlPerfdata, Assign) { */ TEST(UnifiedSqlPerfdata, CopyCtor) { // First object. - misc::perfdata p1; + common::perfdata p1; p1.critical(42.0); p1.critical_low(-456.032); p1.critical_mode(false); @@ -121,13 +121,13 @@ TEST(UnifiedSqlPerfdata, CopyCtor) { p1.name("foo"); p1.unit("bar"); p1.value(52189.912); - p1.value_type(misc::perfdata::counter); + p1.value_type(common::perfdata::counter); p1.warning(4548.0); p1.warning_low(42.42); p1.warning_mode(true); // Second object. - misc::perfdata p2(p1); + common::perfdata p2(p1); // Change first object. p1.critical(9432.5); @@ -138,7 +138,7 @@ TEST(UnifiedSqlPerfdata, CopyCtor) { p1.name("baz"); p1.unit("qux"); p1.value(3485.9); - p1.value_type(misc::perfdata::derive); + p1.value_type(common::perfdata::derive); p1.warning(3612.0); p1.warning_low(-987579.0); p1.warning_mode(false); @@ -152,7 +152,7 @@ TEST(UnifiedSqlPerfdata, CopyCtor) { ASSERT_FALSE(p1.name() != "baz"); ASSERT_FALSE(p1.unit() != "qux"); ASSERT_FALSE(fabs(p1.value() - 3485.9) > 0.00001); - ASSERT_FALSE(p1.value_type() != misc::perfdata::derive); + ASSERT_FALSE(p1.value_type() != common::perfdata::derive); ASSERT_FALSE(fabs(p1.warning() - 3612.0) > 0.00001); ASSERT_FALSE(fabs(p1.warning_low() + 987579.0) > 0.01); ASSERT_FALSE(p1.warning_mode()); @@ -164,7 +164,7 @@ TEST(UnifiedSqlPerfdata, CopyCtor) { ASSERT_FALSE(p2.name() != "foo"); ASSERT_FALSE(p2.unit() != "bar"); ASSERT_FALSE(fabs(p2.value() - 52189.912) > 0.00001); - ASSERT_FALSE(p2.value_type() != misc::perfdata::counter); + ASSERT_FALSE(p2.value_type() != common::perfdata::counter); ASSERT_FALSE(fabs(p2.warning() - 4548.0) > 0.00001); ASSERT_FALSE(fabs(p2.warning_low() - 42.42) > 0.00001); ASSERT_FALSE(!p2.warning_mode()); @@ -177,7 +177,7 @@ TEST(UnifiedSqlPerfdata, CopyCtor) { */ TEST(UnifiedSqlPerfdata, DefaultCtor) { // Build object. - misc::perfdata p; + common::perfdata p; // Check properties values. ASSERT_FALSE(!std::isnan(p.critical())); @@ -188,7 +188,7 @@ TEST(UnifiedSqlPerfdata, DefaultCtor) { ASSERT_FALSE(!p.name().empty()); ASSERT_FALSE(!p.unit().empty()); ASSERT_FALSE(!std::isnan(p.value())); - ASSERT_FALSE(p.value_type() != misc::perfdata::gauge); + ASSERT_FALSE(p.value_type() != common::perfdata::gauge); ASSERT_FALSE(!std::isnan(p.warning())); ASSERT_FALSE(!std::isnan(p.warning_low())); ASSERT_FALSE(p.warning_mode()); @@ -196,9 +196,7 @@ TEST(UnifiedSqlPerfdata, DefaultCtor) { class UnifiedSqlParserParsePerfdata : public testing::Test { public: - void SetUp() override { - config::applier::init(0, "test_broker", 0); - } + void SetUp() override { config::applier::init(0, "test_broker", 0); } void TearDown() override { config::applier::deinit(); }; }; @@ -206,15 +204,15 @@ class UnifiedSqlParserParsePerfdata : public testing::Test { // When parse_perfdata() is called with a valid perfdata string // Then perfdata are returned in a list TEST_F(UnifiedSqlParserParsePerfdata, Simple1) { - auto lst{misc::parse_perfdata( + auto lst{common::perfdata::parse_perfdata( 0, 0, "time=2.45698s;2.000000;5.000000;0.000000;10.000000")}; // Assertions. ASSERT_EQ(lst.size(), 1u); - std::list::const_iterator it(lst.begin()); - misc::perfdata expected; + std::list::const_iterator it(lst.begin()); + common::perfdata expected; expected.name("time"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(common::perfdata::gauge); expected.value(2.45698); expected.unit("s"); expected.warning(2.0); @@ -227,14 +225,15 @@ TEST_F(UnifiedSqlParserParsePerfdata, Simple1) { } TEST_F(UnifiedSqlParserParsePerfdata, Simple2) { - auto list{misc::parse_perfdata(0, 0, "'ABCD12E'=18.00%;15:;10:;0;100")}; + auto list{ + common::perfdata::parse_perfdata(0, 0, "'ABCD12E'=18.00%;15:;10:;0;100")}; // Assertions. ASSERT_EQ(list.size(), 1u); - std::list::const_iterator it(list.begin()); - misc::perfdata expected; + std::list::const_iterator it(list.begin()); + common::perfdata expected; expected.name("ABCD12E"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(common::perfdata::gauge); expected.value(18.0); expected.unit("%"); expected.warning(std::numeric_limits::infinity()); @@ -247,7 +246,7 @@ TEST_F(UnifiedSqlParserParsePerfdata, Simple2) { } TEST_F(UnifiedSqlParserParsePerfdata, Complex1) { - auto list{misc::parse_perfdata( + auto list{common::perfdata::parse_perfdata( 0, 0, "time=2.45698s;;nan;;inf d[metric]=239765B/s;5;;-inf; " "infotraffic=18x;;;; a[foo]=1234;10;11: c[bar]=1234;~:10;20:30 " @@ -255,12 +254,12 @@ TEST_F(UnifiedSqlParserParsePerfdata, Complex1) { // Assertions. ASSERT_EQ(list.size(), 7u); - std::list::const_iterator it(list.begin()); - misc::perfdata expected; + std::list::const_iterator it(list.begin()); + common::perfdata expected; // #1. expected.name("time"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(common::perfdata::gauge); expected.value(2.45698); expected.unit("s"); expected.max(std::numeric_limits::infinity()); @@ -268,9 +267,9 @@ TEST_F(UnifiedSqlParserParsePerfdata, Complex1) { ++it; // #2. - expected = misc::perfdata(); + expected = common::perfdata(); expected.name("metric"); - expected.value_type(misc::perfdata::derive); + expected.value_type(common::perfdata::derive); expected.value(239765); expected.unit("B/s"); expected.warning(5.0); @@ -280,18 +279,18 @@ TEST_F(UnifiedSqlParserParsePerfdata, Complex1) { ++it; // #3. - expected = misc::perfdata(); + expected = common::perfdata(); expected.name("infotraffic"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(common::perfdata::gauge); expected.value(18.0); expected.unit("x"); ASSERT_TRUE(expected == *it); ++it; // #4. - expected = misc::perfdata(); + expected = common::perfdata(); expected.name("foo"); - expected.value_type(misc::perfdata::absolute); + expected.value_type(common::perfdata::absolute); expected.value(1234.0); expected.warning(10.0); expected.warning_low(0.0); @@ -301,9 +300,9 @@ TEST_F(UnifiedSqlParserParsePerfdata, Complex1) { ++it; // #5. - expected = misc::perfdata(); + expected = common::perfdata(); expected.name("bar"); - expected.value_type(misc::perfdata::counter); + expected.value_type(common::perfdata::counter); expected.value(1234.0); expected.warning(10.0); expected.warning_low(-std::numeric_limits::infinity()); @@ -313,9 +312,9 @@ TEST_F(UnifiedSqlParserParsePerfdata, Complex1) { ++it; // #6. - expected = misc::perfdata(); + expected = common::perfdata(); expected.name("baz"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(common::perfdata::gauge); expected.value(1234.0); expected.warning(20.0); expected.warning_low(10.0); @@ -324,9 +323,9 @@ TEST_F(UnifiedSqlParserParsePerfdata, Complex1) { ++it; // #7. - expected = misc::perfdata(); + expected = common::perfdata(); expected.name("q u x"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(common::perfdata::gauge); expected.value(9.0); expected.unit("queries_per_second"); expected.warning(std::numeric_limits::infinity()); @@ -344,20 +343,20 @@ TEST_F(UnifiedSqlParserParsePerfdata, Complex1) { // When parse_perfdata() is called multiple time with valid strings // Then the corresponding perfdata list is returned TEST_F(UnifiedSqlParserParsePerfdata, Loop) { - std::list list; + std::list list; // Loop. for (uint32_t i(0); i < 10000; ++i) { // Parse perfdata string. - list = misc::parse_perfdata( + list = common::perfdata::parse_perfdata( 0, 0, "c[time]=2.45698s;2.000000;5.000000;0.000000;10.000000"); // Assertions. ASSERT_EQ(list.size(), 1u); - std::list::const_iterator it(list.begin()); - misc::perfdata expected; + std::list::const_iterator it(list.begin()); + common::perfdata expected; expected.name("time"); - expected.value_type(misc::perfdata::counter); + expected.value_type(common::perfdata::counter); expected.value(2.45698); expected.unit("s"); expected.warning(2.0); @@ -376,7 +375,7 @@ TEST_F(UnifiedSqlParserParsePerfdata, Loop) { // Then it throws a unified_sql::exceptions::perfdata TEST_F(UnifiedSqlParserParsePerfdata, Incorrect1) { // Attempt to parse perfdata. - auto list{misc::parse_perfdata(0, 0, "metric1= 10 metric2=42")}; + auto list{common::perfdata::parse_perfdata(0, 0, "metric1= 10 metric2=42")}; ASSERT_EQ(list.size(), 1u); ASSERT_EQ(list.back().name(), "metric2"); ASSERT_EQ(list.back().value(), 42); @@ -386,19 +385,19 @@ TEST_F(UnifiedSqlParserParsePerfdata, Incorrect1) { // When parse_perfdata() is called with a metric without value but with unit // Then it throws a unified_sql::exceptions::perfdata TEST_F(UnifiedSqlParserParsePerfdata, Incorrect2) { - auto list{misc::parse_perfdata(0, 0, "metric=kb/s")}; + auto list{common::perfdata::parse_perfdata(0, 0, "metric=kb/s")}; ASSERT_TRUE(list.empty()); } TEST_F(UnifiedSqlParserParsePerfdata, LabelWithSpaces) { - auto lst{misc::parse_perfdata(0, 0, " 'foo bar '=2s;2;5;;")}; + auto lst{common::perfdata::parse_perfdata(0, 0, " 'foo bar '=2s;2;5;;")}; // Assertions. ASSERT_EQ(lst.size(), 1u); - std::list::const_iterator it(lst.begin()); - misc::perfdata expected; + std::list::const_iterator it(lst.begin()); + common::perfdata expected; expected.name("foo bar"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(common::perfdata::gauge); expected.value(2); expected.unit("s"); expected.warning(2.0); @@ -409,14 +408,14 @@ TEST_F(UnifiedSqlParserParsePerfdata, LabelWithSpaces) { } TEST_F(UnifiedSqlParserParsePerfdata, LabelWithSpacesMultiline) { - auto lst{misc::parse_perfdata(0, 0, " 'foo bar '=2s;2;5;;")}; + auto lst{common::perfdata::parse_perfdata(0, 0, " 'foo bar '=2s;2;5;;")}; // Assertions. ASSERT_EQ(lst.size(), 1u); - std::list::const_iterator it(lst.begin()); - misc::perfdata expected; + std::list::const_iterator it(lst.begin()); + common::perfdata expected; expected.name("foo bar"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(common::perfdata::gauge); expected.value(2); expected.unit("s"); expected.warning(2.0); @@ -427,7 +426,7 @@ TEST_F(UnifiedSqlParserParsePerfdata, LabelWithSpacesMultiline) { } TEST_F(UnifiedSqlParserParsePerfdata, Complex2) { - auto list{misc::parse_perfdata( + auto list{common::perfdata::parse_perfdata( 0, 0, "' \n time'=2,45698s;;nan;;inf d[metric]=239765B/s;5;;-inf; " "g[test]=8x;;;;" @@ -436,12 +435,12 @@ TEST_F(UnifiedSqlParserParsePerfdata, Complex2) { // Assertions. ASSERT_EQ(list.size(), 6u); - std::list::const_iterator it(list.begin()); - misc::perfdata expected; + std::list::const_iterator it(list.begin()); + common::perfdata expected; // #1. expected.name("time"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(common::perfdata::gauge); expected.value(2.45698); expected.unit("s"); expected.max(std::numeric_limits::infinity()); @@ -450,9 +449,9 @@ TEST_F(UnifiedSqlParserParsePerfdata, Complex2) { ++it; // #2. - expected = misc::perfdata(); + expected = common::perfdata(); expected.name("metric"); - expected.value_type(misc::perfdata::derive); + expected.value_type(common::perfdata::derive); expected.value(239765); expected.unit("B/s"); expected.warning(5.0); @@ -463,9 +462,9 @@ TEST_F(UnifiedSqlParserParsePerfdata, Complex2) { ++it; // #3. - expected = misc::perfdata(); + expected = common::perfdata(); expected.name("test"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(common::perfdata::gauge); expected.value(8); expected.unit("x"); ASSERT_TRUE(expected == *it); @@ -473,9 +472,9 @@ TEST_F(UnifiedSqlParserParsePerfdata, Complex2) { ++it; // #4. - expected = misc::perfdata(); + expected = common::perfdata(); expected.name("infotraffic"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(common::perfdata::gauge); expected.value(18.6); expected.unit("x"); ASSERT_TRUE(expected == *it); @@ -483,9 +482,9 @@ TEST_F(UnifiedSqlParserParsePerfdata, Complex2) { ++it; // #5. - expected = misc::perfdata(); + expected = common::perfdata(); expected.name("foo"); - expected.value_type(misc::perfdata::absolute); + expected.value_type(common::perfdata::absolute); expected.value(1234.17); expected.warning(10.0); expected.warning_low(0.0); @@ -496,9 +495,9 @@ TEST_F(UnifiedSqlParserParsePerfdata, Complex2) { ++it; // #6. - expected = misc::perfdata(); + expected = common::perfdata(); expected.name("bar"); - expected.value_type(misc::perfdata::counter); + expected.value_type(common::perfdata::counter); expected.value(1234.147); expected.warning(10.0); expected.warning_low(-std::numeric_limits::infinity()); @@ -513,14 +512,14 @@ TEST_F(UnifiedSqlParserParsePerfdata, Complex2) { // When parse_perfdata() is called with a valid perfdata string // Then perfdata are returned in a list TEST_F(UnifiedSqlParserParsePerfdata, SimpleWithR) { - auto lst{misc::parse_perfdata(0, 0, "'total'=5;;;0;\r")}; + auto lst{common::perfdata::parse_perfdata(0, 0, "'total'=5;;;0;\r")}; // Assertions. ASSERT_EQ(lst.size(), 1u); - std::list::const_iterator it(lst.begin()); - misc::perfdata expected; + std::list::const_iterator it(lst.begin()); + common::perfdata expected; expected.name("total"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(common::perfdata::gauge); expected.value(5); expected.unit(""); expected.warning(NAN); @@ -536,7 +535,8 @@ TEST_F(UnifiedSqlParserParsePerfdata, SimpleWithR) { // When parse_perfdata() is called with a valid perfdata string // Then perfdata are returned in a list TEST_F(UnifiedSqlParserParsePerfdata, BadMetric) { - auto lst{misc::parse_perfdata(0, 0, "user1=1 user2=2 =1 user3=3")}; + auto lst{ + common::perfdata::parse_perfdata(0, 0, "user1=1 user2=2 =1 user3=3")}; // Assertions. ASSERT_EQ(lst.size(), 3u); @@ -549,7 +549,8 @@ TEST_F(UnifiedSqlParserParsePerfdata, BadMetric) { } TEST_F(UnifiedSqlParserParsePerfdata, BadMetric1) { - auto lst{misc::parse_perfdata(0, 0, "user1=1 user2=2 user4= user3=3")}; + auto lst{ + common::perfdata::parse_perfdata(0, 0, "user1=1 user2=2 user4= user3=3")}; // Assertions. ASSERT_EQ(lst.size(), 3u); diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt index fd8633b6256..8d06a60276e 100644 --- a/common/CMakeLists.txt +++ b/common/CMakeLists.txt @@ -45,7 +45,9 @@ add_custom_command( # Set sources. set(SOURCES ${SRC_DIR}/hex_dump.cc + ${SRC_DIR}/perfdata.cc ${SRC_DIR}/pool.cc + ${SRC_DIR}/process.cc ${SRC_DIR}/process_stat.cc ${SRC_DIR}/process_stat.pb.cc ${SRC_DIR}/process_stat.grpc.pb.cc diff --git a/common/doc/common-doc.md b/common/doc/common-doc.md index f0614cf68e7..38959b0b41f 100644 --- a/common/doc/common-doc.md +++ b/common/doc/common-doc.md @@ -4,6 +4,7 @@ * [Pool](#Pool) * [Grpc](#Grpc) +* [Process](#Process) ## Pool @@ -50,3 +51,68 @@ my_grpc_client::my_grpc_client(const grpc_config::pointer& conf) ``` + +## Process + +The goal of this class is to provide an base class to execute asynchronously process according to asio library. +It relies on boost v2 process library. +All is asynchronous, child process end of life is notified to on_process_end method. It's the same for stdin write and stdout/err read. + +You have 4 constructors that allow user to pass executable arguments in four different ways. On of them accept a string command line with exe and arguments + +In order to use this, you have to inherit from this class + +An example of usage: +```c++ +class process_wait : public process { + std::condition_variable _cond; + std::string _stdout; + std::string _stderr; + + public: + void on_stdout_read(const boost::system::error_code& err, + size_t nb_read) override { + if (!err) { + _stdout += std::string_view(_stdout_read_buffer, nb_read); + } + process::on_stdout_read(err, nb_read); + } + + void on_stderr_read(const boost::system::error_code& err, + size_t nb_read) override { + if (!err) { + _stderr += std::string_view(_stderr_read_buffer, nb_read); + } + process::on_stderr_read(err, nb_read); + } + + void on_process_end(const boost::system::error_code& err, + int raw_exit_status) override { + process::on_process_end(err, raw_exit_status); + _cond.notify_one(); + } + + template + process_wait(const std::shared_ptr& io_context, + const std::shared_ptr& logger, + const std::string_view& exe_path, + const std::initializer_list& args) + : process(io_context, logger, exe_path, args) {} + + process_wait(const std::shared_ptr& io_context, + const std::shared_ptr& logger, + const std::string_view& cmd_line) + : process(io_context, logger, cmd_line) {} + + const std::string& get_stdout() const { return _stdout; } + const std::string& get_stderr() const { return _stderr; } + + void wait() { + std::mutex dummy; + std::unique_lock l(dummy); + _cond.wait(l); + } +}; + +``` + diff --git a/common/inc/com/centreon/common/perfdata.hh b/common/inc/com/centreon/common/perfdata.hh new file mode 100644 index 00000000000..beaef41610b --- /dev/null +++ b/common/inc/com/centreon/common/perfdata.hh @@ -0,0 +1,86 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#ifndef CENTREON_COMMON_PERFDATA_HH +#define CENTREON_COMMON_PERFDATA_HH + +namespace com::centreon::common { +class perfdata { + public: + enum data_type { gauge = 0, counter, derive, absolute, automatic }; + + private: + double _critical; + double _critical_low; + bool _critical_mode; + double _max; + double _min; + std::string _name; + std::string _unit; + double _value; + data_type _value_type; + double _warning; + double _warning_low; + bool _warning_mode; + + public: + static std::list parse_perfdata( + uint32_t host_id, + uint32_t service_id, + const char* str, + const std::shared_ptr& logger); + + perfdata(); + ~perfdata() noexcept = default; + + double critical() const { return _critical; } + void critical(double c) { _critical = c; } + double critical_low() const { return _critical_low; } + void critical_low(double c) { _critical_low = c; } + bool critical_mode() const { return _critical_mode; } + void critical_mode(bool val) { _critical_mode = val; } + double max() const { return _max; } + void max(double val) { _max = val; } + double min() const { return _min; } + void min(double val) { _min = val; } + const std::string& name() const { return _name; } + void name(const std::string&& val) { _name = val; } + void resize_name(size_t new_size); + const std::string& unit() const { return _unit; } + void resize_unit(size_t new_size); + void unit(const std::string&& val) { _unit = val; } + double value() const { return _value; } + void value(double val) { _value = val; } + data_type value_type() const { return _value_type; }; + void value_type(data_type val) { _value_type = val; } + double warning() const { return _warning; } + void warning(double val) { _warning = val; } + double warning_low() const { return _warning_low; } + void warning_low(double val) { _warning_low = val; } + bool warning_mode() const { return _warning_mode; } + void warning_mode(bool val) { _warning_mode = val; } +}; + +} // namespace com::centreon::common + +bool operator==(com::centreon::common::perfdata const& left, + com::centreon::common::perfdata const& right); +bool operator!=(com::centreon::common::perfdata const& left, + com::centreon::common::perfdata const& right); + +#endif diff --git a/common/inc/com/centreon/common/process.hh b/common/inc/com/centreon/common/process.hh new file mode 100644 index 00000000000..bc9ef7902bb --- /dev/null +++ b/common/inc/com/centreon/common/process.hh @@ -0,0 +1,194 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#ifndef CENTREON_AGENT_CHECK_PROCESS_HH +#define CENTREON_AGENT_CHECK_PROCESS_HH + +namespace com::centreon::common { + +namespace detail { +// here to limit included files +struct boost_process; +} // namespace detail + +/** + * @brief This class allow to exec a process asynchronously. + * It's a base class. If you want to get stdin and stdout returned data, you + * must inherit from this and override on_stdout_read and on_stderr_read + * You can call start_process at any moment, if a process is already running, + * it's killed + * As we can start a process at any moment, all handlers take a caller in + * parameter, if this caller is not equal to current _proc, we do nothing. + * When completion methods like on_stdout_read are called, _protect is already + * locked + */ +class process : public std::enable_shared_from_this { + std::shared_ptr _io_context; + std::shared_ptr _logger; + + std::string _exe_path; + std::vector _args; + + std::deque> _stdin_write_queue + ABSL_GUARDED_BY(_protect); + bool _write_pending = false ABSL_GUARDED_BY(_protect); + + std::shared_ptr _proc ABSL_GUARDED_BY(_protect); + + int _exit_status = 0; + + absl::Mutex _protect; + + void stdin_write_no_lock(const std::shared_ptr& data) + ABSL_EXCLUSIVE_LOCKS_REQUIRED(_protect); + void stdin_write(const std::shared_ptr& data); + + void stdout_read(); + void stderr_read(); + + protected: + char _stdout_read_buffer[0x1000] ABSL_GUARDED_BY(_protect); + char _stderr_read_buffer[0x1000] ABSL_GUARDED_BY(_protect); + + virtual void on_stdout_read(const boost::system::error_code& err, + size_t nb_read) + ABSL_EXCLUSIVE_LOCKS_REQUIRED(_protect); + virtual void on_stderr_read(const boost::system::error_code& err, + size_t nb_read) + ABSL_EXCLUSIVE_LOCKS_REQUIRED(_protect); + + virtual void on_process_end(const boost::system::error_code& err, + int raw_exit_status) + ABSL_EXCLUSIVE_LOCKS_REQUIRED(_protect); + + virtual void on_stdin_write(const boost::system::error_code& err) + ABSL_EXCLUSIVE_LOCKS_REQUIRED(_protect); + + public: + template + process(const std::shared_ptr& io_context, + const std::shared_ptr& logger, + const std::string_view& exe_path, + string_iterator arg_begin, + string_iterator arg_end); + + template + process(const std::shared_ptr& io_context, + const std::shared_ptr& logger, + const std::string_view& exe_path, + const args_container& args); + + template + process(const std::shared_ptr& io_context, + const std::shared_ptr& logger, + const std::string_view& exe_path, + const std::initializer_list& args); + + process(const std::shared_ptr& io_context, + const std::shared_ptr& logger, + const std::string_view& cmd_line); + + virtual ~process() = default; + + template + void write_to_stdin(const string_class& content); + + void start_process(); + + void kill(); + + int get_exit_status() const { return _exit_status; } + const std::string& get_exe_path() const { return _exe_path; } +}; + +/** + * @brief Construct a new process::process object + * + * @tparam string_iterator + * @param io_context + * @param logger + * @param exe_path path of executable without arguments + * @param arg_begin iterator to first argument + * @param arg_end iterator after the last argument + */ +template +process::process(const std::shared_ptr& io_context, + const std::shared_ptr& logger, + const std::string_view& exe_path, + string_iterator arg_begin, + string_iterator arg_end) + : _io_context(io_context), + _logger(logger), + _exe_path(exe_path), + _args(arg_begin, arg_end) {} + +/** + * @brief Construct a new process::process object + * + * @tparam args_container + * @param io_context + * @param logger + * @param exe_path path of executable without argument + * @param args container of arguments + */ +template +process::process(const std::shared_ptr& io_context, + const std::shared_ptr& logger, + const std::string_view& exe_path, + const args_container& args) + : _io_context(io_context), + _logger(logger), + _exe_path(exe_path), + _args(args) {} + +/** + * @brief Construct a new process::process object + * + * @tparam string_type string_class such as string_view, char* string or + * anything else that can be used to construct a std::string + * @param io_context + * @param logger + * @param exe_path path of executable without argument + * @param args brace of arguments {"--flag1", "arg1", "-c", "arg2"} + */ +template +process::process(const std::shared_ptr& io_context, + const std::shared_ptr& logger, + const std::string_view& exe_path, + const std::initializer_list& args) + : _io_context(io_context), _logger(logger), _exe_path(exe_path) { + _args.reserve(args.size()); + for (const auto& str : args) { + _args.emplace_back(str); + } +} + +/** + * @brief write string to child process stdin + * + * @tparam string_class such as string_view, char* string or anything else that + * can be used to construct a std::string + * @param content + */ +template +void process::write_to_stdin(const string_class& content) { + stdin_write(std::make_shared(content)); +} + +} // namespace com::centreon::common +#endif diff --git a/common/precomp_inc/precomp.hh b/common/precomp_inc/precomp.hh index 2d25e38fab8..0b20d35411a 100644 --- a/common/precomp_inc/precomp.hh +++ b/common/precomp_inc/precomp.hh @@ -25,8 +25,11 @@ #include #include #include +#include +#include #include #include +#include #include #include #include @@ -37,6 +40,7 @@ #include #include #include +#include #include #include @@ -48,7 +52,6 @@ #include "com/centreon/exceptions/msg_fmt.hh" - namespace asio = boost::asio; #endif // CCB_HTTP_CLIENT_PRECOMP_HH diff --git a/broker/core/src/misc/parse_perfdata.cc b/common/src/perfdata.cc similarity index 64% rename from broker/core/src/misc/parse_perfdata.cc rename to common/src/perfdata.cc index 5ea51f8c4e6..fab01b147f5 100644 --- a/broker/core/src/misc/parse_perfdata.cc +++ b/common/src/perfdata.cc @@ -16,20 +16,94 @@ * For more information : contact@centreon.com */ -#include -#include #include -#include "bbdo/storage/metric.hh" -#include "com/centreon/broker/misc/misc.hh" -#include "com/centreon/broker/misc/string.hh" -#include "com/centreon/broker/sql/table_max_size.hh" -#include "common/log_v2/log_v2.hh" +#include "perfdata.hh" -using namespace com::centreon::broker; -using namespace com::centreon::broker::misc; +using namespace com::centreon::common; -using log_v2 = com::centreon::common::log_v2::log_v2; +/** + * Default constructor. + */ +perfdata::perfdata() + : _critical(NAN), + _critical_low(NAN), + _critical_mode(false), + _max(NAN), + _min(NAN), + _value(NAN), + _value_type(gauge), + _warning(NAN), + _warning_low(NAN), + _warning_mode(false) {} + +/** + * Comparison helper. + * + * @param[in] a First value. + * @param[in] b Second value. + * + * @return true if a and b are equal. + */ +static inline bool float_equal(float a, float b) { + return (std::isnan(a) && std::isnan(b)) || + (std::isinf(a) && std::isinf(b) && + std::signbit(a) == std::signbit(b)) || + (std::isfinite(a) && std::isfinite(b) && + fabs(a - b) <= 0.01 * fabs(a)); +} + +/** + * Compare two perfdata objects. + * + * @param[in] left First object. + * @param[in] right Second object. + * + * @return true if both objects are equal. + */ +bool operator==(perfdata const& left, perfdata const& right) { + return float_equal(left.critical(), right.critical()) && + float_equal(left.critical_low(), right.critical_low()) && + left.critical_mode() == right.critical_mode() && + float_equal(left.max(), right.max()) && + float_equal(left.min(), right.min()) && left.name() == right.name() && + left.unit() == right.unit() && + float_equal(left.value(), right.value()) && + left.value_type() == right.value_type() && + float_equal(left.warning(), right.warning()) && + float_equal(left.warning_low(), right.warning_low()) && + left.warning_mode() == right.warning_mode(); +} + +/** + * Compare two perfdata objects. + * + * @param[in] left First object. + * @param[in] right Second object. + * + * @return true if both objects are inequal. + */ +bool operator!=(perfdata const& left, perfdata const& right) { + return !(left == right); +} +/** + * @brief in case of db insertions we need to ensure that name can be stored in + * table With it, you can reduce name size + * + * @param new_size + */ +void perfdata::resize_name(size_t new_size) { + _name.resize(new_size); +} + +/** + * @brief idem of resize_name + * + * @param new_size + */ +void perfdata::resize_unit(size_t new_size) { + _unit.resize(new_size); +} /** * Extract a real value from a perfdata string. @@ -39,32 +113,31 @@ using log_v2 = com::centreon::common::log_v2::log_v2; * * @return Extracted real value if successful, NaN otherwise. */ -static inline float extract_float(char const** str, bool skip = true) { +static inline float extract_float(char const*& str, bool skip = true) { float retval; char* tmp; - if (isspace(**str)) + if (isspace(*str)) retval = NAN; else { - char const* comma{strchr(*str, ',')}; + char const* comma{strchr(str, ',')}; if (comma) { /* In case of comma decimal separator, we duplicate the number and * replace the comma by a point. */ size_t t = strcspn(comma, " \t\n\r;"); - char* nb = strndup(*str, (comma - *str) + t); - nb[comma - *str] = '.'; - retval = strtof(nb, &tmp); - if (nb == tmp) + std::string nb(str, (comma - str) + t); + nb[comma - str] = '.'; + retval = strtod(nb.c_str(), &tmp); + if (nb.c_str() == tmp) retval = NAN; - *str = *str + (tmp - nb); - free(nb); + str = str + (tmp - nb.c_str()); } else { - retval = strtof(*str, &tmp); - if (*str == tmp) + retval = strtof(str, &tmp); + if (str == tmp) retval = NAN; - *str = tmp; + str = tmp; } - if (skip && (**str == ';')) - ++*str; + if (skip && (*str == ';')) + ++str; } return retval; } @@ -81,33 +154,33 @@ static inline float extract_float(char const** str, bool skip = true) { static inline void extract_range(float* low, float* high, bool* inclusive, - char const** str) { + char const*& str) { // Exclusive range ? - if ((**str) == '@') { + if (*str == '@') { *inclusive = true; - ++*str; + ++str; } else *inclusive = false; // Low threshold value. float low_value; - if ('~' == **str) { + if ('~' == *str) { low_value = -std::numeric_limits::infinity(); - ++*str; + ++str; } else low_value = extract_float(str); // High threshold value. float high_value; - if (**str != ':') { + if (*str != ':') { high_value = low_value; if (!std::isnan(low_value)) low_value = 0.0; } else { - ++*str; - char const* ptr(*str); + ++str; + char const* ptr(str); high_value = extract_float(str); - if (std::isnan(high_value) && ((*str == ptr) || (*str == (ptr + 1)))) + if (std::isnan(high_value) && ((str == ptr) || (str == (ptr + 1)))) high_value = std::numeric_limits::infinity(); } @@ -125,7 +198,7 @@ static inline void extract_range(float* low, * * @return A list of perfdata */ -std::list misc::parse_perfdata( +std::list perfdata::parse_perfdata( uint32_t host_id, uint32_t service_id, const char* str, @@ -192,25 +265,21 @@ std::list misc::parse_perfdata( --end; if (strncmp(s, "a[", 2) == 0) { s += 2; - p.value_type(perfdata::absolute); + p._value_type = perfdata::data_type::absolute; } else if (strncmp(s, "c[", 2) == 0) { s += 2; - p.value_type(perfdata::counter); + p._value_type = perfdata::data_type::counter; } else if (strncmp(s, "d[", 2) == 0) { s += 2; - p.value_type(perfdata::derive); + p._value_type = perfdata::data_type::derive; } else if (strncmp(s, "g[", 2) == 0) { s += 2; - p.value_type(perfdata::gauge); + p._value_type = perfdata::data_type::gauge; } } if (end - s + 1 > 0) { - std::string name(s, end - s + 1); - name.resize(misc::string::adjust_size_utf8( - name, get_centreon_storage_metrics_col_size( - centreon_storage_metrics_metric_name))); - p.name(std::move(name)); + p._name.assign(s, end - s + 1); } else { logger->error("In service {}, metric name empty before '{}...'", id(), fmt::string_view(s, 10)); @@ -236,7 +305,7 @@ std::list misc::parse_perfdata( } // Extract value. - p.value(extract_float(const_cast(&tmp), false)); + p.value(extract_float(tmp, false)); if (std::isnan(p.value())) { int i; for (i = 0; i < 10 && tmp[i]; i++) @@ -253,13 +322,7 @@ std::list misc::parse_perfdata( // Extract unit. size_t t = strcspn(tmp, " \t\n\r;"); - { - std::string unit(tmp, t); - unit.resize(misc::string::adjust_size_utf8( - unit, get_centreon_storage_metrics_col_size( - centreon_storage_metrics_unit_name))); - p.unit(std::move(unit)); - } + p._unit.assign(tmp, t); tmp += t; if (*tmp == ';') ++tmp; @@ -269,8 +332,7 @@ std::list misc::parse_perfdata( float warning_high; float warning_low; bool warning_mode; - extract_range(&warning_low, &warning_high, &warning_mode, - const_cast(&tmp)); + extract_range(&warning_low, &warning_high, &warning_mode, tmp); p.warning(warning_high); p.warning_low(warning_low); p.warning_mode(warning_mode); @@ -281,18 +343,17 @@ std::list misc::parse_perfdata( float critical_high; float critical_low; bool critical_mode; - extract_range(&critical_low, &critical_high, &critical_mode, - const_cast(&tmp)); + extract_range(&critical_low, &critical_high, &critical_mode, tmp); p.critical(critical_high); p.critical_low(critical_low); p.critical_mode(critical_mode); } // Extract minimum. - p.min(extract_float(const_cast(&tmp))); + p.min(extract_float(tmp)); // Extract maximum. - p.max(extract_float(const_cast(&tmp))); + p.max(extract_float(tmp)); // Log new perfdata. logger->debug( diff --git a/common/src/process.cc b/common/src/process.cc new file mode 100644 index 00000000000..c66e1cbcc21 --- /dev/null +++ b/common/src/process.cc @@ -0,0 +1,321 @@ +/* + * Copyright 2024 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ + +#include +#include + +#include "process.hh" + +namespace proc = boost::process::v2; + +namespace com::centreon::common::detail { +/** + * @brief each time we start a process we create this struct witch contains all + * sub-process objects + * + */ +struct boost_process { + boost_process(asio::io_context& io_context, + const std::string& exe_path, + const std::vector& args) + : stdout(io_context), + stderr(io_context), + stdin(io_context), + proc(io_context, + exe_path, + args, + proc::process_stdio{stdin, stdout, stderr}) {} + + asio::readable_pipe stdout; + asio::readable_pipe stderr; + asio::writable_pipe stdin; + proc::process proc; +}; +} // namespace com::centreon::common::detail + +using namespace com::centreon::common; + +/** + * @brief Construct a new process::process object + * + * @param io_context + * @param logger + * @param cmd_line cmd line split (the first element is the path of the + * executable) + */ +process::process(const std::shared_ptr& io_context, + const std::shared_ptr& logger, + const std::string_view& cmd_line) + : _io_context(io_context), _logger(logger) { + auto split_res = + absl::StrSplit(cmd_line, absl::ByAnyChar(" \t"), absl::SkipEmpty()); + if (split_res.begin() == split_res.end()) { + SPDLOG_LOGGER_ERROR(_logger, "empty command line:\"{}\"", cmd_line); + throw exceptions::msg_fmt("empty command line:\"{}\"", cmd_line); + } + auto field_iter = split_res.begin(); + + _exe_path = *field_iter++; + for (; field_iter != split_res.end(); ++field_iter) { + _args.emplace_back(*field_iter); + } +} + +/** + * @brief start a new process, if a previous one is running, it's killed + * In this function, we start child process and stdout, stderr asynchronous read + * we also start an asynchronous read on process fd to be aware of child process + * termination + */ +void process::start_process() { + SPDLOG_LOGGER_DEBUG(_logger, "start process: {}", _exe_path); + absl::MutexLock l(&_protect); + _stdin_write_queue.clear(); + _write_pending = false; + + try { + _proc = + std::make_shared(*_io_context, _exe_path, _args); + _proc->proc.async_wait( + [me = shared_from_this(), current = _proc]( + const boost::system::error_code& err, int raw_exit_status) { + absl::MutexLock l(&me->_protect); + if (current != me->_proc) { + return; + } + me->on_process_end(err, raw_exit_status); + }); + } catch (const std::exception& e) { + SPDLOG_LOGGER_ERROR(_logger, "fail to start {}: {}", _exe_path, e.what()); + throw; + } + stdout_read(); + stderr_read(); +} + +/** + * @brief called when child process end + * + * @param err + * @param raw_exit_status end status of the process + */ +void process::on_process_end(const boost::system::error_code& err, + int raw_exit_status) { + if (err) { + SPDLOG_LOGGER_ERROR(_logger, "fail async_wait of {}: {}", _exe_path, + err.message()); + _exit_status = -1; + } else { + _exit_status = proc::evaluate_exit_code(raw_exit_status); + SPDLOG_LOGGER_DEBUG(_logger, "end of process {}, exit_status={}", _exe_path, + _exit_status); + } +} + +/** + * @brief kill child process + * + */ +void process::kill() { + absl::MutexLock l(&_protect); + if (_proc) { + boost::system::error_code err; + _proc->proc.terminate(err); + _proc.reset(); + } +} + +/** + * @brief write some data to child process stdin, if a write is pending, data is + * pushed to a queue + * + * @param data + */ +void process::stdin_write(const std::shared_ptr& data) { + absl::MutexLock l(&_protect); + stdin_write_no_lock(data); +} + +/** + * @brief asynchronously write some data to child process stdin, if a write is + * pending, data is pushed to a queue + * + * @param data + */ +void process::stdin_write_no_lock(const std::shared_ptr& data) { + if (!_proc) { + SPDLOG_LOGGER_ERROR(_logger, "stdin_write process {} not started", + _exe_path); + throw exceptions::msg_fmt("stdin_write process {} not started", _exe_path); + } + if (_write_pending) { + _stdin_write_queue.push_back(data); + } else { + try { + _write_pending = true; + _proc->stdin.async_write_some( + asio::buffer(*data), + [me = shared_from_this(), caller = _proc, data]( + const boost::system::error_code& err, size_t nb_written) { + absl::MutexLock l(&me->_protect); + if (caller != me->_proc) { + return; + } + me->on_stdin_write(err); + }); + } catch (const std::exception& e) { + _write_pending = false; + SPDLOG_LOGGER_ERROR(_logger, + "stdin_write process {} fail to write to stdin {}", + _exe_path, e.what()); + } + } +} + +/** + * @brief stdin write handler + * if data remains in queue, we send them + * if override process::on_stdin_write must be called + * + * @param err + */ +void process::on_stdin_write(const boost::system::error_code& err) { + _write_pending = false; + + if (err) { + if (err == asio::error::eof) { + SPDLOG_LOGGER_DEBUG(_logger, + "on_stdin_write process {} fail to write to stdin {}", + _exe_path, err.message()); + } else { + SPDLOG_LOGGER_ERROR(_logger, + "on_stdin_write process {} fail to write to stdin {}", + _exe_path, err.message()); + } + return; + } + + if (!_stdin_write_queue.empty()) { + std::shared_ptr to_send = _stdin_write_queue.front(); + _stdin_write_queue.pop_front(); + stdin_write_no_lock(to_send); + } +} + +/** + * @brief asynchronous read from child process stdout + * + */ +void process::stdout_read() { + if (_proc) { + try { + _proc->stdout.async_read_some( + asio::buffer(_stdout_read_buffer), + [me = shared_from_this(), caller = _proc]( + const boost::system::error_code& err, size_t nb_read) { + absl::MutexLock l(&me->_protect); + if (caller != me->_proc) { + return; + } + me->on_stdout_read(err, nb_read); + }); + } catch (const std::exception& e) { + _io_context->post([me = shared_from_this(), caller = _proc]() { + absl::MutexLock l(&me->_protect); + me->on_stdout_read(std::make_error_code(std::errc::broken_pipe), 0); + }); + } + } +} + +/** + * @brief stdout read handler + * This method or his override is called with _protect locked. + * If override process::on_stdout_read must be called + * + * @param err + * @param nb_read + */ +void process::on_stdout_read(const boost::system::error_code& err, + size_t nb_read) { + if (err) { + if (err == asio::error::eof) { + SPDLOG_LOGGER_DEBUG(_logger, "fail read from stdout of process {}: {}", + _exe_path, err.message()); + } else { + SPDLOG_LOGGER_ERROR(_logger, "fail read from stdout of process {}: {}", + _exe_path, err.message()); + } + return; + } + SPDLOG_LOGGER_TRACE(_logger, " process: {} read from stdout: {}", _exe_path, + std::string_view(_stdout_read_buffer, nb_read)); + stdout_read(); +} + +/** + * @brief asynchronous read from child process stderr + * + */ +void process::stderr_read() { + if (_proc) { + try { + _proc->stderr.async_read_some( + asio::buffer(_stderr_read_buffer), + [me = shared_from_this(), caller = _proc]( + const boost::system::error_code& err, size_t nb_read) { + absl::MutexLock l(&me->_protect); + if (caller != me->_proc) { + return; + } + me->on_stderr_read(err, nb_read); + }); + } catch (const std::exception& e) { + _io_context->post([me = shared_from_this(), caller = _proc]() { + absl::MutexLock l(&me->_protect); + me->on_stderr_read(std::make_error_code(std::errc::broken_pipe), 0); + }); + } + } +} + +/** + * @brief stderr read handler + * This method or his override is called with _protect locked. + * If override process::on_stderr_read must be called + * + * @param err + * @param nb_read + */ +void process::on_stderr_read(const boost::system::error_code& err, + size_t nb_read) { + if (err) { + if (err == asio::error::eof) { + SPDLOG_LOGGER_DEBUG(_logger, "fail read from stderr of process {}: {}", + _exe_path, err.message()); + } else { + SPDLOG_LOGGER_ERROR(_logger, "fail read from stderr of process {}: {}", + _exe_path, err.message()); + } + } else { + SPDLOG_LOGGER_TRACE(_logger, " process: {} read from stdout: {}", _exe_path, + std::string_view(_stderr_read_buffer, nb_read)); + stderr_read(); + } +} diff --git a/common/tests/CMakeLists.txt b/common/tests/CMakeLists.txt index b7ce413dfe9..1bd982a7743 100644 --- a/common/tests/CMakeLists.txt +++ b/common/tests/CMakeLists.txt @@ -21,6 +21,8 @@ add_executable(ut_common hex_dump_test.cc log_v2/log_v2.cc node_allocator_test.cc + perfdata_test.cc + process_test.cc rapidjson_helper_test.cc test_main.cc ${TESTS_SOURCES}) diff --git a/broker/core/test/misc/perfdata.cc b/common/tests/perfdata_test.cc similarity index 63% rename from broker/core/test/misc/perfdata.cc rename to common/tests/perfdata_test.cc index be3f6071038..25ac9d30cff 100644 --- a/broker/core/test/misc/perfdata.cc +++ b/common/tests/perfdata_test.cc @@ -17,24 +17,21 @@ * */ -#include #include - +#include #include -#include "com/centreon/broker/config/applier/init.hh" -#include "com/centreon/broker/misc/misc.hh" -#include "common/log_v2/log_v2.hh" +#include "perfdata.hh" -using namespace com::centreon::broker; -using com::centreon::common::log_v2::log_v2; +using namespace com::centreon; +using namespace com::centreon::common; /** * Check that the perfdata assignment operator works properly. */ -TEST(MiscPerfdata, Assign) { +TEST(PerfData, Assign) { // First object. - misc::perfdata p1; + perfdata p1; p1.critical(42.0); p1.critical_low(-456.032); p1.critical_mode(false); @@ -43,13 +40,13 @@ TEST(MiscPerfdata, Assign) { p1.name("foo"); p1.unit("bar"); p1.value(52189.912); - p1.value_type(misc::perfdata::counter); + p1.value_type(perfdata::counter); p1.warning(4548.0); p1.warning_low(42.42); p1.warning_mode(true); // Second object. - misc::perfdata p2; + perfdata p2; p2.critical(2345678.9672374); p2.critical_low(-3284523786.8923); p2.critical_mode(true); @@ -58,7 +55,7 @@ TEST(MiscPerfdata, Assign) { p2.name("merethis"); p2.unit("centreon"); p2.value(8374598345.234); - p2.value_type(misc::perfdata::absolute); + p2.value_type(perfdata::absolute); p2.warning(0.823745784); p2.warning_low(NAN); p2.warning_mode(false); @@ -75,44 +72,44 @@ TEST(MiscPerfdata, Assign) { p1.name("baz"); p1.unit("qux"); p1.value(3485.9); - p1.value_type(misc::perfdata::derive); + p1.value_type(perfdata::derive); p1.warning(3612.0); p1.warning_low(-987579.0); p1.warning_mode(false); // Check objects properties values. - ASSERT_FALSE(fabs(p1.critical() - 9432.5f) > 0.00001f); - ASSERT_TRUE(fabs(p1.critical_low() - 1000.0001f) < 0.0001f); + ASSERT_FALSE(fabs(p1.critical() - 9432.5) > 0.00001); + ASSERT_FALSE(fabs(p1.critical_low() - 1000.0001) > 0.00001); ASSERT_FALSE(!p1.critical_mode()); - ASSERT_FALSE(fabs(p1.max() - 123.0f) > 0.00001f); - ASSERT_TRUE(fabs(p1.min() - 843.876f) < 0.0001f); + ASSERT_FALSE(fabs(p1.max() - 123.0) > 0.00001); + ASSERT_FALSE(fabs(p1.min() - 843.876) > 0.00001); ASSERT_FALSE(p1.name() != "baz"); ASSERT_FALSE(p1.unit() != "qux"); - ASSERT_TRUE(fabs(p1.value() - 3485.9f) < 0.0001f); - ASSERT_FALSE(p1.value_type() != misc::perfdata::derive); - ASSERT_FALSE(fabs(p1.warning() - 3612.0f) > 0.00001f); - ASSERT_FALSE(fabs(p1.warning_low() + 987579.0f) > 0.01f); + ASSERT_FALSE(fabs(p1.value() - 3485.9) > 0.00001); + ASSERT_FALSE(p1.value_type() != perfdata::derive); + ASSERT_FALSE(fabs(p1.warning() - 3612.0) > 0.00001); + ASSERT_FALSE(fabs(p1.warning_low() + 987579.0) > 0.01); ASSERT_FALSE(p1.warning_mode()); - ASSERT_FALSE(fabs(p2.critical() - 42.0f) > 0.00001f); - ASSERT_FALSE(fabs(p2.critical_low() + 456.032f) > 0.00001f); + ASSERT_FALSE(fabs(p2.critical() - 42.0) > 0.00001); + ASSERT_FALSE(fabs(p2.critical_low() + 456.032) > 0.00001); ASSERT_FALSE(p2.critical_mode()); - ASSERT_FALSE(fabs(p2.max() - 76.3f) > 0.00001f); - ASSERT_FALSE(fabs(p2.min() - 567.2f) > 0.00001f); + ASSERT_FALSE(fabs(p2.max() - 76.3) > 0.00001); + ASSERT_FALSE(fabs(p2.min() - 567.2) > 0.00001); ASSERT_FALSE(p2.name() != "foo"); ASSERT_FALSE(p2.unit() != "bar"); - ASSERT_FALSE(fabs(p2.value() - 52189.912f) > 0.00001f); - ASSERT_FALSE(p2.value_type() != misc::perfdata::counter); - ASSERT_FALSE(fabs(p2.warning() - 4548.0f) > 0.00001f); - ASSERT_FALSE(fabs(p2.warning_low() - 42.42f) > 0.00001f); + ASSERT_FALSE(fabs(p2.value() - 52189.912) > 0.00001); + ASSERT_FALSE(p2.value_type() != perfdata::counter); + ASSERT_FALSE(fabs(p2.warning() - 4548.0) > 0.00001); + ASSERT_FALSE(fabs(p2.warning_low() - 42.42) > 0.00001); ASSERT_FALSE(!p2.warning_mode()); } /** * Check that the perfdata copy constructor works properly. */ -TEST(MiscPerfdata, CopyCtor) { +TEST(PerfData, CopyCtor) { // First object. - misc::perfdata p1; + perfdata p1; p1.critical(42.0); p1.critical_low(-456.032); p1.critical_mode(false); @@ -121,13 +118,13 @@ TEST(MiscPerfdata, CopyCtor) { p1.name("foo"); p1.unit("bar"); p1.value(52189.912); - p1.value_type(misc::perfdata::counter); + p1.value_type(perfdata::counter); p1.warning(4548.0); p1.warning_low(42.42); p1.warning_mode(true); // Second object. - misc::perfdata p2(p1); + perfdata p2(p1); // Change first object. p1.critical(9432.5); @@ -138,35 +135,35 @@ TEST(MiscPerfdata, CopyCtor) { p1.name("baz"); p1.unit("qux"); p1.value(3485.9); - p1.value_type(misc::perfdata::derive); + p1.value_type(perfdata::derive); p1.warning(3612.0); p1.warning_low(-987579.0); p1.warning_mode(false); // Check objects properties values. - ASSERT_FALSE(fabs(p1.critical() - 9432.5f) > 0.00001f); - ASSERT_FALSE(fabs(p1.critical_low() - 1000.0001f) > 0.00001f); + ASSERT_FALSE(fabs(p1.critical() - 9432.5) > 0.00001); + ASSERT_FALSE(fabs(p1.critical_low() - 1000.0001) > 0.00001); ASSERT_FALSE(!p1.critical_mode()); - ASSERT_FALSE(fabs(p1.max() - 123.0f) > 0.00001f); - ASSERT_FALSE(fabs(p1.min() - 843.876f) > 0.00001f); + ASSERT_FALSE(fabs(p1.max() - 123.0) > 0.00001); + ASSERT_FALSE(fabs(p1.min() - 843.876) > 0.00001); ASSERT_FALSE(p1.name() != "baz"); ASSERT_FALSE(p1.unit() != "qux"); - ASSERT_FALSE(fabs(p1.value() - 3485.9f) > 0.00001f); - ASSERT_FALSE(p1.value_type() != misc::perfdata::derive); - ASSERT_FALSE(fabs(p1.warning() - 3612.0f) > 0.00001f); - ASSERT_FALSE(fabs(p1.warning_low() + 987579.0f) > 0.01f); + ASSERT_FALSE(fabs(p1.value() - 3485.9) > 0.00001); + ASSERT_FALSE(p1.value_type() != perfdata::derive); + ASSERT_FALSE(fabs(p1.warning() - 3612.0) > 0.00001); + ASSERT_FALSE(fabs(p1.warning_low() + 987579.0) > 0.01); ASSERT_FALSE(p1.warning_mode()); - ASSERT_FALSE(fabs(p2.critical() - 42.0f) > 0.00001f); - ASSERT_FALSE(fabs(p2.critical_low() + 456.032f) > 0.00001f); + ASSERT_FALSE(fabs(p2.critical() - 42.0) > 0.00001); + ASSERT_FALSE(fabs(p2.critical_low() + 456.032) > 0.00001); ASSERT_FALSE(p2.critical_mode()); - ASSERT_FALSE(fabs(p2.max() - 76.3f) > 0.00001f); - ASSERT_FALSE(fabs(p2.min() - 567.2f) > 0.00001f); + ASSERT_FALSE(fabs(p2.max() - 76.3) > 0.00001); + ASSERT_FALSE(fabs(p2.min() - 567.2) > 0.00001); ASSERT_FALSE(p2.name() != "foo"); ASSERT_FALSE(p2.unit() != "bar"); - ASSERT_FALSE(fabs(p2.value() - 52189.912f) > 0.00001f); - ASSERT_FALSE(p2.value_type() != misc::perfdata::counter); - ASSERT_FALSE(fabs(p2.warning() - 4548.0f) > 0.00001f); - ASSERT_FALSE(fabs(p2.warning_low() - 42.42f) > 0.00001f); + ASSERT_FALSE(fabs(p2.value() - 52189.912) > 0.00001); + ASSERT_FALSE(p2.value_type() != perfdata::counter); + ASSERT_FALSE(fabs(p2.warning() - 4548.0) > 0.00001); + ASSERT_FALSE(fabs(p2.warning_low() - 42.42) > 0.00001); ASSERT_FALSE(!p2.warning_mode()); } @@ -175,9 +172,9 @@ TEST(MiscPerfdata, CopyCtor) { * * @return 0 on success. */ -TEST(MiscPerfdata, DefaultCtor) { +TEST(PerfData, DefaultCtor) { // Build object. - misc::perfdata p; + perfdata p; // Check properties values. ASSERT_FALSE(!std::isnan(p.critical())); @@ -188,38 +185,34 @@ TEST(MiscPerfdata, DefaultCtor) { ASSERT_FALSE(!p.name().empty()); ASSERT_FALSE(!p.unit().empty()); ASSERT_FALSE(!std::isnan(p.value())); - ASSERT_FALSE(p.value_type() != misc::perfdata::gauge); + ASSERT_FALSE(p.value_type() != perfdata::gauge); ASSERT_FALSE(!std::isnan(p.warning())); ASSERT_FALSE(!std::isnan(p.warning_low())); ASSERT_FALSE(p.warning_mode()); } -class MiscParserParsePerfdata : public testing::Test { +class PerfdataParser : public testing::Test { protected: - std::shared_ptr _logger; - - public: - void SetUp() override { - config::applier::init(0, "test_broker", 0); - _logger = log_v2::instance().get(log_v2::PERFDATA); - } - void TearDown() override { config::applier::deinit(); }; + static std::shared_ptr _logger; }; +std::shared_ptr PerfdataParser::_logger = + spdlog::stdout_color_mt("perfdata_test"); + // Given a misc::parser object // When parse_perfdata() is called with a valid perfdata string // Then perfdata are returned in a list -TEST_F(MiscParserParsePerfdata, Simple1) { +TEST_F(PerfdataParser, Simple1) { // Parse perfdata. - std::list lst{misc::parse_perfdata( + std::list lst{common::perfdata::parse_perfdata( 0, 0, "time=2.45698s;2.000000;5.000000;0.000000;10.000000", _logger)}; // Assertions. ASSERT_EQ(lst.size(), 1u); - std::list::const_iterator it(lst.begin()); - misc::perfdata expected; + std::list::const_iterator it(lst.begin()); + perfdata expected; expected.name("time"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(perfdata::gauge); expected.value(2.45698); expected.unit("s"); expected.warning(2.0); @@ -231,17 +224,17 @@ TEST_F(MiscParserParsePerfdata, Simple1) { ASSERT_TRUE(expected == *it); } -TEST_F(MiscParserParsePerfdata, Simple2) { +TEST_F(PerfdataParser, Simple2) { // Parse perfdata. - std::list list{ - misc::parse_perfdata(0, 0, "'ABCD12E'=18.00%;15:;10:;0;100", _logger)}; + std::list list{common::perfdata::parse_perfdata( + 0, 0, "'ABCD12E'=18.00%;15:;10:;0;100", _logger)}; // Assertions. ASSERT_EQ(list.size(), 1u); - std::list::const_iterator it(list.begin()); - misc::perfdata expected; + std::list::const_iterator it(list.begin()); + perfdata expected; expected.name("ABCD12E"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(perfdata::gauge); expected.value(18.0); expected.unit("%"); expected.warning(std::numeric_limits::infinity()); @@ -253,9 +246,9 @@ TEST_F(MiscParserParsePerfdata, Simple2) { ASSERT_TRUE(expected == *it); } -TEST_F(MiscParserParsePerfdata, Complex1) { +TEST_F(PerfdataParser, Complex1) { // Parse perfdata. - std::list list{misc::parse_perfdata( + std::list list{perfdata::parse_perfdata( 0, 0, "time=2.45698s;;nan;;inf d[metric]=239765B/s;5;;-inf; " "infotraffic=18x;;;; a[foo]=1234;10;11: c[bar]=1234;~:10;20:30 " @@ -264,12 +257,12 @@ TEST_F(MiscParserParsePerfdata, Complex1) { // Assertions. ASSERT_EQ(list.size(), 7u); - std::list::const_iterator it(list.begin()); - misc::perfdata expected; + std::list::const_iterator it(list.begin()); + perfdata expected; // #1. expected.name("time"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(perfdata::gauge); expected.value(2.45698); expected.unit("s"); expected.max(std::numeric_limits::infinity()); @@ -277,9 +270,9 @@ TEST_F(MiscParserParsePerfdata, Complex1) { ++it; // #2. - expected = misc::perfdata(); + expected = perfdata(); expected.name("metric"); - expected.value_type(misc::perfdata::derive); + expected.value_type(perfdata::derive); expected.value(239765); expected.unit("B/s"); expected.warning(5.0); @@ -289,18 +282,18 @@ TEST_F(MiscParserParsePerfdata, Complex1) { ++it; // #3. - expected = misc::perfdata(); + expected = perfdata(); expected.name("infotraffic"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(perfdata::gauge); expected.value(18.0); expected.unit("x"); ASSERT_TRUE(expected == *it); ++it; // #4. - expected = misc::perfdata(); + expected = perfdata(); expected.name("foo"); - expected.value_type(misc::perfdata::absolute); + expected.value_type(perfdata::absolute); expected.value(1234.0); expected.warning(10.0); expected.warning_low(0.0); @@ -310,9 +303,9 @@ TEST_F(MiscParserParsePerfdata, Complex1) { ++it; // #5. - expected = misc::perfdata(); + expected = perfdata(); expected.name("bar"); - expected.value_type(misc::perfdata::counter); + expected.value_type(perfdata::counter); expected.value(1234.0); expected.warning(10.0); expected.warning_low(-std::numeric_limits::infinity()); @@ -322,9 +315,9 @@ TEST_F(MiscParserParsePerfdata, Complex1) { ++it; // #6. - expected = misc::perfdata(); + expected = perfdata(); expected.name("baz"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(perfdata::gauge); expected.value(1234.0); expected.warning(20.0); expected.warning_low(10.0); @@ -333,9 +326,9 @@ TEST_F(MiscParserParsePerfdata, Complex1) { ++it; // #7. - expected = misc::perfdata(); + expected = perfdata(); expected.name("q u x"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(perfdata::gauge); expected.value(9.0); expected.unit("queries_per_second"); expected.warning(std::numeric_limits::infinity()); @@ -352,22 +345,22 @@ TEST_F(MiscParserParsePerfdata, Complex1) { // Given a misc::parser object // When parse_perfdata() is called multiple time with valid strings // Then the corresponding perfdata list is returned -TEST_F(MiscParserParsePerfdata, Loop) { +TEST_F(PerfdataParser, Loop) { // Objects. - std::list list; + std::list list; // Loop. for (uint32_t i(0); i < 10000; ++i) { // Parse perfdata string. - list = misc::parse_perfdata( + list = common::perfdata::parse_perfdata( 0, 0, "c[time]=2.45698s;2.000000;5.000000;0.000000;10.000000", _logger); // Assertions. ASSERT_EQ(list.size(), 1u); - std::list::const_iterator it(list.begin()); - misc::perfdata expected; + std::list::const_iterator it(list.begin()); + perfdata expected; expected.name("time"); - expected.value_type(misc::perfdata::counter); + expected.value_type(perfdata::counter); expected.value(2.45698); expected.unit("s"); expected.warning(2.0); @@ -383,9 +376,10 @@ TEST_F(MiscParserParsePerfdata, Loop) { // Given a misc::parser object // When parse_perfdata() is called with an invalid string -TEST_F(MiscParserParsePerfdata, Incorrect1) { +TEST_F(PerfdataParser, Incorrect1) { // Attempt to parse perfdata. - auto list{misc::parse_perfdata(0, 0, "metric1= 10 metric2=42", _logger)}; + auto list{common::perfdata::parse_perfdata(0, 0, "metric1= 10 metric2=42", + _logger)}; ASSERT_EQ(list.size(), 1u); ASSERT_EQ(list.back().name(), "metric2"); ASSERT_EQ(list.back().value(), 42); @@ -393,22 +387,23 @@ TEST_F(MiscParserParsePerfdata, Incorrect1) { // Given a misc::parser object // When parse_perfdata() is called with a metric without value but with unit -TEST_F(MiscParserParsePerfdata, Incorrect2) { +TEST_F(PerfdataParser, Incorrect2) { // Then - auto list{misc::parse_perfdata(0, 0, "metric=kb/s", _logger)}; + auto list{common::perfdata::parse_perfdata(0, 0, "metric=kb/s", _logger)}; ASSERT_TRUE(list.empty()); } -TEST_F(MiscParserParsePerfdata, LabelWithSpaces) { +TEST_F(PerfdataParser, LabelWithSpaces) { // Parse perfdata. - auto lst{misc::parse_perfdata(0, 0, " 'foo bar '=2s;2;5;;", _logger)}; + auto lst{common::perfdata::parse_perfdata(0, 0, " 'foo bar '=2s;2;5;;", + _logger)}; // Assertions. ASSERT_EQ(lst.size(), 1u); - std::list::const_iterator it(lst.begin()); - misc::perfdata expected; + std::list::const_iterator it(lst.begin()); + perfdata expected; expected.name("foo bar"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(perfdata::gauge); expected.value(2); expected.unit("s"); expected.warning(2.0); @@ -418,16 +413,17 @@ TEST_F(MiscParserParsePerfdata, LabelWithSpaces) { ASSERT_TRUE(expected == *it); } -TEST_F(MiscParserParsePerfdata, LabelWithSpacesMultiline) { +TEST_F(PerfdataParser, LabelWithSpacesMultiline) { // Parse perfdata. - auto lst{misc::parse_perfdata(0, 0, " 'foo bar '=2s;2;5;;", _logger)}; + auto lst{common::perfdata::parse_perfdata(0, 0, " 'foo bar '=2s;2;5;;", + _logger)}; // Assertions. ASSERT_EQ(lst.size(), 1u); - std::list::const_iterator it(lst.begin()); - misc::perfdata expected; + std::list::const_iterator it(lst.begin()); + perfdata expected; expected.name("foo bar"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(perfdata::gauge); expected.value(2); expected.unit("s"); expected.warning(2.0); @@ -437,9 +433,9 @@ TEST_F(MiscParserParsePerfdata, LabelWithSpacesMultiline) { ASSERT_TRUE(expected == *it); } -TEST_F(MiscParserParsePerfdata, Complex2) { +TEST_F(PerfdataParser, Complex2) { // Parse perfdata. - auto list{misc::parse_perfdata( + auto list{perfdata::parse_perfdata( 0, 0, "' \n time'=2,45698s;;nan;;inf d[metric]=239765B/s;5;;-inf; " "g[test]=8x;;;;" @@ -449,12 +445,12 @@ TEST_F(MiscParserParsePerfdata, Complex2) { // Assertions. ASSERT_EQ(list.size(), 6u); - std::list::const_iterator it(list.begin()); - misc::perfdata expected; + std::list::const_iterator it(list.begin()); + perfdata expected; // #1. expected.name("time"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(perfdata::gauge); expected.value(2.45698); expected.unit("s"); expected.max(std::numeric_limits::infinity()); @@ -463,9 +459,9 @@ TEST_F(MiscParserParsePerfdata, Complex2) { ++it; // #2. - expected = misc::perfdata(); + expected = perfdata(); expected.name("metric"); - expected.value_type(misc::perfdata::derive); + expected.value_type(perfdata::derive); expected.value(239765); expected.unit("B/s"); expected.warning(5.0); @@ -476,9 +472,9 @@ TEST_F(MiscParserParsePerfdata, Complex2) { ++it; // #3. - expected = misc::perfdata(); + expected = perfdata(); expected.name("test"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(perfdata::gauge); expected.value(8); expected.unit("x"); ASSERT_TRUE(expected == *it); @@ -486,9 +482,9 @@ TEST_F(MiscParserParsePerfdata, Complex2) { ++it; // #4. - expected = misc::perfdata(); + expected = perfdata(); expected.name("infotraffic"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(perfdata::gauge); expected.value(18.6); expected.unit("x"); ASSERT_TRUE(expected == *it); @@ -496,9 +492,9 @@ TEST_F(MiscParserParsePerfdata, Complex2) { ++it; // #5. - expected = misc::perfdata(); + expected = perfdata(); expected.name("foo"); - expected.value_type(misc::perfdata::absolute); + expected.value_type(perfdata::absolute); expected.value(1234.17); expected.warning(10.0); expected.warning_low(0.0); @@ -509,9 +505,9 @@ TEST_F(MiscParserParsePerfdata, Complex2) { ++it; // #6. - expected = misc::perfdata(); + expected = perfdata(); expected.name("bar"); - expected.value_type(misc::perfdata::counter); + expected.value_type(perfdata::counter); expected.value(1234.147); expected.warning(10.0); expected.warning_low(-std::numeric_limits::infinity()); @@ -525,15 +521,15 @@ TEST_F(MiscParserParsePerfdata, Complex2) { // Given a misc::parser object // When parse_perfdata() is called with a valid perfdata string // Then perfdata are returned in a list -TEST_F(MiscParserParsePerfdata, SimpleWithR) { - auto lst{misc::parse_perfdata(0, 0, "'total'=5;;;0;\r", _logger)}; +TEST_F(PerfdataParser, SimpleWithR) { + auto lst{common::perfdata::parse_perfdata(0, 0, "'total'=5;;;0;\r", _logger)}; // Assertions. ASSERT_EQ(lst.size(), 1u); - std::list::const_iterator it(lst.begin()); - misc::perfdata expected; + std::list::const_iterator it(lst.begin()); + perfdata expected; expected.name("total"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(perfdata::gauge); expected.value(5); expected.unit(""); expected.warning(NAN); @@ -548,8 +544,9 @@ TEST_F(MiscParserParsePerfdata, SimpleWithR) { // Given a misc::parser object // When parse_perfdata() is called with a valid perfdata string // Then perfdata are returned in a list -TEST_F(MiscParserParsePerfdata, BadMetric) { - auto lst{misc::parse_perfdata(0, 0, "user1=1 user2=2 =1 user3=3", _logger)}; +TEST_F(PerfdataParser, BadMetric) { + auto lst{common::perfdata::parse_perfdata(0, 0, "user1=1 user2=2 =1 user3=3", + _logger)}; // Assertions. ASSERT_EQ(lst.size(), 3u); @@ -561,9 +558,9 @@ TEST_F(MiscParserParsePerfdata, BadMetric) { } } -TEST_F(MiscParserParsePerfdata, BadMetric1) { - auto lst{ - misc::parse_perfdata(0, 0, "user1=1 user2=2 user4= user3=3", _logger)}; +TEST_F(PerfdataParser, BadMetric1) { + auto lst{common::perfdata::parse_perfdata( + 0, 0, "user1=1 user2=2 user4= user3=3", _logger)}; // Assertions. ASSERT_EQ(lst.size(), 3u); diff --git a/common/tests/process_test.cc b/common/tests/process_test.cc new file mode 100644 index 00000000000..7537532c321 --- /dev/null +++ b/common/tests/process_test.cc @@ -0,0 +1,174 @@ +/** + * Copyright 2023 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#include +#include + +#include "pool.hh" +#include "process.hh" + +using namespace com::centreon::common; + +extern std::shared_ptr g_io_context; + +static std::shared_ptr _logger = + spdlog::stdout_color_mt("process_test"); + +class process_test : public ::testing::Test { + public: + static void SetUpTestSuite() { + _logger->set_level(spdlog::level::trace); + _logger->set_pattern("[%Y-%m-%dT%H:%M:%S.%e%z] [%s:%#] [%n] [%l] [%P] %v"); + } +}; + +class process_wait : public process { + std::condition_variable _cond; + std::string _stdout; + std::string _stderr; + + public: + void on_stdout_read(const boost::system::error_code& err, + size_t nb_read) override { + if (!err) { + _stdout += std::string_view(_stdout_read_buffer, nb_read); + } + process::on_stdout_read(err, nb_read); + } + + void on_stderr_read(const boost::system::error_code& err, + size_t nb_read) override { + if (!err) { + _stderr += std::string_view(_stderr_read_buffer, nb_read); + } + process::on_stderr_read(err, nb_read); + } + + void on_process_end(const boost::system::error_code& err, + int raw_exit_status) override { + process::on_process_end(err, raw_exit_status); + _cond.notify_one(); + } + + template + process_wait(const std::shared_ptr& io_context, + const std::shared_ptr& logger, + const std::string_view& exe_path, + const std::initializer_list& args) + : process(io_context, logger, exe_path, args) {} + + process_wait(const std::shared_ptr& io_context, + const std::shared_ptr& logger, + const std::string_view& cmd_line) + : process(io_context, logger, cmd_line) {} + + const std::string& get_stdout() const { return _stdout; } + const std::string& get_stderr() const { return _stderr; } + + void wait() { + std::mutex dummy; + std::unique_lock l(dummy); + _cond.wait(l); + } +}; + +TEST_F(process_test, echo) { + using namespace std::literals; + std::shared_ptr to_wait( + new process_wait(g_io_context, _logger, "/bin/echo", {"hello"s})); + to_wait->start_process(); + to_wait->wait(); + ASSERT_EQ(to_wait->get_exit_status(), 0); + ASSERT_EQ(to_wait->get_stdout(), "hello\n"); + ASSERT_EQ(to_wait->get_stderr(), ""); +} + +TEST_F(process_test, throw_on_error) { + using namespace std::literals; + std::shared_ptr to_wait( + new process_wait(g_io_context, _logger, "turlututu", {"hello"s})); + ASSERT_THROW(to_wait->start_process(), std::exception); +} + +TEST_F(process_test, script_error) { + using namespace std::literals; + std::shared_ptr to_wait( + new process_wait(g_io_context, _logger, "/bin/sh", {"taratata"s})); + to_wait->start_process(); + to_wait->wait(); + ASSERT_NE(to_wait->get_exit_status(), 0); + ASSERT_EQ(to_wait->get_stdout(), ""); + ASSERT_GT(to_wait->get_stderr().length(), 10); +} + +TEST_F(process_test, call_start_several_time) { + std::shared_ptr to_wait( + new process_wait(g_io_context, _logger, "/bin/echo", {"hello"})); + std::string expected; + for (int ii = 0; ii < 10; ++ii) { + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + to_wait->start_process(); + expected += "hello\n"; + } + to_wait->wait(); + ASSERT_EQ(to_wait->get_exit_status(), 0); + ASSERT_EQ(to_wait->get_stdout(), expected); + ASSERT_EQ(to_wait->get_stderr(), ""); +} + +TEST_F(process_test, stdin_to_stdout) { + ::remove("toto.sh"); + std::ofstream script("toto.sh"); + script << "while read line ; do echo receive $line ; done" << std::endl; + + std::shared_ptr loopback( + new process_wait(g_io_context, _logger, "/bin/sh toto.sh")); + + loopback->start_process(); + + std::string expected; + for (unsigned ii = 0; ii < 10; ++ii) { + if (ii > 5) { + // in order to let some async_read_some complete + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } + loopback->write_to_stdin(fmt::format("hello{}\n", ii)); + expected += fmt::format("receive hello{}\n", ii); + } + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + ASSERT_EQ(expected, loopback->get_stdout()); +} + +TEST_F(process_test, shell_stdin_to_stdout) { + std::shared_ptr loopback( + new process_wait(g_io_context, _logger, "/bin/sh")); + + loopback->start_process(); + + std::string expected; + for (unsigned ii = 0; ii < 10; ++ii) { + if (ii > 5) { + // in order to let some async_read_some complete + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } + loopback->write_to_stdin(fmt::format("echo hello{}\n", ii)); + expected += fmt::format("hello{}\n", ii); + } + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + ASSERT_EQ(expected, loopback->get_stdout()); +} diff --git a/common/tests/test_main.cc b/common/tests/test_main.cc index 995392ef7a4..09955d482aa 100644 --- a/common/tests/test_main.cc +++ b/common/tests/test_main.cc @@ -47,6 +47,7 @@ std::shared_ptr pool_logger = int main(int argc, char* argv[]) { // GTest initialization. testing::InitGoogleTest(&argc, argv); + sigignore(SIGPIPE); // Set specific environment. testing::AddGlobalTestEnvironment(new CentreonEngineEnvironment()); diff --git a/engine/modules/opentelemetry/src/otl_config.cc b/engine/modules/opentelemetry/src/otl_config.cc index f75d0c9ab28..c36fd359f24 100644 --- a/engine/modules/opentelemetry/src/otl_config.cc +++ b/engine/modules/opentelemetry/src/otl_config.cc @@ -123,6 +123,10 @@ bool otl_config::operator==(const otl_config& right) const { _second_fifo_expiry == right._second_fifo_expiry && _max_fifo_size == right._max_fifo_size; + if (!ret) { + return false; + } + if (_telegraf_conf_server_config && right._telegraf_conf_server_config) { return *_telegraf_conf_server_config == *right._telegraf_conf_server_config; } diff --git a/engine/tests/checks/anomalydetection.cc b/engine/tests/checks/anomalydetection.cc index 7d1a9e7981f..d210bd77ea6 100644 --- a/engine/tests/checks/anomalydetection.cc +++ b/engine/tests/checks/anomalydetection.cc @@ -1062,6 +1062,8 @@ TEST_P(AnomalydetectionCheckFileTooOld, FileTooOld) { ASSERT_EQ(_ad->get_perf_data(), "metric=70%;50;75"); ::unlink("/tmp/thresholds_status_change.json"); + // let's time to callback to be called + std::this_thread::sleep_for(std::chrono::milliseconds(10)); } INSTANTIATE_TEST_SUITE_P( diff --git a/vcpkg.json b/vcpkg.json index 04388ffde31..5a4e2b5d1d7 100644 --- a/vcpkg.json +++ b/vcpkg.json @@ -20,6 +20,7 @@ "boost-multi-index", "boost-interprocess", "boost-exception", + "boost-process", "boost-program-options", "boost-serialization", "boost-url", @@ -27,4 +28,4 @@ "rapidjson", "gtest" ] -} +} \ No newline at end of file From b09373b4ccd7e99f432dc4c30f3918e2185e4017 Mon Sep 17 00:00:00 2001 From: David Boucher Date: Wed, 12 Jun 2024 17:15:36 +0200 Subject: [PATCH 36/60] fix(broker): gnutls minimal version is now 3.6.0 * fix(broker): gnutls minimal version is now 3.6.0 * cleanup(broker): the code concerning gnutls prior to 3.0.0 is removed * fix(broker): tests simplified REFS: MON-103546 --- broker/grpc/test/acceptor.cc | 2 -- broker/tls/src/internal.cc | 28 +++++----------------------- broker/tls/src/stream.cc | 3 --- packaging/centreon-broker-core.yaml | 2 +- 4 files changed, 6 insertions(+), 29 deletions(-) diff --git a/broker/grpc/test/acceptor.cc b/broker/grpc/test/acceptor.cc index 34892211d43..52d1faf06db 100644 --- a/broker/grpc/test/acceptor.cc +++ b/broker/grpc/test/acceptor.cc @@ -51,8 +51,6 @@ static auto read_file = [](const std::string& path) { TEST_F(GrpcTlsTest, TlsStream) { /* Let's prepare certificates */ std::string hostname = misc::exec("hostname --fqdn"); - if (hostname.empty()) - hostname = "localhost"; hostname = misc::string::trim(hostname); if (hostname.empty()) hostname = "localhost"; diff --git a/broker/tls/src/internal.cc b/broker/tls/src/internal.cc index 337479d2934..757bffcb7dc 100644 --- a/broker/tls/src/internal.cc +++ b/broker/tls/src/internal.cc @@ -18,12 +18,6 @@ #include -#if GNUTLS_VERSION_NUMBER < 0x030000 -#include -#include - -#include -#endif // GNU TLS < 3.0.0 #include "com/centreon/broker/io/raw.hh" #include "com/centreon/broker/io/stream.hh" #include "com/centreon/broker/tls/internal.hh" @@ -51,10 +45,6 @@ unsigned char const tls::dh_params_2048[] = gnutls_dh_params_t tls::dh_params; -#if GNUTLS_VERSION_NUMBER < 0x030000 -GCRY_THREAD_OPTION_PTHREAD_IMPL; -#endif // GNU TLS < 3.0.0 - /** * Deinit the TLS library. */ @@ -78,12 +68,6 @@ void tls::initialize() { auto logger = log_v2::instance().get(log_v2::TLS); - // Eventually initialize libgcrypt. -#if GNUTLS_VERSION_NUMBER < 0x030000 - logger->info("TLS: initializing libgcrypt (GNU TLS <= 2.11.0)"); - gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread); -#endif // GNU TLS < 3.0.0 - // Initialize GNU TLS library. if (gnutls_global_init() != GNUTLS_E_SUCCESS) { logger->error("TLS: GNU TLS library initialization failed"); @@ -93,16 +77,14 @@ void tls::initialize() { // Log GNU TLS version. { logger->info("TLS: compiled with GNU TLS version {}", GNUTLS_VERSION); - char const* v(gnutls_check_version(GNUTLS_VERSION)); + char const* v(gnutls_check_version("3.6.0")); if (!v) { logger->error( - "TLS: GNU TLS run-time version is incompatible with the compile-time " - "version ({}): please update your GNU TLS library", - GNUTLS_VERSION); + "TLS: The GNU TLS run-time version is older than version 3.6.0. " + "Please upgrade your GNU TLS library."); throw msg_fmt( - "TLS: GNU TLS run-time version is incompatible with the compile-time " - "version ({}): please update your GNU TLS library", - GNUTLS_VERSION); + "TLS: The GNU TLS run-time version is older than version 3.6.0. " + "Please upgrade your GNU TLS library."); } logger->info("TLS: loading GNU TLS version {}", v); // gnutls_global_set_log_function(log_gnutls_message); diff --git a/broker/tls/src/stream.cc b/broker/tls/src/stream.cc index 1e36d6f9dfc..165980ba15f 100644 --- a/broker/tls/src/stream.cc +++ b/broker/tls/src/stream.cc @@ -65,9 +65,6 @@ void stream::init(const params& param) { param.apply(_session); // Bind the TLS session with the stream from the lower layer. -#if GNUTLS_VERSION_NUMBER < 0x020C00 - gnutls_transport_set_lowat(*session, 0); -#endif // GNU TLS < 2.12.0 gnutls_transport_set_pull_function(_session, pull_helper); gnutls_transport_set_push_function(_session, push_helper); gnutls_transport_set_ptr(_session, this); diff --git a/packaging/centreon-broker-core.yaml b/packaging/centreon-broker-core.yaml index 1f8eaac6e26..143a9e4b259 100644 --- a/packaging/centreon-broker-core.yaml +++ b/packaging/centreon-broker-core.yaml @@ -42,7 +42,7 @@ overrides: - lua - centreon-clib = ${VERSION}-${RELEASE}${DIST} - centreon-broker = ${VERSION}-${RELEASE}${DIST} - - gnutls >= 3.3.29 + - gnutls >= 3.6.0 conflicts: - centreon-broker-storage - centreon-broker-core-devel From b8840789c1357b57e58d08c2a66b51f777ff785d Mon Sep 17 00:00:00 2001 From: David Boucher Date: Wed, 12 Jun 2024 17:22:18 +0200 Subject: [PATCH 37/60] fix(broker): All metrics sent to database are floats now. REFS: MON-92694 --- broker/core/multiplexing/CMakeLists.txt | 3 -- .../broker/storage/conflict_manager.hh | 16 +++++------ .../inc/com/centreon/broker/storage/stream.hh | 16 +++++------ .../storage/src/conflict_manager_storage.cc | 4 +-- broker/storage/test/perfdata.cc | 28 +++++++++---------- .../com/centreon/broker/unified_sql/stream.hh | 14 +++++----- broker/unified_sql/src/stream_storage.cc | 4 +-- broker/unified_sql/test/perfdata.cc | 28 +++++++++---------- 8 files changed, 55 insertions(+), 58 deletions(-) diff --git a/broker/core/multiplexing/CMakeLists.txt b/broker/core/multiplexing/CMakeLists.txt index 23b824c008d..3a822a1c1cd 100644 --- a/broker/core/multiplexing/CMakeLists.txt +++ b/broker/core/multiplexing/CMakeLists.txt @@ -42,7 +42,4 @@ if(WITH_TESTING) ${TESTS_DIR}/publisher/read.cc ${TESTS_DIR}/publisher/write.cc PARENT_SCOPE) - message(STATUS "&&&&&&&&&&&&&&&") - message(STATUS "${TESTS_SOURCES}") - message(STATUS "&&&&&&&&&&&&&&&") endif(WITH_TESTING) diff --git a/broker/storage/inc/com/centreon/broker/storage/conflict_manager.hh b/broker/storage/inc/com/centreon/broker/storage/conflict_manager.hh index 6a8a1330519..b7815b6e5be 100644 --- a/broker/storage/inc/com/centreon/broker/storage/conflict_manager.hh +++ b/broker/storage/inc/com/centreon/broker/storage/conflict_manager.hh @@ -126,23 +126,23 @@ class conflict_manager { bool locked; uint32_t metric_id; int16_t type; - double value; + float value; std::string unit_name; - double warn; - double warn_low; + float warn; + float warn_low; bool warn_mode; - double crit; - double crit_low; + float crit; + float crit_low; bool crit_mode; - double min; - double max; + float min; + float max; bool metric_mapping_sent; }; struct metric_value { time_t c_time; uint32_t metric_id; short status; - double value; + float value; }; static void (conflict_manager::*const _neb_processing_table[])( diff --git a/broker/storage/inc/com/centreon/broker/storage/stream.hh b/broker/storage/inc/com/centreon/broker/storage/stream.hh index f005ddb79ba..6a409bb5938 100644 --- a/broker/storage/inc/com/centreon/broker/storage/stream.hh +++ b/broker/storage/inc/com/centreon/broker/storage/stream.hh @@ -52,22 +52,22 @@ class stream : public io::stream { bool locked; uint32_t metric_id; uint16_t type; - double value; + float value; std::string unit_name; - double warn; - double warn_low; + float warn; + float warn_low; bool warn_mode; - double crit; - double crit_low; + float crit; + float crit_low; bool crit_mode; - double min; - double max; + float min; + float max; }; struct metric_value { time_t c_time; uint32_t metric_id; short status; - double value; + float value; }; std::string _status; diff --git a/broker/storage/src/conflict_manager_storage.cc b/broker/storage/src/conflict_manager_storage.cc index 6b66c1a5b8c..d2fca02796e 100644 --- a/broker/storage/src/conflict_manager_storage.cc +++ b/broker/storage/src/conflict_manager_storage.cc @@ -49,8 +49,8 @@ using namespace com::centreon::broker::storage; * * @return true if they are equal, false otherwise. */ -static inline bool check_equality(double a, double b) { - static const double eps = 0.000001; +static inline bool check_equality(float a, float b) { + static const float eps = 0.00001; if (a == b) return true; if (std::isnan(a) && std::isnan(b)) diff --git a/broker/storage/test/perfdata.cc b/broker/storage/test/perfdata.cc index 6e3b16f40de..9d4fbf0d83e 100644 --- a/broker/storage/test/perfdata.cc +++ b/broker/storage/test/perfdata.cc @@ -238,9 +238,9 @@ TEST_F(StorageParserParsePerfdata, Simple2) { expected.value_type(common::perfdata::gauge); expected.value(18.0); expected.unit("%"); - expected.warning(std::numeric_limits::infinity()); + expected.warning(std::numeric_limits::infinity()); expected.warning_low(15.0); - expected.critical(std::numeric_limits::infinity()); + expected.critical(std::numeric_limits::infinity()); expected.critical_low(10.0); expected.min(0.0); expected.max(100.0); @@ -265,7 +265,7 @@ TEST_F(StorageParserParsePerfdata, Complex1) { expected.value_type(common::perfdata::gauge); expected.value(2.45698); expected.unit("s"); - expected.max(std::numeric_limits::infinity()); + expected.max(std::numeric_limits::infinity()); ASSERT_TRUE(expected == *it); ++it; @@ -277,7 +277,7 @@ TEST_F(StorageParserParsePerfdata, Complex1) { expected.unit("B/s"); expected.warning(5.0); expected.warning_low(0.0); - expected.min(-std::numeric_limits::infinity()); + expected.min(-std::numeric_limits::infinity()); ASSERT_TRUE(expected == *it); ++it; @@ -297,7 +297,7 @@ TEST_F(StorageParserParsePerfdata, Complex1) { expected.value(1234.0); expected.warning(10.0); expected.warning_low(0.0); - expected.critical(std::numeric_limits::infinity()); + expected.critical(std::numeric_limits::infinity()); expected.critical_low(11.0); ASSERT_TRUE(expected == *it); ++it; @@ -308,7 +308,7 @@ TEST_F(StorageParserParsePerfdata, Complex1) { expected.value_type(common::perfdata::counter); expected.value(1234.0); expected.warning(10.0); - expected.warning_low(-std::numeric_limits::infinity()); + expected.warning_low(-std::numeric_limits::infinity()); expected.critical(30.0); expected.critical_low(20.0); ASSERT_TRUE(expected == *it); @@ -331,10 +331,10 @@ TEST_F(StorageParserParsePerfdata, Complex1) { expected.value_type(common::perfdata::gauge); expected.value(9.0); expected.unit("queries_per_second"); - expected.warning(std::numeric_limits::infinity()); + expected.warning(std::numeric_limits::infinity()); expected.warning_low(10.0); expected.warning_mode(true); - expected.critical(std::numeric_limits::infinity()); + expected.critical(std::numeric_limits::infinity()); expected.critical_low(5.0); expected.critical_mode(true); expected.min(0.0); @@ -449,7 +449,7 @@ TEST_F(StorageParserParsePerfdata, Complex2) { expected.value_type(common::perfdata::gauge); expected.value(2.45698); expected.unit("s"); - expected.max(std::numeric_limits::infinity()); + expected.max(std::numeric_limits::infinity()); ASSERT_TRUE(expected == *it); ASSERT_FALSE(expected != *it); ++it; @@ -462,7 +462,7 @@ TEST_F(StorageParserParsePerfdata, Complex2) { expected.unit("B/s"); expected.warning(5.0); expected.warning_low(0.0); - expected.min(-std::numeric_limits::infinity()); + expected.min(-std::numeric_limits::infinity()); ASSERT_TRUE(expected == *it); ASSERT_FALSE(expected != *it); ++it; @@ -494,7 +494,7 @@ TEST_F(StorageParserParsePerfdata, Complex2) { expected.value(1234.17); expected.warning(10.0); expected.warning_low(0.0); - expected.critical(std::numeric_limits::infinity()); + expected.critical(std::numeric_limits::infinity()); expected.critical_low(11.0); ASSERT_TRUE(expected == *it); ASSERT_FALSE(expected != *it); @@ -506,7 +506,7 @@ TEST_F(StorageParserParsePerfdata, Complex2) { expected.value_type(common::perfdata::counter); expected.value(1234.147); expected.warning(10.0); - expected.warning_low(-std::numeric_limits::infinity()); + expected.warning_low(-std::numeric_limits::infinity()); expected.critical(30.0); expected.critical_low(20.0); ASSERT_TRUE(expected == *it); @@ -549,7 +549,7 @@ TEST_F(StorageParserParsePerfdata, BadMetric) { int i = 1; for (auto& p : lst) { ASSERT_EQ(p.name(), fmt::format("user{}", i)); - ASSERT_EQ(p.value(), static_cast(i)); + ASSERT_EQ(p.value(), static_cast(i)); ++i; } } @@ -563,7 +563,7 @@ TEST_F(StorageParserParsePerfdata, BadMetric1) { int i = 1; for (auto& p : lst) { ASSERT_EQ(p.name(), fmt::format("user{}", i)); - ASSERT_EQ(p.value(), static_cast(i)); + ASSERT_EQ(p.value(), static_cast(i)); ++i; } } diff --git a/broker/unified_sql/inc/com/centreon/broker/unified_sql/stream.hh b/broker/unified_sql/inc/com/centreon/broker/unified_sql/stream.hh index 67a2e27fc4f..f0944953f6f 100644 --- a/broker/unified_sql/inc/com/centreon/broker/unified_sql/stream.hh +++ b/broker/unified_sql/inc/com/centreon/broker/unified_sql/stream.hh @@ -211,16 +211,16 @@ class stream : public io::stream { bool locked; uint32_t metric_id; uint32_t type; - double value; + float value; std::string unit_name; - double warn; - double warn_low; + float warn; + float warn_low; bool warn_mode; - double crit; - double crit_low; + float crit; + float crit_low; bool crit_mode; - double min; - double max; + float min; + float max; bool metric_mapping_sent; }; diff --git a/broker/unified_sql/src/stream_storage.cc b/broker/unified_sql/src/stream_storage.cc index 9a0e8333756..01e6f92fd80 100644 --- a/broker/unified_sql/src/stream_storage.cc +++ b/broker/unified_sql/src/stream_storage.cc @@ -56,8 +56,8 @@ constexpr int32_t queue_timer_duration = 10; * * @return true if they are equal, false otherwise. */ -static inline bool check_equality(double a, double b) { - static const double eps = 0.000001; +static inline bool check_equality(float a, float b) { + static const float eps = 0.00001; if (a == b) return true; if (std::isnan(a) && std::isnan(b)) diff --git a/broker/unified_sql/test/perfdata.cc b/broker/unified_sql/test/perfdata.cc index f2edbb234ea..a19d3689dca 100644 --- a/broker/unified_sql/test/perfdata.cc +++ b/broker/unified_sql/test/perfdata.cc @@ -236,9 +236,9 @@ TEST_F(UnifiedSqlParserParsePerfdata, Simple2) { expected.value_type(common::perfdata::gauge); expected.value(18.0); expected.unit("%"); - expected.warning(std::numeric_limits::infinity()); + expected.warning(std::numeric_limits::infinity()); expected.warning_low(15.0); - expected.critical(std::numeric_limits::infinity()); + expected.critical(std::numeric_limits::infinity()); expected.critical_low(10.0); expected.min(0.0); expected.max(100.0); @@ -262,7 +262,7 @@ TEST_F(UnifiedSqlParserParsePerfdata, Complex1) { expected.value_type(common::perfdata::gauge); expected.value(2.45698); expected.unit("s"); - expected.max(std::numeric_limits::infinity()); + expected.max(std::numeric_limits::infinity()); ASSERT_TRUE(expected == *it); ++it; @@ -274,7 +274,7 @@ TEST_F(UnifiedSqlParserParsePerfdata, Complex1) { expected.unit("B/s"); expected.warning(5.0); expected.warning_low(0.0); - expected.min(-std::numeric_limits::infinity()); + expected.min(-std::numeric_limits::infinity()); ASSERT_TRUE(expected == *it); ++it; @@ -294,7 +294,7 @@ TEST_F(UnifiedSqlParserParsePerfdata, Complex1) { expected.value(1234.0); expected.warning(10.0); expected.warning_low(0.0); - expected.critical(std::numeric_limits::infinity()); + expected.critical(std::numeric_limits::infinity()); expected.critical_low(11.0); ASSERT_TRUE(expected == *it); ++it; @@ -305,7 +305,7 @@ TEST_F(UnifiedSqlParserParsePerfdata, Complex1) { expected.value_type(common::perfdata::counter); expected.value(1234.0); expected.warning(10.0); - expected.warning_low(-std::numeric_limits::infinity()); + expected.warning_low(-std::numeric_limits::infinity()); expected.critical(30.0); expected.critical_low(20.0); ASSERT_TRUE(expected == *it); @@ -328,10 +328,10 @@ TEST_F(UnifiedSqlParserParsePerfdata, Complex1) { expected.value_type(common::perfdata::gauge); expected.value(9.0); expected.unit("queries_per_second"); - expected.warning(std::numeric_limits::infinity()); + expected.warning(std::numeric_limits::infinity()); expected.warning_low(10.0); expected.warning_mode(true); - expected.critical(std::numeric_limits::infinity()); + expected.critical(std::numeric_limits::infinity()); expected.critical_low(5.0); expected.critical_mode(true); expected.min(0.0); @@ -443,7 +443,7 @@ TEST_F(UnifiedSqlParserParsePerfdata, Complex2) { expected.value_type(common::perfdata::gauge); expected.value(2.45698); expected.unit("s"); - expected.max(std::numeric_limits::infinity()); + expected.max(std::numeric_limits::infinity()); ASSERT_TRUE(expected == *it); ASSERT_FALSE(expected != *it); ++it; @@ -456,7 +456,7 @@ TEST_F(UnifiedSqlParserParsePerfdata, Complex2) { expected.unit("B/s"); expected.warning(5.0); expected.warning_low(0.0); - expected.min(-std::numeric_limits::infinity()); + expected.min(-std::numeric_limits::infinity()); ASSERT_TRUE(expected == *it); ASSERT_FALSE(expected != *it); ++it; @@ -488,7 +488,7 @@ TEST_F(UnifiedSqlParserParsePerfdata, Complex2) { expected.value(1234.17); expected.warning(10.0); expected.warning_low(0.0); - expected.critical(std::numeric_limits::infinity()); + expected.critical(std::numeric_limits::infinity()); expected.critical_low(11.0); ASSERT_TRUE(expected == *it); ASSERT_FALSE(expected != *it); @@ -500,7 +500,7 @@ TEST_F(UnifiedSqlParserParsePerfdata, Complex2) { expected.value_type(common::perfdata::counter); expected.value(1234.147); expected.warning(10.0); - expected.warning_low(-std::numeric_limits::infinity()); + expected.warning_low(-std::numeric_limits::infinity()); expected.critical(30.0); expected.critical_low(20.0); ASSERT_TRUE(expected == *it); @@ -543,7 +543,7 @@ TEST_F(UnifiedSqlParserParsePerfdata, BadMetric) { int i = 1; for (auto& p : lst) { ASSERT_EQ(p.name(), fmt::format("user{}", i)); - ASSERT_EQ(p.value(), static_cast(i)); + ASSERT_EQ(p.value(), static_cast(i)); ++i; } } @@ -557,7 +557,7 @@ TEST_F(UnifiedSqlParserParsePerfdata, BadMetric1) { int i = 1; for (auto& p : lst) { ASSERT_EQ(p.name(), fmt::format("user{}", i)); - ASSERT_EQ(p.value(), static_cast(i)); + ASSERT_EQ(p.value(), static_cast(i)); ++i; } } From 1ea67d2ea8ff4979520bb2565d0f5c91e96894e9 Mon Sep 17 00:00:00 2001 From: jean-christophe81 <98889244+jean-christophe81@users.noreply.github.com> Date: Fri, 14 Jun 2024 09:56:13 +0200 Subject: [PATCH 38/60] MON-103295 default mariadb plugins directory is configurable and set by default according to the os (#1421) * default mariadb plugins directory is configurable and set by default according to the os * fix previous rebase issue * no lib mariadb static link * fix test REFS:MON-103295 --- .../docker/Dockerfile.centreon-collect-alma9 | 1 + ...ockerfile.centreon-collect-debian-bookworm | 1 + ...ockerfile.centreon-collect-debian-bullseye | 1 + .../Dockerfile.centreon-collect-mysql-alma9 | 1 + ...ckerfile.centreon-collect-mysql-alma9-test | 5 +- .../Dockerfile.centreon-collect-ubuntu-jammy | 1 + .github/scripts/collect-prepare-test-robot.sh | 4 +- broker/CMakeLists.txt | 8 ++- .../centreon/broker/sql/database_config.hh | 8 +++ .../centreon/broker/sql/mysql_bind_base.hh | 2 +- .../com/centreon/broker/sql/mysql_column.hh | 3 +- .../centreon/broker/sql/mysql_connection.hh | 1 + broker/core/sql/src/database_config.cc | 18 ++++-- broker/core/sql/src/mysql_connection.cc | 9 ++- common/inc/com/centreon/common/perfdata.hh | 42 +++++++------- common/tests/perfdata_test.cc | 56 +++++++++---------- common/tests/process_test.cc | 18 +++++- packaging/centreon-broker-core.yaml | 2 + tests/mysql_docker_conf/centreon16.cnf | 1 - vcpkg.json | 1 - 20 files changed, 118 insertions(+), 65 deletions(-) diff --git a/.github/docker/Dockerfile.centreon-collect-alma9 b/.github/docker/Dockerfile.centreon-collect-alma9 index 7eb1fabb13e..d2ae761de8d 100644 --- a/.github/docker/Dockerfile.centreon-collect-alma9 +++ b/.github/docker/Dockerfile.centreon-collect-alma9 @@ -29,6 +29,7 @@ dnf --best install -y cmake \ openssh-server \ mariadb-server \ mariadb \ + mariadb-connector-c-devel \ gnutls-devel \ libgcrypt-devel \ lua-devel \ diff --git a/.github/docker/Dockerfile.centreon-collect-debian-bookworm b/.github/docker/Dockerfile.centreon-collect-debian-bookworm index 5bb95c9d0db..d395c7cba52 100644 --- a/.github/docker/Dockerfile.centreon-collect-debian-bookworm +++ b/.github/docker/Dockerfile.centreon-collect-debian-bookworm @@ -21,6 +21,7 @@ apt-get -y install git \ mariadb-server \ openssh-server \ libmariadb3 \ + libmariadb-dev \ librrd-dev \ libgnutls28-dev \ liblua5.3-dev \ diff --git a/.github/docker/Dockerfile.centreon-collect-debian-bullseye b/.github/docker/Dockerfile.centreon-collect-debian-bullseye index eb3b14950bc..9c019e53072 100644 --- a/.github/docker/Dockerfile.centreon-collect-debian-bullseye +++ b/.github/docker/Dockerfile.centreon-collect-debian-bullseye @@ -17,6 +17,7 @@ apt-get -y install git \ mariadb-server \ openssh-server \ libmariadb3 \ + libmariadb-dev \ librrd-dev \ libgnutls28-dev \ liblua5.3-dev \ diff --git a/.github/docker/Dockerfile.centreon-collect-mysql-alma9 b/.github/docker/Dockerfile.centreon-collect-mysql-alma9 index 5cd38f62a42..02661fdb023 100644 --- a/.github/docker/Dockerfile.centreon-collect-mysql-alma9 +++ b/.github/docker/Dockerfile.centreon-collect-mysql-alma9 @@ -25,6 +25,7 @@ dnf --best install -y cmake \ gdb \ gettext \ git \ + mariadb-connector-c-devel \ ninja-build \ openssh-server \ mysql-server \ diff --git a/.github/docker/Dockerfile.centreon-collect-mysql-alma9-test b/.github/docker/Dockerfile.centreon-collect-mysql-alma9-test index 8d5a10771f9..bd135b7dee9 100644 --- a/.github/docker/Dockerfile.centreon-collect-mysql-alma9-test +++ b/.github/docker/Dockerfile.centreon-collect-mysql-alma9-test @@ -20,6 +20,7 @@ dnf --best install -y gcc \ gdb \ git \ openssh-server \ + mariadb-connector-c \ mysql-server \ mysql \ gnutls \ @@ -42,8 +43,8 @@ dnf clean all echo "install robot and dependencies" -pip3 install -U robotframework robotframework-databaselibrary robotframework-httpctrl robotframework-examples pymysql python-dateutil psutil -pip3 install grpcio grpcio_tools py-cpuinfo cython unqlite gitpython boto3 robotframework-requests +pip3 install -U robotframework robotframework-databaselibrary robotframework-httpctrl robotframework-examples pymysql python-dateutil psutil +pip3 install grpcio grpcio_tools py-cpuinfo cython unqlite gitpython boto3 robotframework-requests cryptography cd /tmp/collect diff --git a/.github/docker/Dockerfile.centreon-collect-ubuntu-jammy b/.github/docker/Dockerfile.centreon-collect-ubuntu-jammy index e664fab6a1a..2d6650acb02 100644 --- a/.github/docker/Dockerfile.centreon-collect-ubuntu-jammy +++ b/.github/docker/Dockerfile.centreon-collect-ubuntu-jammy @@ -21,6 +21,7 @@ apt-get -y install cmake \ mariadb-server \ openssh-server \ libmariadb3 \ + libmariadb-dev \ librrd-dev \ libgnutls28-dev \ liblua5.3-dev \ diff --git a/.github/scripts/collect-prepare-test-robot.sh b/.github/scripts/collect-prepare-test-robot.sh index 71a070bb091..25e9f02e5b0 100755 --- a/.github/scripts/collect-prepare-test-robot.sh +++ b/.github/scripts/collect-prepare-test-robot.sh @@ -30,8 +30,8 @@ if [ $database_type == 'mysql' ]; then sleep 5 echo "########################### Init centreon database ############################" - mysql -e "CREATE USER IF NOT EXISTS 'centreon'@'localhost' IDENTIFIED WITH mysql_native_password BY 'centreon'" - mysql -e "CREATE USER IF NOT EXISTS 'root_centreon'@'localhost' IDENTIFIED WITH mysql_native_password BY 'centreon'" + mysql -e "CREATE USER IF NOT EXISTS 'centreon'@'localhost' IDENTIFIED BY 'centreon'" + mysql -e "CREATE USER IF NOT EXISTS 'root_centreon'@'localhost' IDENTIFIED BY 'centreon'" else echo "########################### Start MariaDB ######################################" if [ "$distrib" = "ALMALINUX" ]; then diff --git a/broker/CMakeLists.txt b/broker/CMakeLists.txt index e3f564ffa9e..ad2373471fe 100644 --- a/broker/CMakeLists.txt +++ b/broker/CMakeLists.txt @@ -66,12 +66,15 @@ endif() if(OS_DISTRIBUTOR STREQUAL "Debian" OR OS_DISTRIBUTOR STREQUAL "Ubuntu") message(STATUS "deb based os") add_definitions("-DMYSQL_SOCKET=\"/var/run/mysqld/mysqld.sock\"") + add_definitions("-DDEFAULT_MARIADB_EXTENSION_DIR=\"/usr/lib/x86_64-linux-gnu/libmariadb3/plugin\"") elseif(OS_DISTRIBUTOR STREQUAL "CentOS" OR OS_DISTRIBUTOR STREQUAL "RedHat") message(STATUS "rpm based os") add_definitions("-DMYSQL_SOCKET=\"/var/lib/mysql/mysql.sock\"") + add_definitions("-DDEFAULT_MARIADB_EXTENSION_DIR=\"/usr/lib64/mariadb/plugin\"") else() message(STATUS "other os: ${OS_DISTRIBUTOR}") - add_definitions("-DMYSQL_SOCKET=/tmp/mysql.sock") + add_definitions("-DMYSQL_SOCKET=\"/tmp/mysql.sock\"") + add_definitions("-DDEFAULT_MARIADB_EXTENSION_DIR=\"/usr/lib/x86_64-linux-gnu/libmariadb3/plugin\"") endif() include_directories( @@ -79,7 +82,8 @@ include_directories( "${PROJECT_SOURCE_DIR}/neb/inc" "${CMAKE_SOURCE_DIR}/engine/inc" "${PROJECT_SOURCE_DIR}/core/multiplexing/inc" - "${PROJECT_SOURCE_DIR}/core/sql/inc") + "${PROJECT_SOURCE_DIR}/core/sql/inc" + "${MARIADB_INCLUDE_DIRS}") set(INC_DIR "${PROJECT_SOURCE_DIR}/core/inc/com/centreon/broker") set(SRC_DIR "${PROJECT_SOURCE_DIR}/core/src") set(TEST_DIR "${PROJECT_SOURCE_DIR}/core/test") diff --git a/broker/core/sql/inc/com/centreon/broker/sql/database_config.hh b/broker/core/sql/inc/com/centreon/broker/sql/database_config.hh index 0636df9d79d..d68df108294 100644 --- a/broker/core/sql/inc/com/centreon/broker/sql/database_config.hh +++ b/broker/core/sql/inc/com/centreon/broker/sql/database_config.hh @@ -75,6 +75,9 @@ class database_config { int get_connections_count() const; unsigned get_max_commit_delay() const; unsigned get_category() const; + const std::string& get_extension_directory() const { + return _extension_directory; + } void set_type(std::string const& type); void set_host(std::string const& host); @@ -87,6 +90,9 @@ class database_config { void set_queries_per_transaction(int qpt); void set_check_replication(bool check_replication); void set_category(unsigned category); + void set_extension_directory(std::string const& extension_directory) { + _extension_directory = extension_directory; + } database_config auto_commit_conf() const; @@ -105,6 +111,8 @@ class database_config { int _connections_count; unsigned _max_commit_delay; unsigned _category; + // where mariadb will find extension such as caching_sha2_password.so + std::string _extension_directory; }; std::ostream& operator<<(std::ostream& s, const database_config cfg); diff --git a/broker/core/sql/inc/com/centreon/broker/sql/mysql_bind_base.hh b/broker/core/sql/inc/com/centreon/broker/sql/mysql_bind_base.hh index e4f6bdde00a..24373ada1b9 100644 --- a/broker/core/sql/inc/com/centreon/broker/sql/mysql_bind_base.hh +++ b/broker/core/sql/inc/com/centreon/broker/sql/mysql_bind_base.hh @@ -19,7 +19,7 @@ #ifndef CCB_MYSQL_BIND_BASE_HH #define CCB_MYSQL_BIND_BASE_HH -#include +#include namespace com::centreon::broker { diff --git a/broker/core/sql/inc/com/centreon/broker/sql/mysql_column.hh b/broker/core/sql/inc/com/centreon/broker/sql/mysql_column.hh index 7d411e8ee0c..beaa8200b7a 100644 --- a/broker/core/sql/inc/com/centreon/broker/sql/mysql_column.hh +++ b/broker/core/sql/inc/com/centreon/broker/sql/mysql_column.hh @@ -19,8 +19,9 @@ #ifndef CCB_DATABASE_MYSQL_COLUMN_HH #define CCB_DATABASE_MYSQL_COLUMN_HH +#include + #include -#include #include namespace com::centreon::broker { diff --git a/broker/core/sql/inc/com/centreon/broker/sql/mysql_connection.hh b/broker/core/sql/inc/com/centreon/broker/sql/mysql_connection.hh index d83aaa17697..efe6140ab21 100644 --- a/broker/core/sql/inc/com/centreon/broker/sql/mysql_connection.hh +++ b/broker/core/sql/inc/com/centreon/broker/sql/mysql_connection.hh @@ -85,6 +85,7 @@ class mysql_connection { const std::string _pwd; const std::string _name; const int _port; + const std::string _extension_directory; const unsigned _max_second_commit_delay; time_t _last_commit; std::atomic _state; diff --git a/broker/core/sql/src/database_config.cc b/broker/core/sql/src/database_config.cc index 855d56e0faa..6adf7ff3684 100644 --- a/broker/core/sql/src/database_config.cc +++ b/broker/core/sql/src/database_config.cc @@ -36,7 +36,8 @@ std::ostream& operator<<(std::ostream& s, const database_config cfg) { s << " queries per transaction:" << cfg.get_queries_per_transaction() << " check replication:" << cfg.get_check_replication() << " connection count:" << cfg.get_connections_count() - << " max commit delay:" << cfg.get_max_commit_delay() << 's'; + << " max commit delay:" << cfg.get_max_commit_delay() << 's' + << " extension_directory" << cfg.get_extension_directory(); return s; } @@ -49,7 +50,8 @@ database_config::database_config() : _queries_per_transaction(1), _check_replication(true), _connections_count(1), - _category(SHARED) {} + _category(SHARED), + _extension_directory(DEFAULT_MARIADB_EXTENSION_DIR) {} /** * Constructor. @@ -90,14 +92,16 @@ database_config::database_config(const std::string& type, _check_replication(check_replication), _connections_count(connections_count), _max_commit_delay(max_commit_delay), - _category(SHARED) {} + _category(SHARED), + _extension_directory(DEFAULT_MARIADB_EXTENSION_DIR) {} /** * Build a database configuration from a configuration set. * * @param[in] cfg Endpoint configuration. */ -database_config::database_config(config::endpoint const& cfg) { +database_config::database_config(config::endpoint const& cfg) + : _extension_directory(DEFAULT_MARIADB_EXTENSION_DIR) { std::map::const_iterator it, end; end = cfg.params.end(); @@ -212,6 +216,11 @@ database_config::database_config(config::endpoint const& cfg) { } } else _max_commit_delay = 5; + + it = cfg.params.find("extension_directory"); + if (it != end) { + _extension_directory = it->second; + } } /** @@ -557,6 +566,7 @@ void database_config::_internal_copy(database_config const& other) { _check_replication = other._check_replication; _connections_count = other._connections_count; _max_commit_delay = other._max_commit_delay; + _extension_directory = other._extension_directory; } /** diff --git a/broker/core/sql/src/mysql_connection.cc b/broker/core/sql/src/mysql_connection.cc index 61580982e5b..5c6d2548bba 100644 --- a/broker/core/sql/src/mysql_connection.cc +++ b/broker/core/sql/src/mysql_connection.cc @@ -15,7 +15,7 @@ * * For more information : contact@centreon.com */ -#include +#include #include "com/centreon/broker/config/applier/init.hh" #include "com/centreon/broker/misc/misc.hh" @@ -190,6 +190,9 @@ bool mysql_connection::_try_to_reconnect() { uint32_t timeout = 10; mysql_options(_conn, MYSQL_OPT_CONNECT_TIMEOUT, &timeout); + mysql_optionsv(_conn, MYSQL_PLUGIN_DIR, + (const void*)_extension_directory.c_str()); + if (!mysql_real_connect(_conn, _host.c_str(), _user.c_str(), _pwd.c_str(), _name.c_str(), _port, (_socket == "" ? nullptr : _socket.c_str()), @@ -830,6 +833,9 @@ void mysql_connection::_run() { uint32_t timeout = 10; mysql_options(_conn, MYSQL_OPT_CONNECT_TIMEOUT, &timeout); + mysql_optionsv(_conn, MYSQL_PLUGIN_DIR, + (const void*)_extension_directory.c_str()); + while (config::applier::mode != config::applier::finished && !mysql_real_connect(_conn, _host.c_str(), _user.c_str(), _pwd.c_str(), _name.c_str(), _port, @@ -1076,6 +1082,7 @@ mysql_connection::mysql_connection( _pwd(db_cfg.get_password()), _name(db_cfg.get_name()), _port(db_cfg.get_port()), + _extension_directory(db_cfg.get_extension_directory()), _max_second_commit_delay(db_cfg.get_max_commit_delay()), _last_commit(db_cfg.get_queries_per_transaction() > 1 ? 0 diff --git a/common/inc/com/centreon/common/perfdata.hh b/common/inc/com/centreon/common/perfdata.hh index beaef41610b..cc863df3d21 100644 --- a/common/inc/com/centreon/common/perfdata.hh +++ b/common/inc/com/centreon/common/perfdata.hh @@ -25,17 +25,17 @@ class perfdata { enum data_type { gauge = 0, counter, derive, absolute, automatic }; private: - double _critical; - double _critical_low; + float _critical; + float _critical_low; bool _critical_mode; - double _max; - double _min; + float _max; + float _min; std::string _name; std::string _unit; - double _value; + float _value; data_type _value_type; - double _warning; - double _warning_low; + float _warning; + float _warning_low; bool _warning_mode; public: @@ -48,30 +48,30 @@ class perfdata { perfdata(); ~perfdata() noexcept = default; - double critical() const { return _critical; } - void critical(double c) { _critical = c; } - double critical_low() const { return _critical_low; } - void critical_low(double c) { _critical_low = c; } + float critical() const { return _critical; } + void critical(float c) { _critical = c; } + float critical_low() const { return _critical_low; } + void critical_low(float c) { _critical_low = c; } bool critical_mode() const { return _critical_mode; } void critical_mode(bool val) { _critical_mode = val; } - double max() const { return _max; } - void max(double val) { _max = val; } - double min() const { return _min; } - void min(double val) { _min = val; } + float max() const { return _max; } + void max(float val) { _max = val; } + float min() const { return _min; } + void min(float val) { _min = val; } const std::string& name() const { return _name; } void name(const std::string&& val) { _name = val; } void resize_name(size_t new_size); const std::string& unit() const { return _unit; } void resize_unit(size_t new_size); void unit(const std::string&& val) { _unit = val; } - double value() const { return _value; } - void value(double val) { _value = val; } + float value() const { return _value; } + void value(float val) { _value = val; } data_type value_type() const { return _value_type; }; void value_type(data_type val) { _value_type = val; } - double warning() const { return _warning; } - void warning(double val) { _warning = val; } - double warning_low() const { return _warning_low; } - void warning_low(double val) { _warning_low = val; } + float warning() const { return _warning; } + void warning(float val) { _warning = val; } + float warning_low() const { return _warning_low; } + void warning_low(float val) { _warning_low = val; } bool warning_mode() const { return _warning_mode; } void warning_mode(bool val) { _warning_mode = val; } }; diff --git a/common/tests/perfdata_test.cc b/common/tests/perfdata_test.cc index 25ac9d30cff..487300251bd 100644 --- a/common/tests/perfdata_test.cc +++ b/common/tests/perfdata_test.cc @@ -78,29 +78,29 @@ TEST(PerfData, Assign) { p1.warning_mode(false); // Check objects properties values. - ASSERT_FALSE(fabs(p1.critical() - 9432.5) > 0.00001); - ASSERT_FALSE(fabs(p1.critical_low() - 1000.0001) > 0.00001); + ASSERT_FALSE(fabs(p1.critical() - 9432.5f) > 0.00001f); + ASSERT_TRUE(fabs(p1.critical_low() - 1000.0001f) < 0.0001f); ASSERT_FALSE(!p1.critical_mode()); - ASSERT_FALSE(fabs(p1.max() - 123.0) > 0.00001); - ASSERT_FALSE(fabs(p1.min() - 843.876) > 0.00001); + ASSERT_FALSE(fabs(p1.max() - 123.0f) > 0.00001f); + ASSERT_TRUE(fabs(p1.min() - 843.876f) < 0.0001f); ASSERT_FALSE(p1.name() != "baz"); ASSERT_FALSE(p1.unit() != "qux"); - ASSERT_FALSE(fabs(p1.value() - 3485.9) > 0.00001); + ASSERT_TRUE(fabs(p1.value() - 3485.9f) < 0.0001f); ASSERT_FALSE(p1.value_type() != perfdata::derive); - ASSERT_FALSE(fabs(p1.warning() - 3612.0) > 0.00001); - ASSERT_FALSE(fabs(p1.warning_low() + 987579.0) > 0.01); + ASSERT_FALSE(fabs(p1.warning() - 3612.0f) > 0.00001f); + ASSERT_FALSE(fabs(p1.warning_low() + 987579.0f) > 0.01f); ASSERT_FALSE(p1.warning_mode()); - ASSERT_FALSE(fabs(p2.critical() - 42.0) > 0.00001); - ASSERT_FALSE(fabs(p2.critical_low() + 456.032) > 0.00001); + ASSERT_FALSE(fabs(p2.critical() - 42.0f) > 0.00001f); + ASSERT_FALSE(fabs(p2.critical_low() + 456.032f) > 0.00001f); ASSERT_FALSE(p2.critical_mode()); - ASSERT_FALSE(fabs(p2.max() - 76.3) > 0.00001); - ASSERT_FALSE(fabs(p2.min() - 567.2) > 0.00001); + ASSERT_FALSE(fabs(p2.max() - 76.3f) > 0.00001f); + ASSERT_FALSE(fabs(p2.min() - 567.2f) > 0.00001f); ASSERT_FALSE(p2.name() != "foo"); ASSERT_FALSE(p2.unit() != "bar"); - ASSERT_FALSE(fabs(p2.value() - 52189.912) > 0.00001); + ASSERT_FALSE(fabs(p2.value() - 52189.912f) > 0.00001f); ASSERT_FALSE(p2.value_type() != perfdata::counter); - ASSERT_FALSE(fabs(p2.warning() - 4548.0) > 0.00001); - ASSERT_FALSE(fabs(p2.warning_low() - 42.42) > 0.00001); + ASSERT_FALSE(fabs(p2.warning() - 4548.0f) > 0.00001f); + ASSERT_FALSE(fabs(p2.warning_low() - 42.42f) > 0.00001f); ASSERT_FALSE(!p2.warning_mode()); } @@ -141,29 +141,29 @@ TEST(PerfData, CopyCtor) { p1.warning_mode(false); // Check objects properties values. - ASSERT_FALSE(fabs(p1.critical() - 9432.5) > 0.00001); - ASSERT_FALSE(fabs(p1.critical_low() - 1000.0001) > 0.00001); + ASSERT_FALSE(fabs(p1.critical() - 9432.5f) > 0.00001f); + ASSERT_FALSE(fabs(p1.critical_low() - 1000.0001f) > 0.00001f); ASSERT_FALSE(!p1.critical_mode()); - ASSERT_FALSE(fabs(p1.max() - 123.0) > 0.00001); - ASSERT_FALSE(fabs(p1.min() - 843.876) > 0.00001); + ASSERT_FALSE(fabs(p1.max() - 123.0f) > 0.00001f); + ASSERT_FALSE(fabs(p1.min() - 843.876f) > 0.00001f); ASSERT_FALSE(p1.name() != "baz"); ASSERT_FALSE(p1.unit() != "qux"); - ASSERT_FALSE(fabs(p1.value() - 3485.9) > 0.00001); + ASSERT_FALSE(fabs(p1.value() - 3485.9f) > 0.00001f); ASSERT_FALSE(p1.value_type() != perfdata::derive); - ASSERT_FALSE(fabs(p1.warning() - 3612.0) > 0.00001); - ASSERT_FALSE(fabs(p1.warning_low() + 987579.0) > 0.01); + ASSERT_FALSE(fabs(p1.warning() - 3612.0f) > 0.00001f); + ASSERT_FALSE(fabs(p1.warning_low() + 987579.0f) > 0.01f); ASSERT_FALSE(p1.warning_mode()); - ASSERT_FALSE(fabs(p2.critical() - 42.0) > 0.00001); - ASSERT_FALSE(fabs(p2.critical_low() + 456.032) > 0.00001); + ASSERT_FALSE(fabs(p2.critical() - 42.0f) > 0.00001f); + ASSERT_FALSE(fabs(p2.critical_low() + 456.032f) > 0.00001f); ASSERT_FALSE(p2.critical_mode()); - ASSERT_FALSE(fabs(p2.max() - 76.3) > 0.00001); - ASSERT_FALSE(fabs(p2.min() - 567.2) > 0.00001); + ASSERT_FALSE(fabs(p2.max() - 76.3f) > 0.00001f); + ASSERT_FALSE(fabs(p2.min() - 567.2f) > 0.00001f); ASSERT_FALSE(p2.name() != "foo"); ASSERT_FALSE(p2.unit() != "bar"); - ASSERT_FALSE(fabs(p2.value() - 52189.912) > 0.00001); + ASSERT_FALSE(fabs(p2.value() - 52189.912f) > 0.00001f); ASSERT_FALSE(p2.value_type() != perfdata::counter); - ASSERT_FALSE(fabs(p2.warning() - 4548.0) > 0.00001); - ASSERT_FALSE(fabs(p2.warning_low() - 42.42) > 0.00001); + ASSERT_FALSE(fabs(p2.warning() - 4548.0f) > 0.00001f); + ASSERT_FALSE(fabs(p2.warning_low() - 42.42f) > 0.00001f); ASSERT_FALSE(!p2.warning_mode()); } diff --git a/common/tests/process_test.cc b/common/tests/process_test.cc index 7537532c321..449e000d3bc 100644 --- a/common/tests/process_test.cc +++ b/common/tests/process_test.cc @@ -41,12 +41,24 @@ class process_wait : public process { std::condition_variable _cond; std::string _stdout; std::string _stderr; + bool _stdout_eof = false; + bool _stderr_eof = false; + bool _process_ended = false; + + void _notify() { + if (_stdout_eof && _stderr_eof && _process_ended) { + _cond.notify_one(); + } + } public: void on_stdout_read(const boost::system::error_code& err, size_t nb_read) override { if (!err) { _stdout += std::string_view(_stdout_read_buffer, nb_read); + } else if (err == asio::error::eof) { + _stdout_eof = true; + _notify(); } process::on_stdout_read(err, nb_read); } @@ -55,6 +67,9 @@ class process_wait : public process { size_t nb_read) override { if (!err) { _stderr += std::string_view(_stderr_read_buffer, nb_read); + } else if (err == asio::error::eof) { + _stderr_eof = true; + _notify(); } process::on_stderr_read(err, nb_read); } @@ -62,7 +77,8 @@ class process_wait : public process { void on_process_end(const boost::system::error_code& err, int raw_exit_status) override { process::on_process_end(err, raw_exit_status); - _cond.notify_one(); + _process_ended = true; + _notify(); } template diff --git a/packaging/centreon-broker-core.yaml b/packaging/centreon-broker-core.yaml index 143a9e4b259..61bf0228188 100644 --- a/packaging/centreon-broker-core.yaml +++ b/packaging/centreon-broker-core.yaml @@ -43,6 +43,7 @@ overrides: - centreon-clib = ${VERSION}-${RELEASE}${DIST} - centreon-broker = ${VERSION}-${RELEASE}${DIST} - gnutls >= 3.6.0 + - mariadb-connector-c >= 3.1.10 conflicts: - centreon-broker-storage - centreon-broker-core-devel @@ -59,6 +60,7 @@ overrides: - centreon-broker (= ${VERSION}-${RELEASE}${DIST}) - libgnutls30 - libssl1.1 | libssl3 + - libmariadb3 - zlib1g conflicts: - centreon-broker-storage diff --git a/tests/mysql_docker_conf/centreon16.cnf b/tests/mysql_docker_conf/centreon16.cnf index 3865e9bf923..692a1e39f6c 100644 --- a/tests/mysql_docker_conf/centreon16.cnf +++ b/tests/mysql_docker_conf/centreon16.cnf @@ -1,7 +1,6 @@ [mysqld] #mariadb conf optimized for a 16Gb ram machine port = 3306 -default-authentication-plugin=mysql_native_password max_heap_table_size=1G open_files_limit = 32000 diff --git a/vcpkg.json b/vcpkg.json index 5a4e2b5d1d7..8e2b18a4af3 100644 --- a/vcpkg.json +++ b/vcpkg.json @@ -6,7 +6,6 @@ "cxx17" ] }, - "libmariadb", "libssh2", "curl", "fmt", From 77f546fda305a3bc0b6f5c35199ff97f604710d2 Mon Sep 17 00:00:00 2001 From: tuntoja <58987095+tuntoja@users.noreply.github.com> Date: Fri, 14 Jun 2024 11:06:44 +0200 Subject: [PATCH 39/60] fix(release): handle multi word component name (#1440) * fix(release): handle multi word component name * Update release-trigger-builds.yml --- .github/workflows/release-trigger-builds.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/release-trigger-builds.yml b/.github/workflows/release-trigger-builds.yml index 3398c2a0844..36189338315 100644 --- a/.github/workflows/release-trigger-builds.yml +++ b/.github/workflows/release-trigger-builds.yml @@ -61,13 +61,13 @@ jobs: if [[ "${{ inputs.dispatch_content }}" == "FULL" ]]; then echo "Requested ${{ inputs.dispatch_content }} content, triggering all component workflows." - for COMPONENT in ${COMPONENTS_COLLECT_FULL[@]}; do - gh workflow run $COMPONENT -r ${{ inputs.dispatch_target_release_branch }} + for COMPONENT in "${COMPONENTS_COLLECT_FULL[@]}"; do + gh workflow run "$COMPONENT" -r ${{ inputs.dispatch_target_release_branch }} done else echo "Requested ${{ inputs.dispatch_content }} content, triggering centreon named components only." - for COMPONENT in ${COMPONENTS_COLLECT[@]}; do - gh workflow run $COMPONENT -r ${{ inputs.dispatch_target_release_branch }} + for COMPONENT in "${COMPONENTS_COLLECT[@]}"; do + gh workflow run "$COMPONENT" -r ${{ inputs.dispatch_target_release_branch }} done fi From bf8135baa641f88406119a266f45b5cec62b586b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane=20Chapron?= <34628915+sc979@users.noreply.github.com> Date: Mon, 17 Jun 2024 10:40:59 +0200 Subject: [PATCH 40/60] chore(ci): upgrade action to fix dependabot alert (#1415) --- .github/workflows/veracode-analysis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/veracode-analysis.yml b/.github/workflows/veracode-analysis.yml index 5a29d429e75..412319590f9 100644 --- a/.github/workflows/veracode-analysis.yml +++ b/.github/workflows/veracode-analysis.yml @@ -169,7 +169,7 @@ jobs: key: "${{ inputs.module_name }}-${{ github.sha }}-${{ github.run_id }}-veracode-binary" - name: Sandbox scan - uses: veracode/veracode-uploadandscan-action@f7e1fbf02c5c899fba9f12e3f537b62f2f1230e1 # master using 0.2.6 + uses: veracode/veracode-uploadandscan-action@f7e1fbf02c5c899fba9f12e3f537b62f2f1230e1 # 0.2.7 continue-on-error: ${{ vars.VERACODE_CONTINUE_ON_ERROR == 'true' }} with: appname: "${{ inputs.module_name }}" From 9432b63091f9ca107f64f901c3f2397f685ae33b Mon Sep 17 00:00:00 2001 From: jean-christophe81 <98889244+jean-christophe81@users.noreply.github.com> Date: Mon, 17 Jun 2024 11:10:15 +0200 Subject: [PATCH 41/60] add host_down_disable_service_checks engine config flag (#1441) --- .../centreon/engine/configuration/state.hh | 3 + engine/inc/com/centreon/engine/host.hh | 2 + engine/src/configuration/applier/state.cc | 2 + engine/src/configuration/state.cc | 31 ++++- engine/src/host.cc | 46 ++++++- engine/src/service.cc | 26 +++- tests/bam/inherited_downtime.robot | 10 +- tests/bam/pb_inherited_downtime.robot | 10 +- tests/broker-engine/output-tables.robot | 2 +- tests/engine/forced_checks.robot | 115 ++++++++++++++++-- tests/resources/Common.py | 2 +- tests/resources/Engine.py | 22 ++++ 12 files changed, 245 insertions(+), 26 deletions(-) diff --git a/engine/inc/com/centreon/engine/configuration/state.hh b/engine/inc/com/centreon/engine/configuration/state.hh index b24712ae80c..3b9b25de0c1 100644 --- a/engine/inc/com/centreon/engine/configuration/state.hh +++ b/engine/inc/com/centreon/engine/configuration/state.hh @@ -453,6 +453,8 @@ class state { void use_true_regexp_matching(bool value); bool use_send_recovery_notifications_anyways() const; void use_send_recovery_notifications_anyways(bool value); + bool use_host_down_disable_service_checks() const; + void use_host_down_disable_service_checks(bool value); using setter_map = absl::flat_hash_map>; @@ -658,6 +660,7 @@ class state { std::string _use_timezone; bool _use_true_regexp_matching; bool _send_recovery_notifications_anyways; + bool _host_down_disable_service_checks; }; } // namespace com::centreon::engine::configuration diff --git a/engine/inc/com/centreon/engine/host.hh b/engine/inc/com/centreon/engine/host.hh index c91f28a5e6a..61c533c27ea 100644 --- a/engine/inc/com/centreon/engine/host.hh +++ b/engine/inc/com/centreon/engine/host.hh @@ -262,6 +262,8 @@ class host : public notifier { std::string get_check_command_line(nagios_macros* macros); private: + void _switch_all_services_to_unknown(); + uint64_t _id; std::string _alias; std::string _address; diff --git a/engine/src/configuration/applier/state.cc b/engine/src/configuration/applier/state.cc index c145c0d3ee2..0221be3879e 100644 --- a/engine/src/configuration/applier/state.cc +++ b/engine/src/configuration/applier/state.cc @@ -463,6 +463,8 @@ void applier::state::_apply(configuration::state const& new_cfg) { config->use_true_regexp_matching(new_cfg.use_true_regexp_matching()); config->use_send_recovery_notifications_anyways( new_cfg.use_send_recovery_notifications_anyways()); + config->use_host_down_disable_service_checks( + new_cfg.use_host_down_disable_service_checks()); config->user(new_cfg.user()); // Set this variable just the first time. diff --git a/engine/src/configuration/state.cc b/engine/src/configuration/state.cc index d3fe4d1e0ce..6d532eac453 100644 --- a/engine/src/configuration/state.cc +++ b/engine/src/configuration/state.cc @@ -339,6 +339,8 @@ void state::_init_setter() { SETTER(const std::string&, _set_downtime_file, "xdddefault_downtime_file"); SETTER(bool, use_send_recovery_notifications_anyways, "send_recovery_notifications_anyways"); + SETTER(bool, use_host_down_disable_service_checks, + "host_down_disable_service_checks"); } // Default values. @@ -617,7 +619,8 @@ state::state() _log_level_otl(default_log_level_otl), _use_timezone(default_use_timezone), _use_true_regexp_matching(default_use_true_regexp_matching), - _send_recovery_notifications_anyways(false) { + _send_recovery_notifications_anyways(false), + _host_down_disable_service_checks(false) { static absl::once_flag _init_call_once; absl::call_once(_init_call_once, _init_setter); } @@ -799,6 +802,7 @@ state& state::operator=(state const& right) { _use_true_regexp_matching = right._use_true_regexp_matching; _send_recovery_notifications_anyways = right._send_recovery_notifications_anyways; + _host_down_disable_service_checks = right._host_down_disable_service_checks; } return *this; } @@ -966,7 +970,9 @@ bool state::operator==(state const& right) const noexcept { _use_timezone == right._use_timezone && _use_true_regexp_matching == right._use_true_regexp_matching && _send_recovery_notifications_anyways == - right._send_recovery_notifications_anyways); + right._send_recovery_notifications_anyways && + _host_down_disable_service_checks == + right._host_down_disable_service_checks); } /** @@ -4832,6 +4838,27 @@ void state::use_send_recovery_notifications_anyways(bool value) { _send_recovery_notifications_anyways = value; } +/** + * @brief when this flag is set as soon a host become down, all services become + * critical + * + * @return true + * @return false + */ +bool state::use_host_down_disable_service_checks() const { + return _host_down_disable_service_checks; +} + +/** + * @brief set the host_down_disable_service_checks flag + * when this flag is set as soon a host become down, all services become + * critical + * @param value + */ +void state::use_host_down_disable_service_checks(bool value) { + _host_down_disable_service_checks = value; +} + /** * @brief modify state according json passed in parameter * diff --git a/engine/src/host.cc b/engine/src/host.cc index 4c96ea8b3fe..62508f113b9 100644 --- a/engine/src/host.cc +++ b/engine/src/host.cc @@ -1857,8 +1857,8 @@ int host::run_async_check(int check_options, try { // Run command. get_check_command_ptr()->run(processed_cmd, *macros, - config->host_check_timeout(), - check_result_info); + config->host_check_timeout(), + check_result_info); } catch (com::centreon::exceptions::interruption const& e) { retry = true; } catch (std::exception const& e) { @@ -2330,6 +2330,8 @@ int host::handle_state() { /* update performance data */ update_performance_data(); + bool have_to_change_service_state = false; + /* record latest time for current state */ switch (get_current_state()) { case host::state_up: @@ -2338,10 +2340,16 @@ int host::handle_state() { case host::state_down: set_last_time_down(current_time); + have_to_change_service_state = + config->use_host_down_disable_service_checks() && + get_state_type() == hard; break; case host::state_unreachable: set_last_time_unreachable(current_time); + have_to_change_service_state = + config->use_host_down_disable_service_checks() && + get_state_type() == hard; break; default: @@ -2426,6 +2434,11 @@ int host::handle_state() { /* the host just recovered, so reset the current host attempt */ if (get_current_state() == host::state_up) set_current_attempt(1); + + // have to change service state to UNKNOWN? + if (have_to_change_service_state) { + _switch_all_services_to_unknown(); + } } /* else the host state has not changed */ else { @@ -4076,3 +4089,32 @@ std::string host::get_check_command_line(nagios_macros* macros) { check_command().c_str(), tmp, 0); return get_check_command_ptr()->process_cmd(macros); } + +/** + * @brief when host switch to no up state and have to propagate state to + * services, we push an UNKNOWN check result for each services + * + */ +void host::_switch_all_services_to_unknown() { + timeval tv; + gettimeofday(&tv, nullptr); + + SPDLOG_LOGGER_DEBUG(runtime_logger, + "host {} is down => all service states switch to UNKNOWN", + name()); + + std::string output = fmt::format("host {} is down", name()); + + time_t now = time(nullptr); + + for (auto serv_iter = service::services_by_id.lower_bound({_id, 0}); + serv_iter != service::services_by_id.end() && + serv_iter->first.first == _id; + ++serv_iter) { + check_result::pointer result = std::make_shared( + service_check, serv_iter->second.get(), checkable::check_active, + CHECK_OPTION_NONE, false, 0, tv, tv, false, true, + service::state_unknown, output); + checks::checker::instance().add_check_result_to_reap(result); + } +} \ No newline at end of file diff --git a/engine/src/service.cc b/engine/src/service.cc index bbf1ea09fb0..c4b96d2962c 100644 --- a/engine/src/service.cc +++ b/engine/src/service.cc @@ -1333,6 +1333,10 @@ int service::handle_async_check_result( /* grab the return code */ _current_state = static_cast( queued_check_result.get_return_code()); + SPDLOG_LOGGER_DEBUG( + checks_logger, "now host:{} serv:{} _current_state={} state_type={}", + _hostname, name(), static_cast(_current_state), + (get_state_type() == soft ? "SOFT" : "HARD")); } /* record the last state time */ @@ -1413,7 +1417,9 @@ int service::handle_async_check_result( engine_logger(dbg_checks, most) << "Service has changed state since last check!"; SPDLOG_LOGGER_DEBUG(checks_logger, - "Service has changed state since last check!"); + "Service has changed state since last check {} => {}", + static_cast(_last_state), + static_cast(_current_state)); state_change = true; } @@ -2705,8 +2711,19 @@ int service::run_async_check_local(int check_options, checks::checker::instance().add_check_result_to_reap(check_result_info); }; + bool has_to_execute_check = true; + if (config->use_host_down_disable_service_checks()) { + auto hst = host::hosts_by_id.find(_host_id); + if (hst != host::hosts_by_id.end() && + hst->second->get_current_state() != host::state_up) { + run_failure(fmt::format("host {} is down", hst->second->name())); + has_to_execute_check = false; + } + } + // allowed by whitelist? - if (!command_is_allowed_by_whitelist(processed_cmd, CHECK_TYPE)) { + if (has_to_execute_check && + !command_is_allowed_by_whitelist(processed_cmd, CHECK_TYPE)) { SPDLOG_LOGGER_ERROR( commands_logger, "service {}: this command cannot be executed because of " @@ -2718,7 +2735,10 @@ int service::run_async_check_local(int check_options, "service {}: command not allowed by whitelist {}", name(), processed_cmd); run_failure(configuration::command_blacklist_output); - } else { + has_to_execute_check = false; + } + + if (has_to_execute_check) { bool retry; do { retry = false; diff --git a/tests/bam/inherited_downtime.robot b/tests/bam/inherited_downtime.robot index 3791f248092..999286b3d0a 100644 --- a/tests/bam/inherited_downtime.robot +++ b/tests/bam/inherited_downtime.robot @@ -102,7 +102,7 @@ BEBAMIDT2 # KPI set to critical Ctn Process Service Result Hard host_16 service_314 2 output critical for service_314 - ${result} Ctn Check Service Status With Timeout host_16 service_314 2 60 + ${result} Ctn Check Service Status With Timeout host_16 service_314 2 60 HARD Should Be True ${result} The service (host_16,service_314) is not CRITICAL as expected # The BA should become critical @@ -205,12 +205,12 @@ BEBAMIGNDT1 # KPI set to ok Ctn Process Service Result Hard host_16 service_313 0 output critical for service_313 - ${result} Ctn Check Service Status With Timeout host_16 service_313 0 60 + ${result} Ctn Check Service Status With Timeout host_16 service_313 0 60 HARD Should Be True ${result} The service (host_16,service_313) is not OK as expected # KPI set to critical Ctn Process Service Result Hard host_16 service_314 2 output critical for service_314 - ${result} Ctn Check Service Status With Timeout host_16 service_314 2 60 + ${result} Ctn Check Service Status With Timeout host_16 service_314 2 60 HARD Should Be True ${result} The service (host_16,service_314) is not CRITICAL as expected # The BA should become critical @@ -304,12 +304,12 @@ BEBAMIGNDT2 # KPI set to ok Ctn Process Service Result Hard host_16 service_313 0 output critical for service_313 - ${result} Ctn Check Service Status With Timeout host_16 service_313 0 60 + ${result} Ctn Check Service Status With Timeout host_16 service_313 0 60 HARD Should Be True ${result} The service (host_16,service_313) is not OK as expected # KPI set to critical Ctn Process Service Result Hard host_16 service_314 2 output critical for 314 - ${result} Ctn Check Service Status With Timeout host_16 service_314 2 60 + ${result} Ctn Check Service Status With Timeout host_16 service_314 2 60 HARD Should Be True ${result} The service (host_16,service_314) is not CRITICAL as expected # The BA should become critical diff --git a/tests/bam/pb_inherited_downtime.robot b/tests/bam/pb_inherited_downtime.robot index ab150fa9277..a6a22278e9b 100644 --- a/tests/bam/pb_inherited_downtime.robot +++ b/tests/bam/pb_inherited_downtime.robot @@ -104,7 +104,7 @@ BEBAMIDTU2 # KPI set to critical Ctn Process Service Result Hard host_16 service_314 2 output critical for 314 - ${result} Ctn Check Service Status With Timeout host_16 service_314 2 60 + ${result} Ctn Check Service Status With Timeout host_16 service_314 2 60 HARD Should Be True ${result} The service (host_16,service_314) is not CRITICAL as expected # The BA should become critical @@ -204,12 +204,12 @@ BEBAMIGNDTU1 # KPI set to ok Ctn Process Service Result Hard host_16 service_313 0 output critical for 313 - ${result} Ctn Check Service Status With Timeout host_16 service_313 0 60 + ${result} Ctn Check Service Status With Timeout host_16 service_313 0 60 HARD Should Be True ${result} The service (host_16,service_313) is not OK as expected # KPI set to critical Ctn Process Service Result Hard host_16 service_314 2 output critical for 314 - ${result} Ctn Check Service Status With Timeout host_16 service_314 2 60 + ${result} Ctn Check Service Status With Timeout host_16 service_314 2 60 HARD Should Be True ${result} The service (host_16,service_314) is not CRITICAL as expected # The BA should become critical @@ -305,12 +305,12 @@ BEBAMIGNDTU2 # KPI set to ok Ctn Process Service Result Hard host_16 service_313 0 output critical for 313 - ${result} Ctn Check Service Status With Timeout host_16 service_313 0 60 + ${result} Ctn Check Service Status With Timeout host_16 service_313 0 60 HARD Should Be True ${result} The service (host_16,service_313) is not OK as expected # KPI set to critical Ctn Process Service Result Hard host_16 service_314 2 output critical for 314 - ${result} Ctn Check Service Status With Timeout host_16 service_314 2 60 + ${result} Ctn Check Service Status With Timeout host_16 service_314 2 60 HARD Should Be True ${result} The service (host_16,service_314) is not CRITICAL as expected # The BA should become critical diff --git a/tests/broker-engine/output-tables.robot b/tests/broker-engine/output-tables.robot index b62670b812a..cdd8adf1cfe 100644 --- a/tests/broker-engine/output-tables.robot +++ b/tests/broker-engine/output-tables.robot @@ -198,7 +198,7 @@ BE_NOTIF_OVERFLOW Ctn Set Svc Notification Number host_16 service_314 40000 Ctn Process Service Result Hard host_16 service_314 2 output critical for 314 - ${result} Ctn Check Service Status With Timeout host_16 service_314 2 30 + ${result} Ctn Check Service Status With Timeout host_16 service_314 2 30 HARD Should Be True ${result} The service (host_16,service_314) is not CRITICAL as expected Connect To Database pymysql ${DBName} ${DBUser} ${DBPass} ${DBHost} ${DBPort} diff --git a/tests/engine/forced_checks.robot b/tests/engine/forced_checks.robot index 276089affa3..d7b3b81b0ce 100644 --- a/tests/engine/forced_checks.robot +++ b/tests/engine/forced_checks.robot @@ -26,7 +26,7 @@ EFHC1 Ctn Clear Retention Ctn Clear Db hosts ${start} Get Current Date - Ctn Start engine + Ctn Start Engine Ctn Start Broker ${result} Ctn Check Host Status host_1 4 1 False Should Be True ${result} host_1 should be pending @@ -72,7 +72,7 @@ EFHC2 Ctn Clear Retention ${start} Get Current Date - Ctn Start engine + Ctn Start Engine Ctn Start Broker ${content} Create List INITIAL HOST STATE: host_1; ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 60 @@ -120,7 +120,7 @@ EFHCU1 Ctn Clear Retention Ctn Clear Db resources ${start} Get Current Date - Ctn Start engine + Ctn Start Engine Ctn Start Broker ${result} Ctn Check Host Status host_1 4 1 True Should Be True ${result} host_1 should be pending @@ -169,7 +169,7 @@ EFHCU2 Ctn Clear Retention ${start} Get Current Date - Ctn Start engine + Ctn Start Engine Ctn Start Broker ${result} Ctn Check Host Status host_1 4 1 True Should Be True ${result} host_1 should be pending @@ -215,7 +215,7 @@ EMACROS ... /bin/echo "ResourceFile: $RESOURCEFILE$ - LogFile: $LOGFILE$ - AdminEmail: $ADMINEMAIL$ - AdminPager: $ADMINPAGER$" Ctn Clear Retention ${start} Get Current Date - Ctn Start engine + Ctn Start Engine Ctn Start Broker ${content} Create List INITIAL HOST STATE: host_1; @@ -258,7 +258,7 @@ EMACROS_NOTIF Remove File /tmp/notif_toto.txt Ctn Clear Retention ${start} Get Current Date - Ctn Start engine + Ctn Start Engine Ctn Start Broker ${content} Create List INITIAL HOST STATE: host_1; @@ -297,7 +297,7 @@ EMACROS_SEMICOLON ... /bin/echo "KEY2=$_HOSTKEY2$" Ctn Clear Retention ${start} Get Current Date - Ctn Start engine + Ctn Start Engine Ctn Start Broker ${content} Create List INITIAL HOST STATE: host_1; @@ -314,3 +314,104 @@ EMACROS_SEMICOLON Ctn Stop engine Ctn Kindly Stop Broker + +E_HOST_DOWN_DISABLE_SERVICE_CHECKS + [Documentation] host_down_disable_service_checks is set to 1, host down switch all services to UNKNOWN + [Tags] engine MON-32780 + Ctn Config Engine ${1} 2 20 + Ctn Set Hosts Passive 0 host_.* + Ctn Engine Config Set Value 0 host_down_disable_service_checks ${1} ${True} + Ctn Config Broker central + Ctn Config Broker module ${1} + + Ctn Clear Retention + ${start} Get Current Date + + ${start} Get Current Date + Ctn Start Engine + Ctn Start Broker only_central=${True} + + ${content} Create List INITIAL HOST STATE: host_1; + ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 60 + Should Be True + ... ${result} + ... An Initial host state on host_1 should be raised before we can start our external commands. + + FOR ${i} IN RANGE ${4} + Ctn Process Host Check Result host_1 1 host_1 DOWN + END + + ${result} Ctn Check Host Status host_1 1 1 False 30 + Should Be True ${result} host_1 should be down/hard + + #after some time services should be in hard state + FOR ${index} IN RANGE ${19} + ${result} Ctn Check Service Status With Timeout host_1 service_${index+1} 3 30 HARD + Should Be True ${result} service_${index+1} should be UNKNOWN hard + END + + #host_1 check returns UP + Ctn Set Command Status checkh1 0 + Ctn Process Host Check Result host_1 0 host_1 UP + + #after some time services should be in ok hard state + FOR ${index} IN RANGE ${19} + Ctn Process Service Check Result host_1 service_${index+1} 0 output + END + FOR ${index} IN RANGE ${19} + ${result} Ctn Check Service Status With Timeout host_1 service_${index+1} 0 30 HARD + Should Be True ${result} service_${index+1} should be OK hard + END + + + [Teardown] Ctn Stop Engine Broker And Save Logs only_central=${True} + +E_HOST_UNREACHABLE_DISABLE_SERVICE_CHECKS + [Documentation] host_down_disable_service_checks is set to 1, host unreachable switch all services to UNKNOWN + [Tags] engine MON-32780 + Ctn Config Engine ${1} 2 20 + Ctn Engine Config Set Value 0 host_down_disable_service_checks ${1} ${True} + Ctn Engine Config Set Value 0 log_level_runtime trace + Ctn Engine Config Set Value 0 log_level_checks trace + Ctn Add Parent To Host 0 host_1 host_2 + Ctn Set Hosts Passive 0 host_.* + Ctn Config Broker central + Ctn Config Broker module ${1} + + Ctn Clear Retention + ${start} Get Current Date + + ${start} Get Current Date + Ctn Start Engine + Ctn Start Broker only_central=${True} + + ${content} Create List INITIAL HOST STATE: host_1; + ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 60 + Should Be True + ... ${result} + ... An Initial host state on host_1 should be raised before we can start our external commands. + + + FOR ${i} IN RANGE ${4} + Ctn Process Host Check Result host_2 1 host_2 down + END + + ${result} Ctn Check Host Status host_2 1 1 False 30 + Should Be True ${result} host_2 should be down/hard + + FOR ${i} IN RANGE ${4} + Ctn Process Host Check Result host_1 1 host_1 down + END + + + ${result} Ctn Check Host Status host_1 2 1 False 30 + Should Be True ${result} host_1 should be unreachable/hard + + #after some time services should be in hard state + FOR ${index} IN RANGE ${19} + ${result} Ctn Check Service Status With Timeout host_1 service_${index+1} 3 30 HARD + Should Be True ${result} service_${index+1} should be UNKNOWN hard + END + + [Teardown] Ctn Stop Engine Broker And Save Logs only_central=${True} + diff --git a/tests/resources/Common.py b/tests/resources/Common.py index f906646bdfe..20fa11819bf 100644 --- a/tests/resources/Common.py +++ b/tests/resources/Common.py @@ -703,7 +703,7 @@ def ctn_check_service_status_with_timeout(hostname: str, service_desc: str, stat f"status={result[0]['state']} and state_type={result[0]['state_type']}") if state_type == 'HARD' and int(result[0]['state_type']) == 1: return True - elif state_type != 'HARD': + elif state_type != 'HARD' and int(result[0]['state_type']) == 0: return True time.sleep(1) return False diff --git a/tests/resources/Engine.py b/tests/resources/Engine.py index b30ef3a99e6..e0562834e47 100755 --- a/tests/resources/Engine.py +++ b/tests/resources/Engine.py @@ -2465,6 +2465,28 @@ def ctn_set_services_passive(poller: int, srv_regex): with open("{}/config{}/services.cfg".format(CONF_DIR, poller), "w") as ff: ff.writelines(lines) +def ctn_set_hosts_passive(poller: int, host_regex): + """ + Set passive a list of hosts. + + Args: + poller (int): Index of the poller to work with. + srv_regex (str): A regexp to match host name. + """ + + with open("{}/config{}/hosts.cfg".format(CONF_DIR, poller), "r") as ff: + lines = ff.readlines() + r = re.compile(f"^\s*host_name\s*({host_regex})$") + for i in range(len(lines)): + m = r.match(lines[i]) + if m: + lines.insert(i+1, " active_checks_enabled 0\n") + lines.insert(i+2, " passive_checks_enabled 1\n") + i += 2 + + with open("{}/config{}/hosts.cfg".format(CONF_DIR, poller), "w") as ff: + ff.writelines(lines) + def ctn_add_severity_to_hosts(poller: int, severity_id: int, svc_lst): """ From e464526ca999cdb4c28340ca384de1fe1e1f0bcd Mon Sep 17 00:00:00 2001 From: tuntoja <58987095+tuntoja@users.noreply.github.com> Date: Mon, 17 Jun 2024 15:06:26 +0200 Subject: [PATCH 42/60] chore(ci): add 24.04 to nightly collect (#1443) --- .github/workflows/robot-nightly.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/robot-nightly.yml b/.github/workflows/robot-nightly.yml index 38836730e2e..3ce8b5df421 100644 --- a/.github/workflows/robot-nightly.yml +++ b/.github/workflows/robot-nightly.yml @@ -19,6 +19,7 @@ jobs: uses: actions/checkout@0ad4b8fadaa221de15dcec353f45205ec38ea70b # v4.1.4 - run: | + gh workflow run robot-nightly.yml -r "dev-24.04.x" gh workflow run robot-nightly.yml -r "dev-23.10.x" gh workflow run robot-nightly.yml -r "dev-23.04.x" gh workflow run robot-nightly.yml -r "dev-22.10.x" From 56c0e9b38e45c75ffbe988fe64955232f9643f0d Mon Sep 17 00:00:00 2001 From: David Boucher Date: Mon, 17 Jun 2024 15:29:12 +0200 Subject: [PATCH 43/60] enh(engine/configuration): Uuid no more used in escalations * enh(engine/configuration): Uuid no more used in escalations * enh(engine/configuration):shared.hh removed from escalation configurations files * fix(engine): servicedependencies contained legacy code to remove REFS: MON-34072 --- .../inc/com/centreon/broker/stats/center.hh | 4 +- broker/neb/src/callbacks.cc | 3 +- common/inc/com/centreon/common/process.hh | 2 +- .../configuration/applier/hostdependency.hh | 60 ++++++------ .../configuration/applier/hostescalation.hh | 61 ++++++------ .../applier/servicedependency.hh | 25 ++--- .../engine/configuration/applier/state.hh | 22 ++--- .../configuration/applier/timeperiod.hh | 62 +++++++------ .../engine/configuration/hostdependency.hh | 5 +- .../engine/configuration/hostescalation.hh | 5 +- .../centreon/engine/configuration/object.hh | 2 +- .../engine/configuration/servicedependency.hh | 5 +- .../engine/configuration/serviceescalation.hh | 41 ++++---- engine/inc/com/centreon/engine/dependency.hh | 55 ++++++----- engine/inc/com/centreon/engine/escalation.hh | 60 ++++++------ .../inc/com/centreon/engine/hostdependency.hh | 46 ++++----- .../inc/com/centreon/engine/hostescalation.hh | 50 +++++----- .../com/centreon/engine/servicedependency.hh | 60 ++++++------ .../com/centreon/engine/serviceescalation.hh | 48 +++++----- engine/src/anomalydetection.cc | 2 - engine/src/checkable.cc | 29 +++--- .../configuration/applier/hostdependency.cc | 16 +--- .../configuration/applier/hostescalation.cc | 17 +--- .../applier/servicedependency.cc | 3 +- .../applier/serviceescalation.cc | 13 ++- engine/src/configuration/applier/state.cc | 8 +- .../src/configuration/applier/timeperiod.cc | 30 ------ engine/src/configuration/hostdependency.cc | 15 ++- engine/src/configuration/hostescalation.cc | 26 +++--- engine/src/configuration/object.cc | 5 - engine/src/configuration/servicedependency.cc | 19 +++- engine/src/configuration/serviceescalation.cc | 25 +++-- engine/src/dependency.cc | 37 ++++---- engine/src/escalation.cc | 36 ++++--- engine/src/hostdependency.cc | 77 +++++---------- engine/src/hostescalation.cc | 50 ++++++---- engine/src/servicedependency.cc | 93 +++++++------------ engine/src/serviceescalation.cc | 55 +++++++---- .../applier/applier-hostescalation.cc | 18 ++++ .../applier/applier-serviceescalation.cc | 35 +++++++ .../host_downtime_notification.cc | 4 +- .../host_flapping_notification.cc | 9 +- .../notifications/host_normal_notification.cc | 32 +++---- .../host_recovery_notification.cc | 3 +- .../service_flapping_notification.cc | 6 +- .../service_normal_notification.cc | 40 ++++---- 46 files changed, 669 insertions(+), 650 deletions(-) diff --git a/broker/core/inc/com/centreon/broker/stats/center.hh b/broker/core/inc/com/centreon/broker/stats/center.hh index d474fc77040..62f5cfd57a1 100644 --- a/broker/core/inc/com/centreon/broker/stats/center.hh +++ b/broker/core/inc/com/centreon/broker/stats/center.hh @@ -96,8 +96,8 @@ class center { void get_processing_stats(ProcessingStats* response) ABSL_LOCKS_EXCLUDED(_stats_m); const BrokerStats& stats() const; - void lock() ABSL_EXCLUSIVE_LOCK_FUNCTION(_stats); - void unlock() ABSL_UNLOCK_FUNCTION(_stats); + void lock() ABSL_EXCLUSIVE_LOCK_FUNCTION(_stats_m); + void unlock() ABSL_UNLOCK_FUNCTION(_stats_m); /** * @brief Set the value pointed by ptr to the value value. diff --git a/broker/neb/src/callbacks.cc b/broker/neb/src/callbacks.cc index cf3c7ffdaea..eca357ed58e 100644 --- a/broker/neb/src/callbacks.cc +++ b/broker/neb/src/callbacks.cc @@ -4075,7 +4075,8 @@ class otl_protobuf } void set_obj(opentelemetry::proto::collector::metrics::v1:: - ExportMetricsServiceRequest&& obj) override { + ExportMetricsServiceRequest&& obj + [[maybe_unused]]) override { throw com::centreon::exceptions::msg_fmt("unauthorized usage {}", typeid(*this).name()); } diff --git a/common/inc/com/centreon/common/process.hh b/common/inc/com/centreon/common/process.hh index bc9ef7902bb..74562bfc18b 100644 --- a/common/inc/com/centreon/common/process.hh +++ b/common/inc/com/centreon/common/process.hh @@ -46,7 +46,7 @@ class process : public std::enable_shared_from_this { std::deque> _stdin_write_queue ABSL_GUARDED_BY(_protect); - bool _write_pending = false ABSL_GUARDED_BY(_protect); + bool _write_pending ABSL_GUARDED_BY(_protect) = false; std::shared_ptr _proc ABSL_GUARDED_BY(_protect); diff --git a/engine/inc/com/centreon/engine/configuration/applier/hostdependency.hh b/engine/inc/com/centreon/engine/configuration/applier/hostdependency.hh index 3a47909e42b..49993874a05 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/hostdependency.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/hostdependency.hh @@ -1,22 +1,21 @@ -/* -** Copyright 2011-2013,2017 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2013,2017 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCE_CONFIGURATION_APPLIER_HOSTDEPENDENCY_HH #define CCE_CONFIGURATION_APPLIER_HOSTDEPENDENCY_HH @@ -29,26 +28,25 @@ class state; namespace applier { class hostdependency { + void _expand_hosts(std::set const& hosts, + std::set const& hostgroups, + configuration::state& s, + std::set& expanded); + public: - hostdependency(); - hostdependency(hostdependency const& right) = delete; - ~hostdependency() throw(); - hostdependency& operator=(hostdependency const& right) = delete; + hostdependency() = default; + hostdependency(const hostdependency&) = delete; + ~hostdependency() noexcept = default; + hostdependency& operator=(const hostdependency&) = delete; void add_object(configuration::hostdependency const& obj); - void expand_objects(configuration::state& s); void modify_object(configuration::hostdependency const& obj); void remove_object(configuration::hostdependency const& obj); + void expand_objects(configuration::state& s); void resolve_object(configuration::hostdependency const& obj); - - private: - void _expand_hosts(std::set const& hosts, - std::set const& hostgroups, - configuration::state& s, - std::set& expanded); }; } // namespace applier } // namespace configuration -} +} // namespace com::centreon::engine #endif // !CCE_CONFIGURATION_APPLIER_HOSTDEPENDENCY_HH diff --git a/engine/inc/com/centreon/engine/configuration/applier/hostescalation.hh b/engine/inc/com/centreon/engine/configuration/applier/hostescalation.hh index 0acf789bca3..868f01f7050 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/hostescalation.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/hostescalation.hh @@ -1,22 +1,20 @@ -/* -** Copyright 2011-2013,2017 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2013,2017-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCE_CONFIGURATION_APPLIER_HOSTESCALATION_HH #define CCE_CONFIGURATION_APPLIER_HOSTESCALATION_HH @@ -29,28 +27,27 @@ class state; namespace applier { class hostescalation { - public: - hostescalation(); - hostescalation(hostescalation const& right) = delete; - ~hostescalation() throw(); - hostescalation& operator=(hostescalation const& right) = delete; - void add_object(configuration::hostescalation const& obj); - void expand_objects(configuration::state& s); - void modify_object(configuration::hostescalation const& obj); - void remove_object(configuration::hostescalation const& obj); - void resolve_object(configuration::hostescalation const& obj); - - private: void _expand_hosts(std::set const& h, std::set const& hg, configuration::state const& s, std::set& expanded); void _inherits_special_vars(configuration::hostescalation& obj, configuration::state& s); + + public: + hostescalation() = default; + ~hostescalation() noexcept = default; + hostescalation(hostescalation const&) = delete; + hostescalation& operator=(hostescalation const&) = delete; + void add_object(const configuration::hostescalation& obj); + void modify_object(configuration::hostescalation const& obj); + void remove_object(configuration::hostescalation const& obj); + void expand_objects(configuration::state& s); + void resolve_object(configuration::hostescalation const& obj); }; } // namespace applier } // namespace configuration -} +} // namespace com::centreon::engine #endif // !CCE_CONFIGURATION_APPLIER_HOSTESCALATION_HH diff --git a/engine/inc/com/centreon/engine/configuration/applier/servicedependency.hh b/engine/inc/com/centreon/engine/configuration/applier/servicedependency.hh index 3e8ca2814ce..cc25eefe498 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/servicedependency.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/servicedependency.hh @@ -1,22 +1,21 @@ /** * Copyright 2011-2013,2017 Centreon * - * This file is part of Centreon Engine. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Centreon Engine is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License version 2 - * as published by the Free Software Foundation. + * http://www.apache.org/licenses/LICENSE-2.0 * - * Centreon Engine is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com * - * You should have received a copy of the GNU General Public License - * along with Centreon Engine. If not, see - * . */ - #ifndef CCE_CONFIGURATION_APPLIER_SERVICEDEPENDENCY_HH #define CCE_CONFIGURATION_APPLIER_SERVICEDEPENDENCY_HH @@ -27,6 +26,8 @@ namespace configuration { class servicedependency; class state; +size_t servicedependency_key(const servicedependency& sd); + namespace applier { class servicedependency { void _expand_services( diff --git a/engine/inc/com/centreon/engine/configuration/applier/state.hh b/engine/inc/com/centreon/engine/configuration/applier/state.hh index 888f89eecd5..8257dd51411 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/state.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/state.hh @@ -1,22 +1,20 @@ /** * Copyright 2011-2024 Centreon * - * This file is part of Centreon Engine. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Centreon Engine is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License version 2 - * as published by the Free Software Foundation. + * http://www.apache.org/licenses/LICENSE-2.0 * - * Centreon Engine is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. * - * You should have received a copy of the GNU General Public License - * along with Centreon Engine. If not, see - * . + * For more information : contact@centreon.com */ - #ifndef CCE_CONFIGURATION_APPLIER_STATE_HH #define CCE_CONFIGURATION_APPLIER_STATE_HH diff --git a/engine/inc/com/centreon/engine/configuration/applier/timeperiod.hh b/engine/inc/com/centreon/engine/configuration/applier/timeperiod.hh index 323555daec7..206616c6077 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/timeperiod.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/timeperiod.hh @@ -1,22 +1,20 @@ -/* -** Copyright 2011-2013,2017 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2013,2017-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCE_CONFIGURATION_APPLIER_TIMEPERIOD_HH #define CCE_CONFIGURATION_APPLIER_TIMEPERIOD_HH @@ -32,24 +30,30 @@ class timeperiod; namespace applier { class timeperiod { + void _add_exclusions(std::set const& exclusions, + com::centreon::engine::timeperiod* tp); + public: - timeperiod(); - timeperiod(timeperiod const& right); - ~timeperiod() throw(); - timeperiod& operator=(timeperiod const& right); - void add_object(configuration::timeperiod const& obj); + /** + * @brief Default constructor. + */ + timeperiod() = default; + + /** + * @brief Destructor. + */ + ~timeperiod() noexcept = default; + timeperiod(const timeperiod&) = delete; + timeperiod& operator=(const timeperiod&) = delete; + void add_object(const configuration::timeperiod& obj); void expand_objects(configuration::state& s); void modify_object(configuration::timeperiod const& obj); void remove_object(configuration::timeperiod const& obj); void resolve_object(configuration::timeperiod const& obj); - - private: - void _add_exclusions(std::set const& exclusions, - com::centreon::engine::timeperiod* tp); }; } // namespace applier } // namespace configuration -} +} // namespace com::centreon::engine #endif // !CCE_CONFIGURATION_APPLIER_TIMEPERIOD_HH diff --git a/engine/inc/com/centreon/engine/configuration/hostdependency.hh b/engine/inc/com/centreon/engine/configuration/hostdependency.hh index 3755f385724..e3f3130bd82 100644 --- a/engine/inc/com/centreon/engine/configuration/hostdependency.hh +++ b/engine/inc/com/centreon/engine/configuration/hostdependency.hh @@ -26,6 +26,7 @@ namespace com::centreon::engine { namespace configuration { + class hostdependency : public object { public: enum action_on { @@ -44,7 +45,7 @@ class hostdependency : public object { hostdependency(); hostdependency(hostdependency const& right); - ~hostdependency() throw() override; + ~hostdependency() noexcept override = default; hostdependency& operator=(hostdependency const& right); bool operator==(hostdependency const& right) const throw(); bool operator!=(hostdependency const& right) const throw(); @@ -97,6 +98,8 @@ class hostdependency : public object { static std::unordered_map const _setters; }; +size_t hostdependency_key(const hostdependency& hd); + typedef std::shared_ptr hostdependency_ptr; typedef std::set set_hostdependency; } // namespace configuration diff --git a/engine/inc/com/centreon/engine/configuration/hostescalation.hh b/engine/inc/com/centreon/engine/configuration/hostescalation.hh index 5c5a286a492..9f6bb6f8e7c 100644 --- a/engine/inc/com/centreon/engine/configuration/hostescalation.hh +++ b/engine/inc/com/centreon/engine/configuration/hostescalation.hh @@ -22,7 +22,6 @@ #include "com/centreon/engine/configuration/group.hh" #include "com/centreon/engine/configuration/object.hh" #include "com/centreon/engine/opt.hh" -#include "com/centreon/engine/shared.hh" namespace com::centreon::engine { @@ -68,7 +67,6 @@ class hostescalation : public object { void notification_interval(unsigned int interval); unsigned int notification_interval() const throw(); bool notification_interval_defined() const throw(); - Uuid const& uuid() const; private: typedef bool (*setter_func)(hostescalation&, char const*); @@ -91,9 +89,10 @@ class hostescalation : public object { opt _last_notification; opt _notification_interval; static std::unordered_map const _setters; - Uuid _uuid; }; +size_t hostescalation_key(const hostescalation& he); + typedef std::shared_ptr hostescalation_ptr; typedef std::set set_hostescalation; } // namespace configuration diff --git a/engine/inc/com/centreon/engine/configuration/object.hh b/engine/inc/com/centreon/engine/configuration/object.hh index 62ccea67a47..534f467c7c0 100644 --- a/engine/inc/com/centreon/engine/configuration/object.hh +++ b/engine/inc/com/centreon/engine/configuration/object.hh @@ -51,7 +51,7 @@ class object { object(object_type type); object(object const& right); - virtual ~object() noexcept; + virtual ~object() noexcept = default; object& operator=(object const& right); bool operator==(object const& right) const noexcept; bool operator!=(object const& right) const noexcept; diff --git a/engine/inc/com/centreon/engine/configuration/servicedependency.hh b/engine/inc/com/centreon/engine/configuration/servicedependency.hh index abac725b73e..aff57a849b4 100644 --- a/engine/inc/com/centreon/engine/configuration/servicedependency.hh +++ b/engine/inc/com/centreon/engine/configuration/servicedependency.hh @@ -26,6 +26,7 @@ namespace com::centreon::engine { namespace configuration { + class servicedependency : public object { public: enum action_on { @@ -45,7 +46,7 @@ class servicedependency : public object { servicedependency(); servicedependency(servicedependency const& right); - ~servicedependency() throw() override; + ~servicedependency() noexcept override = default; servicedependency& operator=(servicedependency const& right); bool operator==(servicedependency const& right) const throw(); bool operator!=(servicedependency const& right) const throw(); @@ -114,6 +115,8 @@ class servicedependency : public object { static std::unordered_map const _setters; }; +size_t servicedependency_key(const servicedependency& sd); + typedef std::shared_ptr servicedependency_ptr; typedef std::set set_servicedependency; } // namespace configuration diff --git a/engine/inc/com/centreon/engine/configuration/serviceescalation.hh b/engine/inc/com/centreon/engine/configuration/serviceescalation.hh index a24daa83226..b122c39315b 100644 --- a/engine/inc/com/centreon/engine/configuration/serviceescalation.hh +++ b/engine/inc/com/centreon/engine/configuration/serviceescalation.hh @@ -22,7 +22,6 @@ #include "com/centreon/engine/configuration/group.hh" #include "com/centreon/engine/configuration/object.hh" #include "com/centreon/engine/opt.hh" -#include "com/centreon/engine/shared.hh" namespace com::centreon::engine::configuration { @@ -40,7 +39,6 @@ class serviceescalation : public object { group _servicegroups; group _service_description; static std::unordered_map const _setters; - Uuid _uuid; bool _set_contactgroups(std::string const& value); bool _set_escalation_options(std::string const& value); @@ -72,7 +70,7 @@ class serviceescalation : public object { bool operator!=(serviceescalation const& right) const noexcept; bool operator<(serviceescalation const& right) const; void check_validity() const override; - key_type const& key() const throw(); + key_type const& key() const noexcept; void merge(object const& obj) override; bool parse(char const* key, char const* value) override; @@ -82,26 +80,27 @@ class serviceescalation : public object { void escalation_options(unsigned int options) noexcept; unsigned short escalation_options() const noexcept; void escalation_period(std::string const& period); - std::string const& escalation_period() const throw(); - bool escalation_period_defined() const throw(); - void first_notification(unsigned int n) throw(); - unsigned int first_notification() const throw(); - list_string& hostgroups() throw(); - list_string const& hostgroups() const throw(); - list_string& hosts() throw(); - list_string const& hosts() const throw(); - void last_notification(unsigned int options) throw(); - unsigned int last_notification() const throw(); - void notification_interval(unsigned int interval) throw(); - unsigned int notification_interval() const throw(); - bool notification_interval_defined() const throw(); - list_string& servicegroups() throw(); - list_string const& servicegroups() const throw(); - list_string& service_description() throw(); - list_string const& service_description() const throw(); - Uuid const& uuid() const; + std::string const& escalation_period() const noexcept; + bool escalation_period_defined() const noexcept; + void first_notification(unsigned int n) noexcept; + unsigned int first_notification() const noexcept; + list_string& hostgroups() noexcept; + list_string const& hostgroups() const noexcept; + list_string& hosts() noexcept; + list_string const& hosts() const noexcept; + void last_notification(unsigned int options) noexcept; + unsigned int last_notification() const noexcept; + void notification_interval(unsigned int interval) noexcept; + unsigned int notification_interval() const noexcept; + bool notification_interval_defined() const noexcept; + list_string& servicegroups() noexcept; + list_string const& servicegroups() const noexcept; + list_string& service_description() noexcept; + list_string const& service_description() const noexcept; }; +size_t serviceescalation_key(const serviceescalation& he); + typedef std::shared_ptr serviceescalation_ptr; typedef std::set set_serviceescalation; } // namespace com::centreon::engine::configuration diff --git a/engine/inc/com/centreon/engine/dependency.hh b/engine/inc/com/centreon/engine/dependency.hh index 5bbcd91b567..756c70d7b19 100644 --- a/engine/inc/com/centreon/engine/dependency.hh +++ b/engine/inc/com/centreon/engine/dependency.hh @@ -1,40 +1,44 @@ -/* -** Copyright 2011-2019 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CENTREON_ENGINE_DEPENDENCY_HH #define CENTREON_ENGINE_DEPENDENCY_HH #include -namespace com::centreon::engine {; +namespace com::centreon::engine { class dependency { + /* This key is a hash of the configuration attributes of this hostdependency, + * essentially used when a new configuration is applied to engine. */ + const size_t _internal_key; + public: enum types { notification = 1, execution }; - dependency(std::string const& dependent_hostname, - std::string const& hostname, + dependency(size_t key, + const std::string& dependent_hostname, + const std::string& hostname, types dependency_type, bool inherits_parent, bool fail_on_pending, - std::string const& dependency_period); - virtual ~dependency() {} + const std::string& dependency_period); + virtual ~dependency() noexcept = default; types get_dependency_type() const; void set_dependency_type(types dependency_type); @@ -57,6 +61,7 @@ class dependency { virtual bool operator==(dependency const& obj) throw(); bool operator!=(dependency const& obj) throw(); virtual bool operator<(dependency const& obj) throw(); + size_t internal_key() const; com::centreon::engine::timeperiod* dependency_period_ptr; @@ -71,6 +76,6 @@ class dependency { bool _contains_circular_path; }; -}; +}; // namespace com::centreon::engine #endif // CENTREON_ENGINE_DEPENDENCY_HH diff --git a/engine/inc/com/centreon/engine/escalation.hh b/engine/inc/com/centreon/engine/escalation.hh index 4db5c189d05..24a1cb4d693 100644 --- a/engine/inc/com/centreon/engine/escalation.hh +++ b/engine/inc/com/centreon/engine/escalation.hh @@ -1,22 +1,20 @@ -/* -** Copyright 2011-2019 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCE_ESCALATION_HH #define CCE_ESCALATION_HH @@ -29,13 +27,22 @@ namespace com::centreon::engine { class timeperiod; class escalation { + uint32_t _first_notification; + uint32_t _last_notification; + double _notification_interval; + std::string _escalation_period; + uint32_t _escalate_on; + contactgroup_map_unsafe _contact_groups; + const size_t _internal_key; + public: escalation(uint32_t first_notification, uint32_t last_notification, double notification_interval, std::string const& escalation_period, uint32_t escalate_on, - Uuid const& uuid); + const size_t key); + virtual ~escalation() noexcept = default; std::string const& get_escalation_period() const; uint32_t get_first_notification() const; @@ -48,7 +55,7 @@ class escalation { bool get_escalate_on(notifier::notification_flag type) const; void set_escalate_on(uint32_t escalate_on); virtual bool is_viable(int state, uint32_t notification_number) const; - Uuid const& get_uuid() const; + size_t internal_key() const; contactgroup_map_unsafe const& get_contactgroups() const; contactgroup_map_unsafe& get_contactgroups(); @@ -56,16 +63,7 @@ class escalation { notifier* notifier_ptr; timeperiod* escalation_period_ptr; - - private: - uint32_t _first_notification; - uint32_t _last_notification; - double _notification_interval; - std::string _escalation_period; - uint32_t _escalate_on; - contactgroup_map_unsafe _contact_groups; - Uuid _uuid; }; -} +} // namespace com::centreon::engine #endif // !CCE_ESCALATION_HH diff --git a/engine/inc/com/centreon/engine/hostdependency.hh b/engine/inc/com/centreon/engine/hostdependency.hh index 6761636be62..ec72dca3651 100644 --- a/engine/inc/com/centreon/engine/hostdependency.hh +++ b/engine/inc/com/centreon/engine/hostdependency.hh @@ -1,22 +1,21 @@ -/* -** Copyright 2011-2019 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCE_OBJECTS_HOSTDEPENDENCY_HH #define CCE_OBJECTS_HOSTDEPENDENCY_HH @@ -28,7 +27,7 @@ namespace com::centreon::engine { class host; class hostdependency; class timeperiod; -} +} // namespace com::centreon::engine typedef std::unordered_multimap< std::string, @@ -38,8 +37,9 @@ typedef std::unordered_multimap< namespace com::centreon::engine { class hostdependency : public dependency { public: - hostdependency(std::string const& dependent_hostname, - std::string const& hostname, + hostdependency(size_t key, + const std::string& dependent_hostname, + const std::string& hostname, dependency::types dependency_type, bool inherits_parent, bool fail_on_up, @@ -76,7 +76,7 @@ class hostdependency : public dependency { bool _fail_on_unreachable; }; -} +} // namespace com::centreon::engine std::ostream& operator<<(std::ostream& os, com::centreon::engine::hostdependency const& obj); diff --git a/engine/inc/com/centreon/engine/hostescalation.hh b/engine/inc/com/centreon/engine/hostescalation.hh index 41d4e3d8ea0..efdb316c222 100644 --- a/engine/inc/com/centreon/engine/hostescalation.hh +++ b/engine/inc/com/centreon/engine/hostescalation.hh @@ -1,22 +1,20 @@ -/* -** Copyright 2011-2019 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCE_HOSTESCALATION_HH #define CCE_HOSTESCALATION_HH #include "com/centreon/engine/escalation.hh" @@ -25,7 +23,7 @@ namespace com::centreon::engine { class host; class hostescalation; -} +} // namespace com::centreon::engine typedef std::unordered_multimap< std::string, @@ -33,6 +31,10 @@ typedef std::unordered_multimap< hostescalation_mmap; namespace com::centreon::engine { +namespace configuration { +class hostescalation; +} + class hostescalation : public escalation { public: hostescalation(std::string const& host_name, @@ -41,19 +43,21 @@ class hostescalation : public escalation { double notification_interval, std::string const& escalation_period, uint32_t escalate_on, - Uuid const& uuid); - virtual ~hostescalation(); + const size_t key); + ~hostescalation() override = default; std::string const& get_hostname() const; bool is_viable(int state, uint32_t notification_number) const override; void resolve(int& w, int& e) override; + bool matches(const configuration::hostescalation& obj) const; + static hostescalation_mmap hostescalations; private: std::string _hostname; }; -} +} // namespace com::centreon::engine #endif // !CCE_HOSTESCALATION_HH diff --git a/engine/inc/com/centreon/engine/servicedependency.hh b/engine/inc/com/centreon/engine/servicedependency.hh index 4abfa45c632..94647358442 100644 --- a/engine/inc/com/centreon/engine/servicedependency.hh +++ b/engine/inc/com/centreon/engine/servicedependency.hh @@ -1,22 +1,22 @@ -/* -** Copyright 2011-2013 Merethis -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2013 Merethis + * Copyright 2014-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCE_OBJECTS_SERVICEDEPENDENCY_HH #define CCE_OBJECTS_SERVICEDEPENDENCY_HH #include "com/centreon/engine/configuration/servicedependency.hh" @@ -28,7 +28,7 @@ namespace com::centreon::engine { class service; class servicedependency; class timeperiod; -} +} // namespace com::centreon::engine typedef std::unordered_multimap< std::pair, @@ -38,8 +38,16 @@ typedef std::unordered_multimap< namespace com::centreon::engine { class servicedependency : public dependency { + std::string _dependent_service_description; + std::string _service_description; + bool _fail_on_ok; + bool _fail_on_warning; + bool _fail_on_unknown; + bool _fail_on_critical; + public: - servicedependency(std::string const& dependent_host_name, + servicedependency(size_t key, + std::string const& dependent_host_name, std::string const& dependent_service_description, std::string const& host_name, std::string const& service_description, @@ -79,17 +87,9 @@ class servicedependency : public dependency { static servicedependency_mmap servicedependencies; static servicedependency_mmap::iterator servicedependencies_find( configuration::servicedependency const& k); - - private: - std::string _dependent_service_description; - std::string _service_description; - bool _fail_on_ok; - bool _fail_on_warning; - bool _fail_on_unknown; - bool _fail_on_critical; }; -}; +}; // namespace com::centreon::engine std::ostream& operator<<(std::ostream& os, com::centreon::engine::servicedependency const& obj); diff --git a/engine/inc/com/centreon/engine/serviceescalation.hh b/engine/inc/com/centreon/engine/serviceescalation.hh index 8c951f50607..abe959912cd 100644 --- a/engine/inc/com/centreon/engine/serviceescalation.hh +++ b/engine/inc/com/centreon/engine/serviceescalation.hh @@ -1,22 +1,20 @@ -/* -** Copyright 2011-2019 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCE_SERVICEESCALATION_HH #define CCE_SERVICEESCALATION_HH @@ -35,6 +33,11 @@ typedef std::unordered_multimap< serviceescalation_mmap; namespace com::centreon::engine { + +namespace configuration { +class serviceescalation; +} + class serviceescalation : public escalation { public: serviceescalation(std::string const& hostname, @@ -44,12 +47,13 @@ class serviceescalation : public escalation { double notification_interval, std::string const& escalation_period, uint32_t escalate_on, - Uuid const& uuid); - virtual ~serviceescalation(); + const size_t key); + ~serviceescalation() override = default; std::string const& get_hostname() const; std::string const& get_description() const; bool is_viable(int state, uint32_t notification_number) const override; void resolve(int& w, int& e) override; + bool matches(const configuration::serviceescalation& obj) const; static serviceescalation_mmap serviceescalations; @@ -58,6 +62,6 @@ class serviceescalation : public escalation { std::string _description; }; -} +} // namespace com::centreon::engine #endif // !CCE_SERVICEESCALATION_HH diff --git a/engine/src/anomalydetection.cc b/engine/src/anomalydetection.cc index 822e06ea15a..2aca85a1275 100644 --- a/engine/src/anomalydetection.cc +++ b/engine/src/anomalydetection.cc @@ -1129,8 +1129,6 @@ bool anomalydetection::parse_perfdata(std::string const& perfdata, /* We should master this string, so no need to check if it is utf-8 */ calculated_result.set_output(oss.str()); - timestamp now(timestamp::now()); - // Update check result. timeval tv; gettimeofday(&tv, nullptr); diff --git a/engine/src/checkable.cc b/engine/src/checkable.cc index 332cb6368f9..37995381f93 100644 --- a/engine/src/checkable.cc +++ b/engine/src/checkable.cc @@ -1,22 +1,21 @@ /** * Copyright 2011-2019,2022-2024 Centreon * - * This file is part of Centreon Engine. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Centreon Engine is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License version 2 - * as published by the Free Software Foundation. + * http://www.apache.org/licenses/LICENSE-2.0 * - * Centreon Engine is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com * - * You should have received a copy of the GNU General Public License - * along with Centreon Engine. If not, see - * . */ - #include "com/centreon/engine/checkable.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" @@ -51,8 +50,7 @@ checkable::checkable(const std::string& name, bool obsess_over, const std::string& timezone, uint64_t icon_id) - : check_period_ptr{nullptr}, - _name{name}, + : _name{name}, _display_name{display_name.empty() ? name : display_name}, _check_command{check_command}, _check_interval{check_interval}, @@ -93,7 +91,8 @@ checkable::checkable(const std::string& name, _event_handler_ptr{nullptr}, _check_command_ptr{nullptr}, _is_executing{false}, - _icon_id{icon_id} { + _icon_id{icon_id}, + check_period_ptr{nullptr} { if (max_attempts <= 0 || retry_interval <= 0 || freshness_threshold < 0) { std::ostringstream oss; bool empty{true}; diff --git a/engine/src/configuration/applier/hostdependency.cc b/engine/src/configuration/applier/hostdependency.cc index f30f8f35b6c..accbce7e42f 100644 --- a/engine/src/configuration/applier/hostdependency.cc +++ b/engine/src/configuration/applier/hostdependency.cc @@ -26,16 +26,6 @@ using namespace com::centreon::engine::configuration; -/** - * Default constructor. - */ -applier::hostdependency::hostdependency() {} - -/** - * Destructor. - */ -applier::hostdependency::~hostdependency() throw() {} - /** * Add new hostdependency. * @@ -77,7 +67,8 @@ void applier::hostdependency::add_object( configuration::hostdependency::execution_dependency) // Create executon dependency. hd = std::make_shared( - *obj.dependent_hosts().begin(), *obj.hosts().begin(), + hostdependency_key(obj), *obj.dependent_hosts().begin(), + *obj.hosts().begin(), static_cast(obj.dependency_type()), obj.inherits_parent(), static_cast(obj.execution_failure_options() & @@ -92,7 +83,8 @@ void applier::hostdependency::add_object( else // Create notification dependency. hd = std::make_shared( - *obj.dependent_hosts().begin(), *obj.hosts().begin(), + hostdependency_key(obj), *obj.dependent_hosts().begin(), + *obj.hosts().begin(), static_cast(obj.dependency_type()), obj.inherits_parent(), static_cast(obj.notification_failure_options() & diff --git a/engine/src/configuration/applier/hostescalation.cc b/engine/src/configuration/applier/hostescalation.cc index f0db4b1b576..d9a2c89f596 100644 --- a/engine/src/configuration/applier/hostescalation.cc +++ b/engine/src/configuration/applier/hostescalation.cc @@ -26,16 +26,6 @@ using namespace com::centreon::engine::configuration; -/** - * Default constructor. - */ -applier::hostescalation::hostescalation() {} - -/** - * Destructor. - */ -applier::hostescalation::~hostescalation() throw() {} - /** * Add new host escalation. * @@ -58,6 +48,8 @@ void applier::hostescalation::add_object( // Add escalation to the global configuration set. config->hostescalations().insert(obj); + size_t key = hostescalation_key(obj); + // Create host escalation. auto he = std::make_shared( *obj.hosts().begin(), obj.first_notification(), obj.last_notification(), @@ -72,7 +64,7 @@ void applier::hostescalation::add_object( ((obj.escalation_options() & configuration::hostescalation::recovery) ? notifier::up : notifier::none), - obj.uuid()); + key); // Add new items to the configuration state. engine::hostescalation::hostescalations.insert({he->get_hostname(), he}); @@ -246,10 +238,11 @@ void applier::hostescalation::resolve_object( throw engine_error() << "Cannot find host escalations concerning host '" << hostname << "'"; + size_t key = hostescalation_key(obj); for (hostescalation_mmap::iterator it{p.first}; it != p.second; ++it) { /* It's a pity but for now we don't have any idea or key to verify if * the hostescalation is the good one. */ - if (it->second->get_uuid() == obj.uuid()) { + if (it->second->internal_key() == key && it->second->matches(obj)) { found = true; // Resolve host escalation. it->second->resolve(config_warnings, config_errors); diff --git a/engine/src/configuration/applier/servicedependency.cc b/engine/src/configuration/applier/servicedependency.cc index f4fd873c949..c256b3e8303 100644 --- a/engine/src/configuration/applier/servicedependency.cc +++ b/engine/src/configuration/applier/servicedependency.cc @@ -83,6 +83,7 @@ void applier::servicedependency::add_object( configuration::servicedependency::execution_dependency) // Create execution dependency. sd = std::make_shared( + configuration::servicedependency_key(obj), obj.dependent_hosts().front(), obj.dependent_service_description().front(), obj.hosts().front(), obj.service_description().front(), dependency::execution, @@ -101,6 +102,7 @@ void applier::servicedependency::add_object( else // Create notification dependency. sd = std::make_shared( + configuration::servicedependency_key(obj), obj.dependent_hosts().front(), obj.dependent_service_description().front(), obj.hosts().front(), obj.service_description().front(), dependency::notification, @@ -245,7 +247,6 @@ void applier::servicedependency::remove_object( engine::servicedependency::servicedependencies_find(obj.key())); if (it != engine::servicedependency::servicedependencies.end()) { // Notify event broker. - timeval tv(get_broker_timestamp(nullptr)); broker_adaptive_dependency_data(NEBTYPE_SERVICEDEPENDENCY_DELETE, it->second.get()); diff --git a/engine/src/configuration/applier/serviceescalation.cc b/engine/src/configuration/applier/serviceescalation.cc index 8676491c66a..053ffc5359b 100644 --- a/engine/src/configuration/applier/serviceescalation.cc +++ b/engine/src/configuration/applier/serviceescalation.cc @@ -20,6 +20,7 @@ #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/config.hh" #include "com/centreon/engine/configuration/applier/state.hh" +#include "com/centreon/engine/configuration/serviceescalation.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" @@ -50,6 +51,8 @@ void applier::serviceescalation::add_object( // Add escalation to the global configuration set. config->serviceescalations().insert(obj); + size_t key = configuration::serviceescalation_key(obj); + // Create service escalation. auto se = std::make_shared( obj.hosts().front(), obj.service_description().front(), @@ -70,7 +73,7 @@ void applier::serviceescalation::add_object( configuration::serviceescalation::recovery) ? notifier::ok : notifier::none), - obj.uuid()); + key); // Add new items to the global list. engine::serviceescalation::serviceescalations.insert( @@ -187,9 +190,10 @@ void applier::serviceescalation::remove_object( } else service_exists = true; + size_t key = serviceescalation_key(obj); for (serviceescalation_mmap::iterator it{range.first}, end{range.second}; it != end; ++it) { - if (it->second->get_uuid() == obj.uuid()) { + if (it->second->internal_key() == key) { // We have the serviceescalation to remove. // Notify event broker. @@ -250,8 +254,9 @@ void applier::serviceescalation::resolve_object( throw engine_error() << "Cannot find service escalations " << "concerning host '" << hostname << "' and service '" << desc << "'"; - for (serviceescalation_mmap::iterator it{p.first}; it != p.second; ++it) { - if (it->second->get_uuid() == obj.uuid()) { + size_t key = serviceescalation_key(obj); + for (serviceescalation_mmap::iterator it = p.first; it != p.second; ++it) { + if (it->second->internal_key() == key && it->second->matches(obj)) { found = true; // Resolve service escalation. it->second->resolve(config_warnings, config_errors); diff --git a/engine/src/configuration/applier/state.cc b/engine/src/configuration/applier/state.cc index 0221be3879e..6c338127ab3 100644 --- a/engine/src/configuration/applier/state.cc +++ b/engine/src/configuration/applier/state.cc @@ -939,12 +939,12 @@ void applier::state::_check_contactgroups() const { found->second.get() != pp.second) { engine_logger(log_config_error, basic) << "Error on contactgroup !!! The contactgroup " << pp.first - << " used in serviceescalation " << p.second->get_uuid().to_string() + << " used in serviceescalation " << p.second->internal_key() << " is not or badly defined"; config_logger->error( "Error on contactgroup !!! The contactgroup {} used in " "serviceescalation {} is not or badly defined", - pp.first, p.second->get_uuid().to_string()); + pp.first, p.second->internal_key()); throw engine_error() << "This is a bug"; } } @@ -958,12 +958,12 @@ void applier::state::_check_contactgroups() const { found->second.get() != pp.second) { engine_logger(log_config_error, basic) << "Error on contactgroup !!! The contactgroup " << pp.first - << " used in hostescalation " << p.second->get_uuid().to_string() + << " used in hostescalation " << p.second->internal_key() << " is not or badly defined"; config_logger->error( "Error on contactgroup !!! The contactgroup {} used in " "hostescalation {} is not or badly defined", - pp.first, p.second->get_uuid().to_string()); + pp.first, p.second->internal_key()); throw engine_error() << "This is a bug"; } } diff --git a/engine/src/configuration/applier/timeperiod.cc b/engine/src/configuration/applier/timeperiod.cc index 74338ac5c39..cd1b6aa03b4 100644 --- a/engine/src/configuration/applier/timeperiod.cc +++ b/engine/src/configuration/applier/timeperiod.cc @@ -28,36 +28,6 @@ using namespace com::centreon::engine::configuration; -/** - * Default constructor. - */ -applier::timeperiod::timeperiod() {} - -/** - * Copy constructor. - * - * @param[in] right Object to copy. - */ -applier::timeperiod::timeperiod(applier::timeperiod const& right) { - (void)right; -} - -/** - * Destructor. - */ -applier::timeperiod::~timeperiod() throw() {} - -/** - * Assignment operator. - * - * @param[in] right Object to copy. - */ -applier::timeperiod& applier::timeperiod::operator=( - applier::timeperiod const& right) { - (void)right; - return (*this); -} - /** * Add new time period. * diff --git a/engine/src/configuration/hostdependency.cc b/engine/src/configuration/hostdependency.cc index e4fe29ad219..251953ee007 100644 --- a/engine/src/configuration/hostdependency.cc +++ b/engine/src/configuration/hostdependency.cc @@ -33,6 +33,16 @@ using namespace com::centreon::engine::logging; #define SETTER(type, method) \ &object::setter::generic +namespace com::centreon::engine::configuration { +size_t hostdependency_key(const hostdependency& hd) { + assert(hd.hosts().size() == 1 && hd.hostgroups().empty() && + hd.dependent_hosts().size() == 1 && hd.dependent_hostgroups().empty()); + return absl::HashOf(hd.dependency_period(), hd.dependency_type(), + *hd.dependent_hosts().begin(), *hd.hosts().begin(), + hd.inherits_parent(), hd.notification_failure_options()); +} +} // namespace com::centreon::engine::configuration + std::unordered_map const hostdependency::_setters{ {"hostgroup", SETTER(std::string const&, _set_hostgroups)}, @@ -87,11 +97,6 @@ hostdependency::hostdependency(hostdependency const& right) : object(right) { operator=(right); } -/** - * Destructor. - */ -hostdependency::~hostdependency() noexcept {} - /** * Copy constructor. * diff --git a/engine/src/configuration/hostescalation.cc b/engine/src/configuration/hostescalation.cc index 09a4ccc9449..0110f5e892d 100644 --- a/engine/src/configuration/hostescalation.cc +++ b/engine/src/configuration/hostescalation.cc @@ -26,6 +26,17 @@ using namespace com::centreon::engine::configuration; #define SETTER(type, method) \ &object::setter::generic +namespace com::centreon::engine::configuration { + +size_t hostescalation_key(const hostescalation& he) { + return absl::HashOf(*he.hosts().begin(), he.contactgroups(), + he.escalation_options(), he.escalation_period(), + he.first_notification(), he.last_notification(), + he.notification_interval()); +} + +} // namespace com::centreon::engine::configuration + std::unordered_map const hostescalation::_setters{ {"hostgroup", SETTER(std::string const&, _set_hostgroups)}, @@ -88,7 +99,6 @@ hostescalation& hostescalation::operator=(hostescalation const& right) { _hosts = right._hosts; _last_notification = right._last_notification; _notification_interval = right._notification_interval; - _uuid = right._uuid; } return *this; } @@ -238,7 +248,6 @@ bool hostescalation::contactgroups_defined() const throw() { */ void hostescalation::escalation_options(unsigned short options) throw() { _escalation_options = options; - return; } /** @@ -257,7 +266,6 @@ unsigned short hostescalation::escalation_options() const throw() { */ void hostescalation::escalation_period(std::string const& period) { _escalation_period = period; - return; } /** @@ -285,7 +293,6 @@ bool hostescalation::escalation_period_defined() const throw() { */ void hostescalation::first_notification(unsigned int n) throw() { _first_notification = n; - return; } /** @@ -340,7 +347,6 @@ set_string const& hostescalation::hosts() const throw() { */ void hostescalation::last_notification(unsigned int n) throw() { _last_notification = n; - return; } /** @@ -359,7 +365,6 @@ unsigned int hostescalation::last_notification() const throw() { */ void hostescalation::notification_interval(unsigned int interval) { _notification_interval = interval; - return; } /** @@ -492,12 +497,3 @@ bool hostescalation::_set_notification_interval(unsigned int value) { _notification_interval = value; return true; } - -/** - * Get uuid value. - * - * @return uuid. - */ -Uuid const& hostescalation::uuid(void) const { - return _uuid; -} diff --git a/engine/src/configuration/object.cc b/engine/src/configuration/object.cc index 87c593a79c0..5cdbd69694e 100644 --- a/engine/src/configuration/object.cc +++ b/engine/src/configuration/object.cc @@ -69,11 +69,6 @@ object::object(object const& right) { operator=(right); } -/** - * Destructor. - */ -object::~object() noexcept {} - /** * Copy constructor. * diff --git a/engine/src/configuration/servicedependency.cc b/engine/src/configuration/servicedependency.cc index ebc0e7667ef..411cb62c914 100644 --- a/engine/src/configuration/servicedependency.cc +++ b/engine/src/configuration/servicedependency.cc @@ -30,6 +30,20 @@ using namespace com::centreon; using namespace com::centreon::engine::configuration; using namespace com::centreon::engine::logging; +namespace com::centreon::engine::configuration { +size_t servicedependency_key(const servicedependency& sd) { + assert(sd.hosts().size() == 1 && sd.service_description().size() == 1 && + sd.dependent_hosts().size() == 1 && + sd.dependent_service_description().size() == 1); + return absl::HashOf(sd.dependency_period(), sd.dependency_type(), + *sd.hosts().begin(), *sd.service_description().begin(), + *sd.dependent_hosts().begin(), + *sd.dependent_service_description().begin(), + sd.execution_failure_options(), sd.inherits_parent(), + sd.notification_failure_options()); +} +} // namespace com::centreon::engine::configuration + #define SETTER(type, method) \ &object::setter::generic @@ -110,11 +124,6 @@ servicedependency::servicedependency(servicedependency const& right) operator=(right); } -/** - * Destructor. - */ -servicedependency::~servicedependency() throw() {} - /** * Copy constructor. * diff --git a/engine/src/configuration/serviceescalation.cc b/engine/src/configuration/serviceescalation.cc index a4b9348ccf5..397fb3abcd8 100644 --- a/engine/src/configuration/serviceescalation.cc +++ b/engine/src/configuration/serviceescalation.cc @@ -29,6 +29,15 @@ using namespace com::centreon::engine::logging; #define SETTER(type, method) \ &object::setter::generic +namespace com::centreon::engine::configuration { +size_t serviceescalation_key(const serviceescalation& se) { + return absl::HashOf(*se.hosts().begin(), *se.service_description().begin(), + se.contactgroups(), se.escalation_options(), + se.escalation_period(), se.first_notification(), + se.last_notification(), se.notification_interval()); +} +} // namespace com::centreon::engine::configuration + std::unordered_map const serviceescalation::_setters{ {"host", SETTER(std::string const&, _set_hosts)}, @@ -99,7 +108,6 @@ serviceescalation& serviceescalation::operator=( _notification_interval = right._notification_interval; _servicegroups = right._servicegroups; _service_description = right._service_description; - _uuid = right._uuid; } return *this; } @@ -192,8 +200,8 @@ bool serviceescalation::operator==(serviceescalation const& right) const * * @return True if is not the same serviceescalation, otherwise false. */ -bool serviceescalation::operator!=(serviceescalation const& right) const - throw() { +bool serviceescalation::operator!=( + serviceescalation const& right) const noexcept { return !operator==(right); } @@ -251,7 +259,7 @@ void serviceescalation::check_validity() const { * * @return This object. */ -serviceescalation::key_type const& serviceescalation::key() const throw() { +serviceescalation::key_type const& serviceescalation::key() const noexcept { return *this; } @@ -640,12 +648,3 @@ bool serviceescalation::_set_service_description(std::string const& value) { _service_description = value; return true; } - -/** - * Get uuid value. - * - * @return uuid. - */ -Uuid const& serviceescalation::uuid(void) const { - return _uuid; -} diff --git a/engine/src/dependency.cc b/engine/src/dependency.cc index 09f48ae5501..b3f2d3a03c3 100644 --- a/engine/src/dependency.cc +++ b/engine/src/dependency.cc @@ -1,22 +1,21 @@ /** * Copyright 2011-2024 Centreon * - * This file is part of Centreon Engine. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Centreon Engine is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License version 2 - * as published by the Free Software Foundation. + * http://www.apache.org/licenses/LICENSE-2.0 * - * Centreon Engine is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com * - * You should have received a copy of the GNU General Public License - * along with Centreon Engine. If not, see - * . */ - #include "com/centreon/engine/dependency.hh" #include "com/centreon/engine/exceptions/error.hh" @@ -26,13 +25,15 @@ using namespace com::centreon::engine; using namespace com::centreon::engine::logging; -dependency::dependency(std::string const& dependent_hostname, - std::string const& hostname, +dependency::dependency(size_t key, + const std::string& dependent_hostname, + const std::string& hostname, types dependency_type, bool inherits_parent, bool fail_on_pending, - std::string const& dependency_period) - : _dependency_type{dependency_type}, + const std::string& dependency_period) + : _internal_key{key}, + _dependency_type{dependency_type}, _dependent_hostname{dependent_hostname}, _hostname{hostname}, _dependency_period{dependency_period}, @@ -170,3 +171,7 @@ bool dependency::operator<(dependency const& obj) noexcept { return _circular_path_checked < obj.get_circular_path_checked(); return _contains_circular_path < obj.get_contains_circular_path(); } + +size_t dependency::internal_key() const { + return _internal_key; +} diff --git a/engine/src/escalation.cc b/engine/src/escalation.cc index 69db6bfc3df..eeedd11aefb 100644 --- a/engine/src/escalation.cc +++ b/engine/src/escalation.cc @@ -1,22 +1,20 @@ /** * Copyright 2011-2024 Centreon * - * This file is part of Centreon Engine. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Centreon Engine is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License version 2 - * as published by the Free Software Foundation. + * http://www.apache.org/licenses/LICENSE-2.0 * - * Centreon Engine is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. * - * You should have received a copy of the GNU General Public License - * along with Centreon Engine. If not, see - * . + * For more information : contact@centreon.com */ - #include "com/centreon/engine/escalation.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" @@ -31,16 +29,16 @@ escalation::escalation(uint32_t first_notification, double notification_interval, std::string const& escalation_period, uint32_t escalate_on, - Uuid const& uuid) - : notifier_ptr{nullptr}, - escalation_period_ptr{nullptr}, - _first_notification{first_notification}, + const size_t key) + : _first_notification{first_notification}, _last_notification{last_notification}, _notification_interval{ (notification_interval < 0) ? 0 : notification_interval}, _escalation_period{escalation_period}, _escalate_on{escalate_on}, - _uuid{uuid} {} + _internal_key{key}, + notifier_ptr{nullptr}, + escalation_period_ptr{nullptr} {} std::string const& escalation::get_escalation_period() const { return _escalation_period; @@ -167,6 +165,6 @@ void escalation::resolve(int& w __attribute__((unused)), int& e) { } } -Uuid const& escalation::get_uuid() const { - return _uuid; +size_t escalation::internal_key() const { + return _internal_key; } diff --git a/engine/src/hostdependency.cc b/engine/src/hostdependency.cc index 15390f5e731..d96c8cb99ab 100644 --- a/engine/src/hostdependency.cc +++ b/engine/src/hostdependency.cc @@ -1,24 +1,24 @@ /** * Copyright 2011-2024 Centreon * - * This file is part of Centreon Engine. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Centreon Engine is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License version 2 - * as published by the Free Software Foundation. + * http://www.apache.org/licenses/LICENSE-2.0 * - * Centreon Engine is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com * - * You should have received a copy of the GNU General Public License - * along with Centreon Engine. If not, see - * . */ - #include "com/centreon/engine/hostdependency.hh" #include "com/centreon/engine/broker.hh" +#include "com/centreon/engine/configuration/applier/hostdependency.hh" #include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" @@ -28,15 +28,16 @@ using namespace com::centreon; using namespace com::centreon::engine; -using namespace com::centreon::engine::configuration::applier; using namespace com::centreon::engine::logging; using namespace com::centreon::engine::string; hostdependency_mmap hostdependency::hostdependencies; /** - * Create a host dependency definition. + * Create a host dependency definition. The key is given by the + * applier::configuration::hostdependency object from its attributes. * + * @param[in] key key representing this hostdependency. * @param[in] dependent_hostname Dependant host name. * @param[in] hostname Host name. * @param[in] dependency_type Dependency type. @@ -49,7 +50,8 @@ hostdependency_mmap hostdependency::hostdependencies; * * @return New host dependency. */ -hostdependency::hostdependency(std::string const& dependent_hostname, +hostdependency::hostdependency(size_t key, + std::string const& dependent_hostname, std::string const& hostname, dependency::types dependency_type, bool inherits_parent, @@ -58,7 +60,8 @@ hostdependency::hostdependency(std::string const& dependent_hostname, bool fail_on_unreachable, bool fail_on_pending, std::string const& dependency_period) - : dependency(dependent_hostname, + : dependency(key, + dependent_hostname, hostname, dependency_type, inherits_parent, @@ -230,7 +233,7 @@ void hostdependency::resolve(int& w, int& e) { int errors{0}; // Find the dependent host. - host_map::const_iterator it{host::hosts.find(_dependent_hostname)}; + host_map::const_iterator it = host::hosts.find(_dependent_hostname); if (it == host::hosts.end() || !it->second) { engine_logger(log_verification_error, basic) << "Error: Dependent host specified in host dependency for " @@ -309,45 +312,15 @@ void hostdependency::resolve(int& w, int& e) { */ hostdependency_mmap::iterator hostdependency::hostdependencies_find( const com::centreon::engine::configuration::hostdependency& k) { - typedef hostdependency_mmap collection; - std::pair p; + std::pair p; + + size_t key = configuration::hostdependency_key(k); p = hostdependencies.equal_range(*k.dependent_hosts().begin()); while (p.first != p.second) { - configuration::hostdependency current; - current.configuration::object::operator=(k); - current.dependent_hosts().insert(p.first->second->get_dependent_hostname()); - current.hosts().insert(p.first->second->get_hostname()); - current.dependency_period( - (!p.first->second->get_dependency_period().empty() - ? p.first->second->get_dependency_period().c_str() - : "")); - current.inherits_parent(p.first->second->get_inherits_parent()); - unsigned int options((p.first->second->get_fail_on_up() - ? configuration::hostdependency::up - : 0) | - (p.first->second->get_fail_on_down() - ? configuration::hostdependency::down - : 0) | - (p.first->second->get_fail_on_unreachable() - ? configuration::hostdependency::unreachable - : 0) | - (p.first->second->get_fail_on_pending() - ? configuration::hostdependency::pending - : 0)); - if (p.first->second->get_dependency_type() == - engine::hostdependency::notification) { - current.dependency_type( - configuration::hostdependency::notification_dependency); - current.notification_failure_options(options); - } else { - current.dependency_type( - configuration::hostdependency::execution_dependency); - current.execution_failure_options(options); - } - if (current == k) + if (p.first->second->internal_key() == key) break; ++p.first; } - return (p.first == p.second) ? hostdependencies.end() : p.first; + return p.first == p.second ? hostdependencies.end() : p.first; } diff --git a/engine/src/hostescalation.cc b/engine/src/hostescalation.cc index f74633f07b6..ae35f3f81b4 100644 --- a/engine/src/hostescalation.cc +++ b/engine/src/hostescalation.cc @@ -1,22 +1,20 @@ /** * Copyright 2011-2024 Centreon * - * This file is part of Centreon Engine. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Centreon Engine is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License version 2 - * as published by the Free Software Foundation. + * http://www.apache.org/licenses/LICENSE-2.0 * - * Centreon Engine is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. * - * You should have received a copy of the GNU General Public License - * along with Centreon Engine. If not, see - * . + * For more information : contact@centreon.com */ - #include "com/centreon/engine/hostescalation.hh" #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/configuration/applier/state.hh" @@ -52,17 +50,15 @@ hostescalation::hostescalation(std::string const& host_name, double notification_interval, std::string const& escalation_period, uint32_t escalate_on, - Uuid const& uuid) + const size_t key) : escalation{first_notification, last_notification, notification_interval, - escalation_period, escalate_on, uuid}, + escalation_period, escalate_on, key}, _hostname{host_name} { if (host_name.empty()) throw engine_error() << "Could not create escalation " << "on host '" << host_name << "'"; } -hostescalation::~hostescalation() {} - std::string const& hostescalation::get_hostname() const { return _hostname; } @@ -130,3 +126,25 @@ void hostescalation::resolve(int& w, int& e) { throw engine_error() << "Cannot resolve host escalation"; } } + +bool hostescalation::matches(const configuration::hostescalation& obj) const { + uint32_t escalate_on = + ((obj.escalation_options() & configuration::hostescalation::down) + ? notifier::down + : notifier::none) | + ((obj.escalation_options() & configuration::hostescalation::unreachable) + ? notifier::unreachable + : notifier::none) | + ((obj.escalation_options() & configuration::hostescalation::recovery) + ? notifier::up + : notifier::none); + if (_hostname != *obj.hosts().begin() || + get_first_notification() != obj.first_notification() || + get_last_notification() != obj.last_notification() || + get_notification_interval() != obj.notification_interval() || + get_escalation_period() != obj.escalation_period() || + get_escalate_on() != escalate_on) + return false; + + return true; +} diff --git a/engine/src/servicedependency.cc b/engine/src/servicedependency.cc index 2b6c62cc0d8..80a73c55dc7 100644 --- a/engine/src/servicedependency.cc +++ b/engine/src/servicedependency.cc @@ -1,24 +1,24 @@ /** - * Copyright 2011-2019 Centreon + * Copyright 2011-2024 Centreon * - * This file is part of Centreon Engine. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Centreon Engine is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License version 2 - * as published by the Free Software Foundation. + * http://www.apache.org/licenses/LICENSE-2.0 * - * Centreon Engine is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com * - * You should have received a copy of the GNU General Public License - * along with Centreon Engine. If not, see - * . */ - #include "com/centreon/engine/servicedependency.hh" #include "com/centreon/engine/broker.hh" +#include "com/centreon/engine/configuration/applier/servicedependency.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" #include "com/centreon/engine/logging/logger.hh" @@ -55,7 +55,8 @@ servicedependency_mmap servicedependency::servicedependencies; * @param[in] dependency_period Dependency timeperiod name. * */ -servicedependency::servicedependency(std::string const& dependent_hostname, +servicedependency::servicedependency(size_t key, + std::string const& dependent_hostname, std::string const& dependent_svc_desc, std::string const& hostname, std::string const& service_description, @@ -67,16 +68,21 @@ servicedependency::servicedependency(std::string const& dependent_hostname, bool fail_on_critical, bool fail_on_pending, std::string const& dependency_period) - : dependency{dependent_hostname, hostname, dependency_type, - inherits_parent, fail_on_pending, dependency_period}, - master_service_ptr{nullptr}, - dependent_service_ptr{nullptr}, + : dependency{key, + dependent_hostname, + hostname, + dependency_type, + inherits_parent, + fail_on_pending, + dependency_period}, _dependent_service_description{dependent_svc_desc}, _service_description{service_description}, _fail_on_ok{fail_on_ok}, _fail_on_warning{fail_on_warning}, _fail_on_unknown{fail_on_unknown}, - _fail_on_critical{fail_on_critical} {} + _fail_on_critical{fail_on_critical}, + master_service_ptr{nullptr}, + dependent_service_ptr{nullptr} {} std::string const& servicedependency::get_dependent_service_description() const { @@ -383,50 +389,15 @@ void servicedependency::resolve(int& w, int& e) { */ servicedependency_mmap::iterator servicedependency::servicedependencies_find( configuration::servicedependency const& k) { - typedef servicedependency_mmap collection; - std::pair p; - p = servicedependencies.equal_range(std::make_pair( - k.dependent_hosts().front(), k.dependent_service_description().front())); + size_t key = configuration::servicedependency_key(k); + std::pair + p = servicedependencies.equal_range( + std::make_pair(k.dependent_hosts().front(), + k.dependent_service_description().front())); while (p.first != p.second) { - configuration::servicedependency current; - current.configuration::object::operator=(k); - current.dependent_hosts().push_back( - p.first->second->get_dependent_hostname()); - current.dependent_service_description().push_back( - p.first->second->get_dependent_service_description()); - current.hosts().push_back(p.first->second->get_hostname()); - current.service_description().push_back( - p.first->second->get_service_description()); - current.dependency_period(p.first->second->get_dependency_period()); - current.inherits_parent(p.first->second->get_inherits_parent()); - unsigned int options((p.first->second->get_fail_on_ok() - ? configuration::servicedependency::ok - : 0) | - (p.first->second->get_fail_on_warning() - ? configuration::servicedependency::warning - : 0) | - (p.first->second->get_fail_on_unknown() - ? configuration::servicedependency::unknown - : 0) | - (p.first->second->get_fail_on_critical() - ? configuration::servicedependency::critical - : 0) | - (p.first->second->get_fail_on_pending() - ? configuration::servicedependency::pending - : 0)); - if (p.first->second->get_dependency_type() == - engine::dependency::notification) { - current.dependency_type( - configuration::servicedependency::notification_dependency); - current.notification_failure_options(options); - } else { - current.dependency_type( - configuration::servicedependency::execution_dependency); - current.execution_failure_options(options); - } - if (current == k) + if (p.first->second->internal_key() == key) break; ++p.first; } - return (p.first == p.second) ? servicedependencies.end() : p.first; + return p.first == p.second ? servicedependencies.end() : p.first; } diff --git a/engine/src/serviceescalation.cc b/engine/src/serviceescalation.cc index 5d98f226890..796177a022a 100644 --- a/engine/src/serviceescalation.cc +++ b/engine/src/serviceescalation.cc @@ -1,22 +1,20 @@ /** * Copyright 2011-2024 Centreon * - * This file is part of Centreon Engine. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Centreon Engine is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License version 2 - * as published by the Free Software Foundation. + * http://www.apache.org/licenses/LICENSE-2.0 * - * Centreon Engine is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. * - * You should have received a copy of the GNU General Public License - * along with Centreon Engine. If not, see - * . + * For more information : contact@centreon.com */ - #include "com/centreon/engine/serviceescalation.hh" #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/configuration/applier/state.hh" @@ -37,9 +35,9 @@ serviceescalation::serviceescalation(std::string const& hostname, double notification_interval, std::string const& escalation_period, uint32_t escalate_on, - Uuid const& uuid) + const size_t key) : escalation{first_notification, last_notification, notification_interval, - escalation_period, escalate_on, uuid}, + escalation_period, escalate_on, key}, _hostname{hostname}, _description{description} { if (hostname.empty()) @@ -50,8 +48,6 @@ serviceescalation::serviceescalation(std::string const& hostname, << "on a service without description"; } -serviceescalation::~serviceescalation() {} - std::string const& serviceescalation::get_hostname() const { return _hostname; } @@ -127,3 +123,30 @@ void serviceescalation::resolve(int& w, int& e) { throw engine_error() << "Cannot resolve service escalation"; } } + +bool serviceescalation::matches( + const configuration::serviceescalation& obj) const { + uint32_t escalate_on = + ((obj.escalation_options() & configuration::serviceescalation::warning) + ? notifier::warning + : notifier::none) | + ((obj.escalation_options() & configuration::serviceescalation::unknown) + ? notifier::unknown + : notifier::none) | + ((obj.escalation_options() & configuration::serviceescalation::critical) + ? notifier::critical + : notifier::none) | + ((obj.escalation_options() & configuration::serviceescalation::recovery) + ? notifier::ok + : notifier::none); + if (_hostname != obj.hosts().front() || + _description != obj.service_description().front() || + get_first_notification() != obj.first_notification() || + get_last_notification() != obj.last_notification() || + get_notification_interval() != obj.notification_interval() || + get_escalation_period() != obj.escalation_period() || + get_escalate_on() != escalate_on) + return false; + + return true; +} diff --git a/engine/tests/configuration/applier/applier-hostescalation.cc b/engine/tests/configuration/applier/applier-hostescalation.cc index f7b5fb82059..42a647a5be1 100644 --- a/engine/tests/configuration/applier/applier-hostescalation.cc +++ b/engine/tests/configuration/applier/applier-hostescalation.cc @@ -55,6 +55,24 @@ TEST_F(ApplierHostEscalation, AddEscalation) { ASSERT_EQ(hostescalation::hostescalations.size(), 2u); } +TEST_F(ApplierHostEscalation, ResolveObject) { + configuration::applier::host hst_aply; + configuration::host hst; + ASSERT_TRUE(hst.parse("host_name", "test_host")); + ASSERT_TRUE(hst.parse("address", "127.0.0.1")); + ASSERT_TRUE(hst.parse("_HOST_ID", "12")); + hst_aply.add_object(hst); + ASSERT_EQ(host::hosts.size(), 1u); + + configuration::applier::hostescalation he_apply; + configuration::hostescalation he; + ASSERT_TRUE(he.parse("host_name", "test_host")); + ASSERT_TRUE(he.parse("first_notification", "4")); + ASSERT_THROW(he_apply.resolve_object(he), std::exception); + he_apply.add_object(he); + ASSERT_NO_THROW(he_apply.resolve_object(he)); +} + TEST_F(ApplierHostEscalation, RemoveEscalation) { configuration::applier::host hst_aply; configuration::host hst; diff --git a/engine/tests/configuration/applier/applier-serviceescalation.cc b/engine/tests/configuration/applier/applier-serviceescalation.cc index 31ea88b4429..754e30da81a 100644 --- a/engine/tests/configuration/applier/applier-serviceescalation.cc +++ b/engine/tests/configuration/applier/applier-serviceescalation.cc @@ -74,6 +74,41 @@ TEST_F(ApplierServiceEscalation, AddEscalation) { ASSERT_EQ(serviceescalation::serviceescalations.size(), 2u); } +TEST_F(ApplierServiceEscalation, ResolveObject) { + configuration::applier::host hst_aply; + configuration::host hst; + ASSERT_TRUE(hst.parse("host_name", "test_host")); + ASSERT_TRUE(hst.parse("address", "127.0.0.1")); + ASSERT_TRUE(hst.parse("_HOST_ID", "12")); + hst_aply.add_object(hst); + ASSERT_EQ(host::hosts.size(), 1u); + + configuration::applier::command cmd_aply; + configuration::command cmd; + cmd.parse("command_name", "cmd"); + cmd.parse("command_line", "echo 1"); + cmd_aply.add_object(cmd); + + configuration::applier::service svc_aply; + configuration::service svc; + ASSERT_TRUE(svc.parse("host", "test_host")); + ASSERT_TRUE(svc.parse("service_description", "test_svc")); + ASSERT_TRUE(svc.parse("service_id", "12")); + ASSERT_TRUE(svc.parse("check_command", "cmd")); + svc.set_host_id(12); + svc_aply.add_object(svc); + ASSERT_EQ(service::services.size(), 1u); + + configuration::applier::serviceescalation se_apply; + configuration::serviceescalation se; + ASSERT_TRUE(se.parse("host", "test_host")); + ASSERT_TRUE(se.parse("service_description", "test_svc")); + ASSERT_TRUE(se.parse("first_notification", "4")); + ASSERT_THROW(se_apply.resolve_object(se), std::exception); + se_apply.add_object(se); + ASSERT_NO_THROW(se_apply.resolve_object(se)); +} + TEST_F(ApplierServiceEscalation, RemoveEscalation) { configuration::applier::host hst_aply; configuration::host hst; diff --git a/engine/tests/notifications/host_downtime_notification.cc b/engine/tests/notifications/host_downtime_notification.cc index 3e12091bc88..61f2003faa5 100644 --- a/engine/tests/notifications/host_downtime_notification.cc +++ b/engine/tests/notifications/host_downtime_notification.cc @@ -89,7 +89,7 @@ TEST_F(HostDowntimeNotification, SimpleHostDowntime) { tperiod->days[i].emplace_back(0, 86400); std::unique_ptr host_escalation{ - new engine::hostescalation("host_name", 0, 1, 1.0, "tperiod", 7, Uuid())}; + new engine::hostescalation("host_name", 0, 1, 1.0, "tperiod", 7, 12345)}; ASSERT_TRUE(host_escalation); uint64_t id{_host->get_next_notification_id()}; @@ -138,7 +138,7 @@ TEST_F(HostDowntimeNotification, tperiod->days[i].emplace_back(0, 86400); std::unique_ptr host_escalation{ - new engine::hostescalation("host_name", 0, 1, 1.0, "tperiod", 7, Uuid())}; + new engine::hostescalation("host_name", 0, 1, 1.0, "tperiod", 7, 12345)}; ASSERT_TRUE(host_escalation); uint64_t id{_host->get_next_notification_id()}; diff --git a/engine/tests/notifications/host_flapping_notification.cc b/engine/tests/notifications/host_flapping_notification.cc index 5f51a7a46ff..0f9b7e6c3e3 100644 --- a/engine/tests/notifications/host_flapping_notification.cc +++ b/engine/tests/notifications/host_flapping_notification.cc @@ -109,8 +109,9 @@ TEST_F(HostFlappingNotification, SimpleHostFlapping) { for (size_t i = 0; i < tperiod->days.size(); ++i) tperiod->days[i].emplace_back(0, 86400); - std::unique_ptr host_escalation{ - new engine::hostescalation("host_name", 0, 1, 1.0, "tperiod", 7, Uuid())}; + std::unique_ptr host_escalation = + std::make_unique("host_name", 0, 1, 1.0, + "tperiod", 7, 12345); ASSERT_TRUE(host_escalation); uint64_t id{_host->get_next_notification_id()}; @@ -160,7 +161,7 @@ TEST_F(HostFlappingNotification, SimpleHostFlappingStartTwoTimes) { tperiod->days[i].emplace_back(0, 86400); std::unique_ptr host_escalation{ - new engine::hostescalation("host_name", 0, 1, 1.0, "tperiod", 7, Uuid())}; + new engine::hostescalation("host_name", 0, 1, 1.0, "tperiod", 7, 12345)}; ASSERT_TRUE(host_escalation); uint64_t id{_host->get_next_notification_id()}; @@ -199,7 +200,7 @@ TEST_F(HostFlappingNotification, SimpleHostFlappingStopTwoTimes) { tperiod->days[i].emplace_back(0, 86400); std::unique_ptr host_escalation{ - new engine::hostescalation("host_name", 0, 1, 1.0, "tperiod", 7, Uuid())}; + new engine::hostescalation("host_name", 0, 1, 1.0, "tperiod", 7, 12345)}; ASSERT_TRUE(host_escalation); uint64_t id{_host->get_next_notification_id()}; diff --git a/engine/tests/notifications/host_normal_notification.cc b/engine/tests/notifications/host_normal_notification.cc index 2d75c1ffbc7..c53cbd34795 100644 --- a/engine/tests/notifications/host_normal_notification.cc +++ b/engine/tests/notifications/host_normal_notification.cc @@ -95,7 +95,7 @@ TEST_F(HostNotification, SimpleNormalHostNotification) { tperiod->days[i].emplace_back(0, 86400); std::unique_ptr host_escalation{ - new engine::hostescalation("host_name", 0, 1, 1.0, "tperiod", 7, Uuid())}; + new engine::hostescalation("host_name", 0, 1, 1.0, "tperiod", 7, 12345)}; ASSERT_TRUE(host_escalation); uint64_t id{_host->get_next_notification_id()}; @@ -122,7 +122,7 @@ TEST_F(HostNotification, SimpleNormalHostNotificationNotificationsdisabled) { tperiod->days[i].emplace_back(0, 86400); std::unique_ptr host_escalation{ - new engine::hostescalation("host_name", 0, 1, 1.0, "tperiod", 7, Uuid())}; + new engine::hostescalation("host_name", 0, 1, 1.0, "tperiod", 7, 12345)}; ASSERT_TRUE(host_escalation); uint64_t id{_host->get_next_notification_id()}; @@ -144,7 +144,7 @@ TEST_F(HostNotification, SimpleNormalHostNotificationNotifierNotifdisabled) { tperiod->days[i].emplace_back(0, 86400); std::unique_ptr host_escalation{ - new engine::hostescalation("host_name", 0, 1, 1.0, "tperiod", 7, Uuid())}; + new engine::hostescalation("host_name", 0, 1, 1.0, "tperiod", 7, 12345)}; ASSERT_TRUE(host_escalation); uint64_t id{_host->get_next_notification_id()}; @@ -166,7 +166,7 @@ TEST_F(HostNotification, SimpleNormalHostNotificationOutsideTimeperiod) { tperiod->days[i].emplace_back(43200, 86400); std::unique_ptr host_escalation{ - new engine::hostescalation("host_name", 0, 1, 1.0, "", 7, Uuid())}; + new engine::hostescalation("host_name", 0, 1, 1.0, "", 7, 12345)}; _host->set_notification_period_ptr(tperiod.get()); ASSERT_TRUE(host_escalation); @@ -188,7 +188,7 @@ TEST_F(HostNotification, tperiod->days[i].emplace_back(43200, 86400); std::unique_ptr host_escalation{ - new engine::hostescalation("host_name", 0, 1, 1.0, "", 7, Uuid())}; + new engine::hostescalation("host_name", 0, 1, 1.0, "", 7, 12345)}; _host->set_notification_period_ptr(tperiod.get()); ASSERT_TRUE(host_escalation); @@ -208,7 +208,7 @@ TEST_F(HostNotification, SimpleNormalHostNotificationForcedNotification) { tperiod->days[i].emplace_back(43200, 86400); std::unique_ptr host_escalation{ - new engine::hostescalation("host_name", 0, 1, 1.0, "", 7, Uuid())}; + new engine::hostescalation("host_name", 0, 1, 1.0, "", 7, 12345)}; _host->set_notification_period_ptr(tperiod.get()); ASSERT_TRUE(host_escalation); @@ -229,7 +229,7 @@ TEST_F(HostNotification, SimpleNormalHostNotificationWithDowntime) { tperiod->days[i].emplace_back(0, 86400); std::unique_ptr host_escalation{ - new engine::hostescalation("host_name", 0, 1, 1.0, "", 7, Uuid())}; + new engine::hostescalation("host_name", 0, 1, 1.0, "", 7, 12345)}; _host->set_notification_period_ptr(tperiod.get()); ASSERT_TRUE(host_escalation); @@ -250,7 +250,7 @@ TEST_F(HostNotification, SimpleNormalHostNotificationWithFlapping) { tperiod->days[i].emplace_back(0, 86400); std::unique_ptr host_escalation{ - new engine::hostescalation("host_name", 0, 1, 1.0, "", 7, Uuid())}; + new engine::hostescalation("host_name", 0, 1, 1.0, "", 7, 12345)}; _host->set_notification_period_ptr(tperiod.get()); ASSERT_TRUE(host_escalation); @@ -271,7 +271,7 @@ TEST_F(HostNotification, SimpleNormalHostNotificationWithSoftState) { tperiod->days[i].emplace_back(0, 86400); std::unique_ptr host_escalation{ - new engine::hostescalation("host_name", 0, 1, 1.0, "", 7, Uuid())}; + new engine::hostescalation("host_name", 0, 1, 1.0, "", 7, 12345)}; _host->set_notification_period_ptr(tperiod.get()); ASSERT_TRUE(host_escalation); @@ -292,7 +292,7 @@ TEST_F(HostNotification, tperiod->days[i].emplace_back(0, 86400); std::unique_ptr host_escalation{ - new engine::hostescalation("host_name", 0, 1, 1.0, "", 7, Uuid())}; + new engine::hostescalation("host_name", 0, 1, 1.0, "", 7, 12345)}; _host->set_notification_period_ptr(tperiod.get()); _host->set_acknowledgement(AckType::NORMAL); @@ -313,7 +313,7 @@ TEST_F(HostNotification, SimpleNormalHostNotificationAfterPreviousTooSoon) { tperiod->days[i].emplace_back(0, 86400); std::unique_ptr host_escalation{ - new engine::hostescalation("host_name", 0, 1, 1.0, "", 7, Uuid())}; + new engine::hostescalation("host_name", 0, 1, 1.0, "", 7, 12345)}; _host->set_notification_period_ptr(tperiod.get()); _host->set_acknowledgement(AckType::NORMAL); @@ -336,7 +336,7 @@ TEST_F(HostNotification, tperiod->days[i].emplace_back(0, 86400); std::unique_ptr host_escalation{ - new engine::hostescalation("host_name", 0, 1, 1.0, "", 7, Uuid())}; + new engine::hostescalation("host_name", 0, 1, 1.0, "", 7, 12345)}; _host->set_notification_period_ptr(tperiod.get()); _host->set_acknowledgement(AckType::NORMAL); @@ -360,7 +360,7 @@ TEST_F(HostNotification, SimpleNormalHostNotificationOnStateNotNotified) { tperiod->days[i].emplace_back(0, 86400); std::unique_ptr host_escalation{ - new engine::hostescalation("host_name", 0, 1, 1.0, "", 7, Uuid())}; + new engine::hostescalation("host_name", 0, 1, 1.0, "", 7, 12345)}; _host->set_notification_period_ptr(tperiod.get()); _host->set_acknowledgement(AckType::NONE); @@ -384,7 +384,7 @@ TEST_F(HostNotification, tperiod->days[i].emplace_back(0, 86400); std::unique_ptr host_escalation{ - new engine::hostescalation("host_name", 0, 1, 1.0, "", 7, Uuid())}; + new engine::hostescalation("host_name", 0, 1, 1.0, "", 7, 12345)}; _host->set_notification_period_ptr(tperiod.get()); _host->set_acknowledgement(AckType::NONE); @@ -410,7 +410,7 @@ TEST_F(HostNotification, tperiod->days[i].emplace_back(0, 86400); std::unique_ptr host_escalation{ - new engine::hostescalation("host_name", 0, 1, 1.0, "", 7, Uuid())}; + new engine::hostescalation("host_name", 0, 1, 1.0, "", 7, 12345)}; _host->set_notification_period_ptr(tperiod.get()); _host->set_acknowledgement(AckType::NONE); @@ -435,7 +435,7 @@ TEST_F(HostNotification, SimpleNormalHostNotificationNotifierDelayTooShort) { tperiod->days[i].emplace_back(0, 86400); std::unique_ptr host_escalation{ - new engine::hostescalation("host_name", 0, 1, 1.0, "tperiod", 7, Uuid())}; + new engine::hostescalation("host_name", 0, 1, 1.0, "tperiod", 7, 12345)}; ASSERT_TRUE(host_escalation); uint64_t id{_host->get_next_notification_id()}; diff --git a/engine/tests/notifications/host_recovery_notification.cc b/engine/tests/notifications/host_recovery_notification.cc index 11ad9dbc673..5bffa4bf1ad 100644 --- a/engine/tests/notifications/host_recovery_notification.cc +++ b/engine/tests/notifications/host_recovery_notification.cc @@ -60,9 +60,10 @@ class HostRecovery : public ::testing::Test { for (size_t i = 0; i < _tperiod->days.size(); ++i) _tperiod->days[i].emplace_back(0, 86400); + /* 12345 is here to simulate a key. It won't allow any look up */ std::unique_ptr host_escalation{ new engine::hostescalation("host_name", 0, 1, 1.0, "tperiod", 7, - Uuid())}; + 12345)}; _host->get_next_notification_id(); _host->set_notification_period_ptr(_tperiod.get()); diff --git a/engine/tests/notifications/service_flapping_notification.cc b/engine/tests/notifications/service_flapping_notification.cc index 673259bd970..140d4690273 100644 --- a/engine/tests/notifications/service_flapping_notification.cc +++ b/engine/tests/notifications/service_flapping_notification.cc @@ -130,7 +130,7 @@ TEST_F(ServiceFlappingNotification, SimpleServiceFlapping) { std::unique_ptr service_escalation{ new engine::serviceescalation("host_name", "test_description", 0, 1, 1.0, - "tperiod", 7, Uuid())}; + "tperiod", 7, 12345)}; ASSERT_TRUE(service_escalation); uint64_t id{_service->get_next_notification_id()}; @@ -183,7 +183,7 @@ TEST_F(ServiceFlappingNotification, SimpleServiceFlappingStartTwoTimes) { std::unique_ptr service_escalation{ new engine::serviceescalation("host_name", "test_description", 0, 1, 1.0, - "tperiod", 7, Uuid())}; + "tperiod", 7, 12345)}; ASSERT_TRUE(service_escalation); uint64_t id{_service->get_next_notification_id()}; @@ -223,7 +223,7 @@ TEST_F(ServiceFlappingNotification, SimpleServiceFlappingStopTwoTimes) { std::unique_ptr service_escalation{ new engine::serviceescalation("host_name", "test_description", 0, 1, 1.0, - "tperiod", 7, Uuid())}; + "tperiod", 7, 12345)}; ASSERT_TRUE(service_escalation); uint64_t id{_service->get_next_notification_id()}; diff --git a/engine/tests/notifications/service_normal_notification.cc b/engine/tests/notifications/service_normal_notification.cc index 3e1b0749c25..2f1111e2f5e 100644 --- a/engine/tests/notifications/service_normal_notification.cc +++ b/engine/tests/notifications/service_normal_notification.cc @@ -112,7 +112,7 @@ TEST_F(ServiceNotification, SimpleNormalServiceNotification) { std::unique_ptr service_escalation{ new engine::serviceescalation("test_host", "test_svc", 0, 1, 1.0, - "tperiod", 7, Uuid())}; + "tperiod", 7, 12345)}; _svc->set_current_state(engine::service::state_critical); _svc->set_last_state(engine::service::state_critical); _svc->set_last_hard_state_change(43200); @@ -141,7 +141,7 @@ TEST_F(ServiceNotification, std::unique_ptr service_escalation{ new engine::serviceescalation("test_host", "test_svc", 0, 1, 1.0, - "tperiod", 7, Uuid())}; + "tperiod", 7, 12345)}; ASSERT_TRUE(service_escalation); uint64_t id{_svc->get_next_notification_id()}; @@ -165,7 +165,7 @@ TEST_F(ServiceNotification, std::unique_ptr service_escalation{ new engine::serviceescalation("test_host", "test_svc", 0, 1, 1.0, - "tperiod", 7, Uuid())}; + "tperiod", 7, 12345)}; ASSERT_TRUE(service_escalation); uint64_t id{_svc->get_next_notification_id()}; @@ -188,7 +188,7 @@ TEST_F(ServiceNotification, SimpleNormalServiceNotificationOutsideTimeperiod) { std::unique_ptr service_escalation{ new engine::serviceescalation("test_host", "test_svc", 0, 1, 1.0, "", 7, - Uuid())}; + 12345)}; _svc->set_notification_period_ptr(tperiod.get()); ASSERT_TRUE(service_escalation); @@ -211,7 +211,7 @@ TEST_F(ServiceNotification, std::unique_ptr service_escalation{ new engine::serviceescalation("test_host", "test_svc", 0, 1, 1.0, "", 7, - Uuid())}; + 12345)}; _svc->set_notification_period_ptr(tperiod.get()); ASSERT_TRUE(service_escalation); @@ -232,7 +232,7 @@ TEST_F(ServiceNotification, SimpleNormalServiceNotificationForcedNotification) { std::unique_ptr service_escalation{ new engine::serviceescalation("test_host", "test_svc", 0, 1, 1.0, "", 7, - Uuid())}; + 12345)}; _svc->set_notification_period_ptr(tperiod.get()); ASSERT_TRUE(service_escalation); @@ -254,7 +254,7 @@ TEST_F(ServiceNotification, SimpleNormalServiceNotificationWithDowntime) { std::unique_ptr service_escalation{ new engine::serviceescalation("test_host", "test_svc", 0, 1, 1.0, "", 7, - Uuid())}; + 12345)}; _svc->set_notification_period_ptr(tperiod.get()); ASSERT_TRUE(service_escalation); @@ -276,7 +276,7 @@ TEST_F(ServiceNotification, SimpleNormalServiceNotificationWithFlapping) { std::unique_ptr service_escalation{ new engine::serviceescalation("test_host", "test_svc", 0, 1, 1.0, "", 7, - Uuid())}; + 12345)}; _svc->set_notification_period_ptr(tperiod.get()); ASSERT_TRUE(service_escalation); @@ -298,7 +298,7 @@ TEST_F(ServiceNotification, SimpleNormalServiceNotificationWithSoftState) { std::unique_ptr service_escalation{ new engine::serviceescalation("test_host", "test_svc", 0, 1, 1.0, "", 7, - Uuid())}; + 12345)}; _svc->set_notification_period_ptr(tperiod.get()); ASSERT_TRUE(service_escalation); @@ -320,7 +320,7 @@ TEST_F(ServiceNotification, std::unique_ptr service_escalation{ new engine::serviceescalation("test_host", "test_svc", 0, 1, 1.0, "", 7, - Uuid())}; + 12345)}; _svc->set_notification_period_ptr(tperiod.get()); _svc->set_acknowledgement(AckType::NORMAL); @@ -343,7 +343,7 @@ TEST_F(ServiceNotification, std::unique_ptr service_escalation{ new engine::serviceescalation("test_host", "test_svc", 0, 1, 1.0, "", 7, - Uuid())}; + 12345)}; _svc->set_notification_period_ptr(tperiod.get()); _svc->set_acknowledgement(AckType::NORMAL); @@ -367,7 +367,7 @@ TEST_F(ServiceNotification, std::unique_ptr service_escalation{ new engine::serviceescalation("test_host", "test_svc", 0, 1, 1.0, "", 7, - Uuid())}; + 12345)}; _svc->set_notification_period_ptr(tperiod.get()); _svc->set_acknowledgement(AckType::NORMAL); @@ -392,7 +392,7 @@ TEST_F(ServiceNotification, SimpleNormalServiceNotificationOnStateNotNotified) { std::unique_ptr service_escalation{ new engine::serviceescalation("test_host", "test_svc", 0, 1, 1.0, "", 7, - Uuid())}; + 12345)}; _svc->set_notification_period_ptr(tperiod.get()); _svc->set_acknowledgement(AckType::NONE); @@ -417,7 +417,7 @@ TEST_F(ServiceNotification, std::unique_ptr service_escalation{ new engine::serviceescalation("test_host", "test_svc", 0, 1, 1.0, "", 7, - Uuid())}; + 12345)}; _svc->set_notification_period_ptr(tperiod.get()); _svc->set_acknowledgement(AckType::NONE); @@ -444,7 +444,7 @@ TEST_F(ServiceNotification, std::unique_ptr service_escalation{ new engine::serviceescalation("test_host", "test_svc", 0, 1, 1.0, "", 7, - Uuid())}; + 12345)}; _svc->set_notification_period_ptr(tperiod.get()); _svc->set_acknowledgement(AckType::NONE); @@ -471,7 +471,7 @@ TEST_F(ServiceNotification, std::unique_ptr service_escalation{ new engine::serviceescalation("test_host", "test_svc", 0, 1, 1.0, - "tperiod", 7, Uuid())}; + "tperiod", 7, 12345)}; _svc->set_current_state(engine::service::state_critical); _svc->set_last_state(engine::service::state_critical); @@ -937,7 +937,7 @@ TEST_F(ServiceNotification, WarnCritServiceNotification) { std::unique_ptr service_escalation{ new engine::serviceescalation("test_host", "test_svc", 0, 1, 1.0, - "tperiod", 7, Uuid())}; + "tperiod", 7, 12345)}; _svc->set_current_state(engine::service::state_critical); _svc->set_last_state(engine::service::state_critical); _svc->set_last_hard_state_change(43200); @@ -974,7 +974,7 @@ TEST_F(ServiceNotification, SimpleNormalVolatileServiceNotification) { std::unique_ptr service_escalation{ new engine::serviceescalation("test_host", "test_svc", 0, 1, 1.0, - "tperiod", 7, Uuid())}; + "tperiod", 7, 12345)}; _svc->set_current_state(engine::service::state_critical); _svc->set_last_state(engine::service::state_critical); _svc->set_last_hard_state_change(43200); @@ -1023,7 +1023,7 @@ TEST_F(ServiceNotification, RecoveryNotifEvenIfServiceAcknowledged) { std::unique_ptr service_escalation{ new engine::serviceescalation("test_host", "test_svc", 0, 1, 1.0, - "tperiod", 7, Uuid())}; + "tperiod", 7, 12345)}; _svc->set_current_state(engine::service::state_critical); _svc->set_last_state(engine::service::state_critical); _svc->set_last_hard_state_change(43200); @@ -1083,7 +1083,7 @@ TEST_F(ServiceNotification, SimpleVolatileServiceNotificationWithDowntime) { std::unique_ptr service_escalation{ new engine::serviceescalation("test_host", "test_svc", 0, 1, 1.0, "", 7, - Uuid())}; + 12345)}; _svc->set_notification_period_ptr(tperiod.get()); ASSERT_TRUE(service_escalation); From 74789b98dec082815d94e1519b332956ab32b40b Mon Sep 17 00:00:00 2001 From: David Boucher Date: Tue, 18 Jun 2024 09:51:53 +0200 Subject: [PATCH 44/60] enh(engine): Engine exceptions in the configuration are replaced by msg_fmt. * enh(engine/configuration): unused headers removed * enh(engine/configuration): exceptions are engine independent * cleanup(engine): comments added * enh(engine): cleanup and fix after review --- bbdo/CMakeLists.txt | 10 -- bbdo/neb.proto | 77 +++++++++- bbdo/severity.proto | 56 -------- bbdo/tag.proto | 62 -------- .../com/centreon/broker/cache/global_cache.hh | 2 +- broker/grpc/CMakeLists.txt | 2 - broker/neb/CMakeLists.txt | 4 - .../inc/com/centreon/broker/neb/internal.hh | 2 - broker/victoria_metrics/test/request_test.cc | 1 - engine/enginerpc/engine_impl.cc | 1 + .../engine/configuration/anomalydetection.hh | 2 +- .../engine/configuration/file_info.hh | 16 ++- .../com/centreon/engine/configuration/host.hh | 1 - .../centreon/engine/configuration/service.hh | 1 - .../centreon/engine/configuration/state.hh | 12 +- engine/modules/bench/passive/engine_cfg.cc | 35 +++-- engine/modules/opentelemetry/CMakeLists.txt | 21 ++- engine/src/centenginestats.cc | 38 +++-- engine/src/checks/checker.cc | 1 + engine/src/commands/environment.cc | 37 +++-- engine/src/compatibility/sighandlers.cc | 38 +++-- engine/src/configuration/anomalydetection.cc | 57 ++++---- .../configuration/applier/anomalydetection.cc | 1 + engine/src/configuration/applier/connector.cc | 1 + engine/src/configuration/applier/contact.cc | 1 + engine/src/configuration/applier/host.cc | 1 + .../configuration/applier/hostdependency.cc | 1 + .../configuration/applier/hostescalation.cc | 1 + engine/src/configuration/applier/service.cc | 1 + .../applier/serviceescalation.cc | 1 + .../src/configuration/applier/timeperiod.cc | 1 + engine/src/configuration/command.cc | 12 +- engine/src/configuration/connector.cc | 17 ++- engine/src/configuration/contact.cc | 9 +- engine/src/configuration/contactgroup.cc | 10 +- engine/src/configuration/host.cc | 32 ++--- engine/src/configuration/hostdependency.cc | 24 ++-- engine/src/configuration/hostescalation.cc | 13 +- engine/src/configuration/hostgroup.cc | 15 +- engine/src/configuration/object.cc | 5 +- engine/src/configuration/parser.cc | 99 ++++++------- engine/src/configuration/service.cc | 26 ++-- engine/src/configuration/servicedependency.cc | 42 +++--- engine/src/configuration/serviceescalation.cc | 24 ++-- engine/src/configuration/servicegroup.cc | 13 +- engine/src/configuration/severity.cc | 16 +-- engine/src/configuration/state.cc | 135 +++++++++--------- engine/src/configuration/tag.cc | 12 +- engine/src/configuration/timeperiod.cc | 12 +- engine/src/events/sched_info.cc | 2 - engine/src/hostescalation.cc | 9 ++ engine/src/retention/dump.cc | 1 + engine/src/serviceescalation.cc | 9 ++ .../configuration/applier/applier-service.cc | 13 +- engine/tests/configuration/contact.cc | 3 +- 55 files changed, 494 insertions(+), 544 deletions(-) delete mode 100644 bbdo/severity.proto delete mode 100644 bbdo/tag.proto diff --git a/bbdo/CMakeLists.txt b/bbdo/CMakeLists.txt index 0bab457aa4e..5232e26135b 100644 --- a/bbdo/CMakeLists.txt +++ b/bbdo/CMakeLists.txt @@ -20,8 +20,6 @@ set(protobuf_files header rebuild_message remove_graph_message - severity - tag bbdo neb storage @@ -63,14 +61,6 @@ add_library(pb_bbdo_lib STATIC bbdo.pb.cc bbdo.pb.h) add_dependencies(pb_bbdo_lib target_bbdo) set_target_properties(pb_bbdo_lib PROPERTIES POSITION_INDEPENDENT_CODE ON) -add_library(pb_severity_lib STATIC severity.pb.cc severity.pb.h) -add_dependencies(pb_severity_lib target_neb) -set_target_properties(pb_severity_lib PROPERTIES POSITION_INDEPENDENT_CODE ON) - -add_library(pb_tag_lib STATIC tag.pb.cc tag.pb.h) -add_dependencies(pb_tag_lib target_neb) -set_target_properties(pb_tag_lib PROPERTIES POSITION_INDEPENDENT_CODE ON) - add_library(pb_bam_lib STATIC bam.pb.cc bam.pb.h bam_state.pb.cc bam_state.pb.h) add_dependencies(pb_bam_lib target_bam target_bam_state target_header) set_target_properties(pb_bam_lib PROPERTIES POSITION_INDEPENDENT_CODE ON) diff --git a/bbdo/neb.proto b/bbdo/neb.proto index 0f3b73c2e42..b4603072255 100644 --- a/bbdo/neb.proto +++ b/bbdo/neb.proto @@ -19,7 +19,6 @@ syntax = "proto3"; import "header.proto"; -import "tag.proto"; package com.centreon.broker; @@ -740,3 +739,79 @@ message InstanceConfiguration { bool loaded = 2; uint64 poller_id = 3; } + +/** + * @brief A severity is a way to give some importance to a resource. It has a + * level that is an integer from 1. 1 is more important than 2, than 3... + * It also has an id, a level, an icon_id and a name. + * + * Because a severity can be sent from several poller, and by moment a poller + * can say it does not need it anymore, broker needs to know from which poller + * the severity event comes from, so we have a poller_id in the message. + * + * For example, two pollers use a severity named 'foo'. Then the first one sends + * a Severity message with the action DELETE. This means this poller does not + * need it anymore but we don't know about the other poller. Then we can remove + * relations between resources of our poller and this severity. And only if the + * severity is no more used at all, we can remove it. + */ +/*io::neb, neb::de_pb_severity*/ +message Severity { + uint64 id = 1; + enum Action { + ADD = 0; + DELETE = 1; + MODIFY = 2; + } + Action action = 2; + uint32 level = 3; + uint64 icon_id = 4; + string name = 5; + enum Type { + SERVICE = 0; + HOST = 1; + } + Type type = 6; + uint64 poller_id = 7; +} + +/** + * @brief A tag is a generalization of a host group or a service group. It + * is a way to group resources. It has an id, a type and a name. + * + * Because a tag can be sent from several poller, and by moment a poller can + * say it does not need it anymore, broker needs to know from which poller the + * tag event comes from, so we have a poller_id in the message. + * + * For example, two pollers use a tag named 'foo'. Then the first one sends a + * Tag message with the action DELETE. This means this poller does not need it + * anymore but we don't know about the other poller. Then we can remove + * relations between resources of our poller and this tag. And only if the tag + * is no more used at all, we can remove it. + */ +enum TagType { + SERVICEGROUP = 0; + HOSTGROUP = 1; + SERVICECATEGORY = 2; + HOSTCATEGORY = 3; +} + +/*io::neb, neb::de_pb_tag*/ +message Tag { + uint64 id = 1; + enum Action { + ADD = 0; + DELETE = 1; + MODIFY = 2; + } + + Action action = 2; + TagType type = 3; + string name = 4; + int64 poller_id = 5; +} + +message TagInfo { + uint64 id = 1; + TagType type = 2; +} diff --git a/bbdo/severity.proto b/bbdo/severity.proto deleted file mode 100644 index 44781d3af1c..00000000000 --- a/bbdo/severity.proto +++ /dev/null @@ -1,56 +0,0 @@ -/* -** Copyright 2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ - -syntax = "proto3"; - -package com.centreon.broker; - -/** - * @brief A severity is a way to give some importance to a resource. It has a - * level that is an integer from 1. 1 is more important than 2, than 3... - * It also has an id, a level, an icon_id and a name. - * - * Because a severity can be sent from several poller, and by moment a poller - * can say it does not need it anymore, broker needs to know from which poller - * the severity event comes from, so we have a poller_id in the message. - * - * For example, two pollers use a severity named 'foo'. Then the first one sends - * a Severity message with the action DELETE. This means this poller does not - * need it anymore but we don't know about the other poller. Then we can remove - * relations between resources of our poller and this severity. And only if the - * severity is no more used at all, we can remove it. - */ -/*io::neb, neb::de_pb_severity*/ -message Severity { - uint64 id = 1; - enum Action { - ADD = 0; - DELETE = 1; - MODIFY = 2; - } - Action action = 2; - uint32 level = 3; - uint64 icon_id = 4; - string name = 5; - enum Type { - SERVICE = 0; - HOST = 1; - } - Type type = 6; - uint64 poller_id = 7; -} diff --git a/bbdo/tag.proto b/bbdo/tag.proto deleted file mode 100644 index d12898d8470..00000000000 --- a/bbdo/tag.proto +++ /dev/null @@ -1,62 +0,0 @@ -/* -** Copyright 2022 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ - -syntax = "proto3"; - -package com.centreon.broker; - -/** - * @brief A tag is a generalization of a host group or a service group. It - * is a way to group resources. It has an id, a type and a name. - * - * Because a tag can be sent from several poller, and by moment a poller can - * say it does not need it anymore, broker needs to know from which poller the - * tag event comes from, so we have a poller_id in the message. - * - * For example, two pollers use a tag named 'foo'. Then the first one sends a - * Tag message with the action DELETE. This means this poller does not need it - * anymore but we don't know about the other poller. Then we can remove - * relations between resources of our poller and this tag. And only if the tag - * is no more used at all, we can remove it. - */ -enum TagType { - SERVICEGROUP = 0; - HOSTGROUP = 1; - SERVICECATEGORY = 2; - HOSTCATEGORY = 3; -} - -/*io::neb, neb::de_pb_tag*/ -message Tag { - uint64 id = 1; - enum Action { - ADD = 0; - DELETE = 1; - MODIFY = 2; - } - - Action action = 2; - TagType type = 3; - string name = 4; - int64 poller_id = 5; -} - -message TagInfo { - uint64 id = 1; - TagType type = 2; -} diff --git a/broker/core/inc/com/centreon/broker/cache/global_cache.hh b/broker/core/inc/com/centreon/broker/cache/global_cache.hh index 58a12960287..f4f4e9b1c03 100644 --- a/broker/core/inc/com/centreon/broker/cache/global_cache.hh +++ b/broker/core/inc/com/centreon/broker/cache/global_cache.hh @@ -19,7 +19,7 @@ #ifndef CCB_GLOBAL_CACHE_HH #define CCB_GLOBAL_CACHE_HH -#include "bbdo/tag.pb.h" +#include "bbdo/neb.pb.h" namespace com::centreon::broker { diff --git a/broker/grpc/CMakeLists.txt b/broker/grpc/CMakeLists.txt index 2dd00ce8935..023c192501a 100644 --- a/broker/grpc/CMakeLists.txt +++ b/broker/grpc/CMakeLists.txt @@ -52,8 +52,6 @@ target_link_libraries( pb_neb_lib pb_storage_lib pb_bbdo_lib - pb_severity_lib - pb_tag_lib pb_bam_lib pb_extcmd_lib pb_open_telemetry_lib diff --git a/broker/neb/CMakeLists.txt b/broker/neb/CMakeLists.txt index b465e8b3942..7e1836bf98d 100644 --- a/broker/neb/CMakeLists.txt +++ b/broker/neb/CMakeLists.txt @@ -95,16 +95,12 @@ add_dependencies( nebbase table_max_size target_neb - target_severity - target_tag pb_neb_lib pb_header_lib) target_link_libraries(nebbase -L${PROTOBUF_LIB_DIR} protobuf - pb_severity_lib - pb_tag_lib pb_neb_lib pb_header_lib pb_open_telemetry_lib) diff --git a/broker/neb/inc/com/centreon/broker/neb/internal.hh b/broker/neb/inc/com/centreon/broker/neb/internal.hh index 083f48ccf13..b3fba5da256 100644 --- a/broker/neb/inc/com/centreon/broker/neb/internal.hh +++ b/broker/neb/inc/com/centreon/broker/neb/internal.hh @@ -22,8 +22,6 @@ #include #include "bbdo/events.hh" #include "bbdo/neb.pb.h" -#include "bbdo/severity.pb.h" -#include "bbdo/tag.pb.h" #include "com/centreon/broker/io/protobuf.hh" #include "com/centreon/broker/multiplexing/publisher.hh" #include "com/centreon/broker/neb/callback.hh" diff --git a/broker/victoria_metrics/test/request_test.cc b/broker/victoria_metrics/test/request_test.cc index fea88349e2b..0ceaf56bfab 100644 --- a/broker/victoria_metrics/test/request_test.cc +++ b/broker/victoria_metrics/test/request_test.cc @@ -28,7 +28,6 @@ using system_clock = std::chrono::system_clock; using time_point = system_clock::time_point; using duration = system_clock::duration; -#include "bbdo/tag.pb.h" #include "com/centreon/broker/cache/global_cache.hh" #include "com/centreon/broker/file/disk_accessor.hh" #include "com/centreon/broker/io/protocols.hh" diff --git a/engine/enginerpc/engine_impl.cc b/engine/enginerpc/engine_impl.cc index 0476f9dc9d0..8c5e5b89b20 100644 --- a/engine/enginerpc/engine_impl.cc +++ b/engine/enginerpc/engine_impl.cc @@ -55,6 +55,7 @@ namespace asio = boost::asio; #include "com/centreon/engine/globals.hh" #include "com/centreon/engine/hostdependency.hh" #include "com/centreon/engine/hostgroup.hh" +#include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/service.hh" #include "com/centreon/engine/servicedependency.hh" #include "com/centreon/engine/servicegroup.hh" diff --git a/engine/inc/com/centreon/engine/configuration/anomalydetection.hh b/engine/inc/com/centreon/engine/configuration/anomalydetection.hh index 71f6c10af98..52be0782d96 100644 --- a/engine/inc/com/centreon/engine/configuration/anomalydetection.hh +++ b/engine/inc/com/centreon/engine/configuration/anomalydetection.hh @@ -19,7 +19,7 @@ #ifndef CCE_CONFIGURATION_ANOMALYDETECTION_HH #define CCE_CONFIGURATION_ANOMALYDETECTION_HH -#include "com/centreon/engine/common.hh" +#include "bbdo/neb.pb.h" #include "com/centreon/engine/configuration/customvariable.hh" #include "com/centreon/engine/configuration/group.hh" #include "com/centreon/engine/configuration/object.hh" diff --git a/engine/inc/com/centreon/engine/configuration/file_info.hh b/engine/inc/com/centreon/engine/configuration/file_info.hh index 6ec9e4e8626..7737dd1144c 100644 --- a/engine/inc/com/centreon/engine/configuration/file_info.hh +++ b/engine/inc/com/centreon/engine/configuration/file_info.hh @@ -20,8 +20,6 @@ #ifndef CCE_CONFIGURATION_FILE_INFO_HH #define CCE_CONFIGURATION_FILE_INFO_HH -#include "com/centreon/engine/exceptions/error.hh" - namespace com::centreon::engine { namespace configuration { @@ -47,10 +45,9 @@ class file_info { bool operator!=(file_info const& right) const noexcept { return !operator==(right); } - friend exceptions::error& operator<<(exceptions::error& err, - file_info const& info) { - err << "in file '" << info.path() << "' on line " << info.line(); - return err; + friend std::ostream& operator<<(std::ostream& s, file_info const& info) { + s << "in file '" << info.path() << "' on line " << info.line(); + return s; } unsigned int line() const noexcept { return _line; } void line(unsigned int line) noexcept { _line = line; } @@ -61,4 +58,11 @@ class file_info { } // namespace com::centreon::engine +namespace fmt { +// formatter specializations for fmt +template <> +struct formatter + : ostream_formatter {}; +} // namespace fmt + #endif // !CCE_CONFIGURATION_FILE_INFO_HH diff --git a/engine/inc/com/centreon/engine/configuration/host.hh b/engine/inc/com/centreon/engine/configuration/host.hh index 121ed461116..50efe049291 100644 --- a/engine/inc/com/centreon/engine/configuration/host.hh +++ b/engine/inc/com/centreon/engine/configuration/host.hh @@ -19,7 +19,6 @@ #ifndef CCE_CONFIGURATION_HOST_HH #define CCE_CONFIGURATION_HOST_HH -#include "com/centreon/engine/common.hh" #include "com/centreon/engine/configuration/customvariable.hh" #include "com/centreon/engine/configuration/group.hh" #include "com/centreon/engine/configuration/object.hh" diff --git a/engine/inc/com/centreon/engine/configuration/service.hh b/engine/inc/com/centreon/engine/configuration/service.hh index 55c15e5d555..135699e6144 100644 --- a/engine/inc/com/centreon/engine/configuration/service.hh +++ b/engine/inc/com/centreon/engine/configuration/service.hh @@ -19,7 +19,6 @@ #ifndef CCE_CONFIGURATION_SERVICE_HH #define CCE_CONFIGURATION_SERVICE_HH -#include "com/centreon/engine/common.hh" #include "com/centreon/engine/configuration/customvariable.hh" #include "com/centreon/engine/configuration/group.hh" #include "com/centreon/engine/configuration/object.hh" diff --git a/engine/inc/com/centreon/engine/configuration/state.hh b/engine/inc/com/centreon/engine/configuration/state.hh index 3b9b25de0c1..c2e412f1ea2 100644 --- a/engine/inc/com/centreon/engine/configuration/state.hh +++ b/engine/inc/com/centreon/engine/configuration/state.hh @@ -35,7 +35,6 @@ #include "com/centreon/engine/configuration/severity.hh" #include "com/centreon/engine/configuration/tag.hh" #include "com/centreon/engine/configuration/timeperiod.hh" -#include "com/centreon/engine/logging/logger.hh" namespace com::centreon::engine::configuration { @@ -61,6 +60,17 @@ class setter_base { * to manage configuration data. */ class state { + enum logger_type { + LOG_ALL = 2096895ull, + DBG_ALL = (4095ull << 32), + ALL = LOG_ALL | DBG_ALL, + }; + enum logger_verbosity_level { + BASIC = 0u, + MORE = 1u, + MOST = 2u, + }; + std::shared_ptr _logger; public: diff --git a/engine/modules/bench/passive/engine_cfg.cc b/engine/modules/bench/passive/engine_cfg.cc index 6fd8cbd29ec..b1006d6bbd9 100644 --- a/engine/modules/bench/passive/engine_cfg.cc +++ b/engine/modules/bench/passive/engine_cfg.cc @@ -1,21 +1,21 @@ /** -* Copyright 2015 Merethis -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2015 Merethis + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "engine_cfg.hh" #include @@ -193,5 +193,4 @@ void engine_cfg::_write_file(std::string const& target, ofs.write(content.data(), content.size()); ofs.close(); } - return; } diff --git a/engine/modules/opentelemetry/CMakeLists.txt b/engine/modules/opentelemetry/CMakeLists.txt index 0146d3f81de..f3407f88aaa 100644 --- a/engine/modules/opentelemetry/CMakeLists.txt +++ b/engine/modules/opentelemetry/CMakeLists.txt @@ -35,7 +35,7 @@ foreach(name IN LISTS service_files) COMMAND ${Protobuf_PROTOC_EXECUTABLE} ARGS --plugin=protoc-gen-grpc=${GRPC_CPP_PLUGIN} - --proto_path=${CMAKE_SOURCE_DIR}/opentelemetry-proto + --proto_path=${CMAKE_SOURCE_DIR}/opentelemetry-proto --grpc_out=${SRC_DIR} ${proto_file} VERBATIM WORKING_DIRECTORY ${CMAKE_BINARY_DIR}) @@ -44,7 +44,7 @@ endforeach() # mod_externalcmd target. -add_library(opentelemetry SHARED +add_library(opentelemetry SHARED ${SRC_DIR}/data_point_fifo.cc ${SRC_DIR}/data_point_fifo_container.cc ${SRC_DIR}/grpc_config.cc @@ -65,20 +65,19 @@ target_precompile_headers(opentelemetry PRIVATE precomp_inc/precomp.hh) # set(EXTERNALCMD_MODULE "${EXTERNALCMD_MODULE}" PARENT_SCOPE) target_link_libraries(opentelemetry spdlog::spdlog) -add_dependencies(opentelemetry +add_dependencies(opentelemetry pb_open_telemetry_lib - pb_neb_lib - pb_tag_lib) + pb_neb_lib) -target_include_directories(opentelemetry PRIVATE - "${MODULE_DIR}/inc/com/centreon/engine/modules/opentelemetry" - "${CMAKE_SOURCE_DIR}/bbdo" +target_include_directories(opentelemetry PRIVATE + "${MODULE_DIR}/inc/com/centreon/engine/modules/opentelemetry" + "${CMAKE_SOURCE_DIR}/bbdo" "${MODULE_DIR}/inc" ${CMAKE_SOURCE_DIR}/common/inc - ${CMAKE_SOURCE_DIR}/common/http/inc - ${CMAKE_SOURCE_DIR}/common/grpc/inc + ${CMAKE_SOURCE_DIR}/common/http/inc + ${CMAKE_SOURCE_DIR}/common/grpc/inc src - ${PROJECT_SOURCE_DIR}/enginerpc + ${PROJECT_SOURCE_DIR}/enginerpc ${CMAKE_SOURCE_DIR}/common/src ) diff --git a/engine/src/centenginestats.cc b/engine/src/centenginestats.cc index 14646c20d69..02ceff82345 100644 --- a/engine/src/centenginestats.cc +++ b/engine/src/centenginestats.cc @@ -1,22 +1,22 @@ /** -* Copyright 2003-2008 Ethan Galstad -* Copyright 2011-2013,2016 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2003-2008 Ethan Galstad + * Copyright 2011-2013,2016 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #ifdef HAVE_GETOPT_H #include @@ -1455,7 +1455,6 @@ void strip(char* buffer) { buffer[z - x] = buffer[z]; buffer[y - x] = '\x0'; } - return; } /* get days, hours, minutes, and seconds from a raw time_t format or total @@ -1485,5 +1484,4 @@ void get_time_breakdown(unsigned long raw_time, *hours = temp_hours; *minutes = temp_minutes; *seconds = temp_seconds; - return; } diff --git a/engine/src/checks/checker.cc b/engine/src/checks/checker.cc index 44e57c0b3f2..6293272e1fa 100644 --- a/engine/src/checks/checker.cc +++ b/engine/src/checks/checker.cc @@ -23,6 +23,7 @@ #include "com/centreon/engine/configuration/whitelist.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" +#include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/macros.hh" #include "com/centreon/engine/neberrors.hh" #include "com/centreon/engine/objects.hh" diff --git a/engine/src/commands/environment.cc b/engine/src/commands/environment.cc index f6e0e9c803a..a464ae2e15f 100644 --- a/engine/src/commands/environment.cc +++ b/engine/src/commands/environment.cc @@ -1,22 +1,22 @@ /** -* Copyright 2012-2013 Merethis -* -* This file is part of Centreon Clib. -* -* Centreon Clib is free software: you can redistribute it -* and/or modify it under the terms of the GNU Affero General Public -* License as published by the Free Software Foundation, either version -* 3 of the License, or (at your option) any later version. -* -* Centreon Clib is distributed in the hope that it will be -* useful, but WITHOUT ANY WARRANTY; without even the implied warranty -* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* Affero General Public License for more details. -* -* You should have received a copy of the GNU Affero General Public -* License along with Centreon Clib. If not, see -* . -*/ + * Copyright 2012-2013 Merethis + * + * This file is part of Centreon Clib. + * + * Centreon Clib is free software: you can redistribute it + * and/or modify it under the terms of the GNU Affero General Public + * License as published by the Free Software Foundation, either version + * 3 of the License, or (at your option) any later version. + * + * Centreon Clib is distributed in the hope that it will be + * useful, but WITHOUT ANY WARRANTY; without even the implied warranty + * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public + * License along with Centreon Clib. If not, see + * . + */ #include "com/centreon/engine/commands/environment.hh" #include "com/centreon/engine/exceptions/error.hh" @@ -180,7 +180,6 @@ void environment::_realloc_env(uint32_t size) { _size_env = size; delete[] _env; _env = new_env; - return; } /** diff --git a/engine/src/compatibility/sighandlers.cc b/engine/src/compatibility/sighandlers.cc index a836c649053..6f72dc75589 100644 --- a/engine/src/compatibility/sighandlers.cc +++ b/engine/src/compatibility/sighandlers.cc @@ -1,21 +1,21 @@ /** -* Copyright 2011-2013 Merethis -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2011-2013 Merethis + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include "sighandlers.h" #include @@ -45,7 +45,6 @@ static void sighandler_helper(char const* msg, unsigned int size, int ret) { // Exit. _Exit(ret); - return; } extern "C" { @@ -58,7 +57,6 @@ void host_check_sighandler(int sig) { (void)sig; sighandler_helper(HOST_TIMEOUT_OUTPUT, sizeof(HOST_TIMEOUT_OUTPUT) - 1, service::state_unknown); - return; } /** @@ -69,7 +67,6 @@ void host_check_sighandler(int sig) { void my_system_sighandler(int sig) { (void)sig; sighandler_helper(NULL, 0, service::state_unknown); - return; } /** @@ -81,6 +78,5 @@ void service_check_sighandler(int sig) { (void)sig; sighandler_helper(SERVICE_TIMEOUT_OUTPUT, sizeof(SERVICE_TIMEOUT_OUTPUT) - 1, service::state_unknown); - return; } } diff --git a/engine/src/configuration/anomalydetection.cc b/engine/src/configuration/anomalydetection.cc index c56b45553ec..8e5c84f74ea 100644 --- a/engine/src/configuration/anomalydetection.cc +++ b/engine/src/configuration/anomalydetection.cc @@ -21,15 +21,14 @@ #include #include #include -#include "com/centreon/engine/exceptions/error.hh" -#include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/host.hh" +#include "com/centreon/exceptions/msg_fmt.hh" extern int config_warnings; extern int config_errors; using namespace com::centreon; using namespace com::centreon::engine::configuration; +using com::centreon::exceptions::msg_fmt; #define SETTER(type, method) \ &object::setter::generic @@ -125,7 +124,7 @@ static unsigned short const default_flap_detection_options( anomalydetection::unknown | anomalydetection::critical); static unsigned int const default_freshness_threshold(0); static unsigned int const default_high_flap_threshold(0); -static unsigned int const default_initial_state(engine::service::state_ok); +static unsigned int const default_initial_state(broker::Service_State_OK); static bool const default_is_volatile(false); static unsigned int const default_low_flap_threshold(0); static unsigned int const default_max_check_attempts(3); @@ -755,24 +754,26 @@ bool anomalydetection::operator<(anomalydetection const& other) const noexcept { /** * Check if the object is valid. * - * @exception engine_error if this anomalydetection is an invalid object. + * @exception msg_fmt if this anomalydetection is an invalid object. */ void anomalydetection::check_validity() const { if (_service_description.empty()) - throw engine_error() << "Service has no description (property " - << "'service_description')"; + throw msg_fmt( + "Service has no description (property 'service_description')"); if (_host_name.empty()) - throw engine_error() << "Service '" << _service_description - << "' is not attached to any host (property " - "'host_name')"; + throw msg_fmt( + "Service '{}' is not attached to any host (property 'host_name')", + _service_description); if (_metric_name.empty()) - throw engine_error() - << "Anomaly detection service '" << _service_description - << "' has no metric name specified (property 'metric_name')"; + throw msg_fmt( + "Anomaly detection service '{}' has no metric name specified (property " + "'metric_name')", + _service_description); if (_thresholds_file.empty()) - throw engine_error() - << "Anomaly detection service '" << _service_description - << "' has no thresholds file specified (property 'thresholds_file')"; + throw msg_fmt( + "Anomaly detection service '{}' has no thresholds file specified " + "(property 'thresholds_file')", + _service_description); } /** @@ -792,8 +793,8 @@ anomalydetection::key_type anomalydetection::key() const { */ void anomalydetection::merge(object const& obj) { if (obj.type() != _type) - throw engine_error() << "Cannot merge anomalydetection with '" << obj.type() - << "'"; + throw msg_fmt("Cannot merge anomalydetection with '{}'", + static_cast(obj.type())); anomalydetection const& tmpl(static_cast(obj)); MRG_OPTION(_acknowledgement_timeout); @@ -1764,13 +1765,13 @@ bool anomalydetection::_set_initial_state(std::string const& value) { std::string_view data(value); data = absl::StripAsciiWhitespace(data); if (data == "o" || data == "ok") - _initial_state = engine::service::state_ok; + _initial_state = broker::Service_State_OK; else if (data == "w" || data == "warning") - _initial_state = engine::service::state_warning; + _initial_state = broker::Service_State_WARNING; else if (data == "u" || data == "unknown") - _initial_state = engine::service::state_unknown; + _initial_state = broker::Service_State_UNKNOWN; else if (data == "c" || data == "critical") - _initial_state = engine::service::state_critical; + _initial_state = broker::Service_State_CRITICAL; else return false; return true; @@ -2112,10 +2113,10 @@ bool anomalydetection::_set_timezone(std::string const& value) { bool anomalydetection::_set_category_tags(const std::string& value) { bool ret = true; std::list tags{absl::StrSplit(value, ',')}; - for (std::set>::iterator it(_tags.begin()), - end(_tags.end()); + for (std::set>::iterator it = _tags.begin(), + end = _tags.end(); it != end;) { - if (it->second == tag::servicecategory) + if (it->second == broker::SERVICECATEGORY) it = _tags.erase(it); else ++it; @@ -2126,7 +2127,7 @@ bool anomalydetection::_set_category_tags(const std::string& value) { bool parse_ok; parse_ok = absl::SimpleAtoi(tag, &id); if (parse_ok) { - _tags.emplace(id, tag::servicecategory); + _tags.emplace(id, broker::SERVICECATEGORY); } else { _logger->warn( "Warning: anomalydetection ({}, {}) error for parsing tag {}", @@ -2150,7 +2151,7 @@ bool anomalydetection::_set_group_tags(const std::string& value) { for (std::set>::iterator it(_tags.begin()), end(_tags.end()); it != end;) { - if (it->second == tag::servicegroup) + if (it->second == broker::SERVICEGROUP) it = _tags.erase(it); else ++it; @@ -2161,7 +2162,7 @@ bool anomalydetection::_set_group_tags(const std::string& value) { bool parse_ok; parse_ok = absl::SimpleAtoi(tag, &id); if (parse_ok) { - _tags.emplace(id, tag::servicegroup); + _tags.emplace(id, broker::SERVICEGROUP); } else { _logger->warn( "Warning: anomalydetection ({}, {}) error for parsing tag {}", diff --git a/engine/src/configuration/applier/anomalydetection.cc b/engine/src/configuration/applier/anomalydetection.cc index 3cac2fe529b..35f1de0b428 100644 --- a/engine/src/configuration/applier/anomalydetection.cc +++ b/engine/src/configuration/applier/anomalydetection.cc @@ -24,6 +24,7 @@ #include "com/centreon/engine/downtimes/downtime_manager.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" +#include "com/centreon/engine/logging/logger.hh" using namespace com::centreon; using namespace com::centreon::engine; diff --git a/engine/src/configuration/applier/connector.cc b/engine/src/configuration/applier/connector.cc index 0fdf87f9c40..4c51c1f5e1f 100644 --- a/engine/src/configuration/applier/connector.cc +++ b/engine/src/configuration/applier/connector.cc @@ -23,6 +23,7 @@ #include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" +#include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/macros/misc.hh" #include "com/centreon/engine/macros/process.hh" #include "com/centreon/exceptions/msg_fmt.hh" diff --git a/engine/src/configuration/applier/contact.cc b/engine/src/configuration/applier/contact.cc index 52469cdb181..59df873f2bc 100644 --- a/engine/src/configuration/applier/contact.cc +++ b/engine/src/configuration/applier/contact.cc @@ -25,6 +25,7 @@ #include "com/centreon/engine/deleter/listmember.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" +#include "com/centreon/engine/logging/logger.hh" using namespace com::centreon; using namespace com::centreon::engine; diff --git a/engine/src/configuration/applier/host.cc b/engine/src/configuration/applier/host.cc index 8459866d7ac..6577915df86 100644 --- a/engine/src/configuration/applier/host.cc +++ b/engine/src/configuration/applier/host.cc @@ -27,6 +27,7 @@ #include "com/centreon/engine/downtimes/downtime_manager.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" +#include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/severity.hh" using namespace com::centreon; diff --git a/engine/src/configuration/applier/hostdependency.cc b/engine/src/configuration/applier/hostdependency.cc index accbce7e42f..50a071559d1 100644 --- a/engine/src/configuration/applier/hostdependency.cc +++ b/engine/src/configuration/applier/hostdependency.cc @@ -23,6 +23,7 @@ #include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" +#include "com/centreon/engine/logging/logger.hh" using namespace com::centreon::engine::configuration; diff --git a/engine/src/configuration/applier/hostescalation.cc b/engine/src/configuration/applier/hostescalation.cc index d9a2c89f596..4337dde13cb 100644 --- a/engine/src/configuration/applier/hostescalation.cc +++ b/engine/src/configuration/applier/hostescalation.cc @@ -23,6 +23,7 @@ #include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" +#include "com/centreon/engine/logging/logger.hh" using namespace com::centreon::engine::configuration; diff --git a/engine/src/configuration/applier/service.cc b/engine/src/configuration/applier/service.cc index fe0259e38fc..76d915b9ad6 100644 --- a/engine/src/configuration/applier/service.cc +++ b/engine/src/configuration/applier/service.cc @@ -25,6 +25,7 @@ #include "com/centreon/engine/downtimes/downtime_manager.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" +#include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/severity.hh" using namespace com::centreon; diff --git a/engine/src/configuration/applier/serviceescalation.cc b/engine/src/configuration/applier/serviceescalation.cc index 053ffc5359b..0141abb6f49 100644 --- a/engine/src/configuration/applier/serviceescalation.cc +++ b/engine/src/configuration/applier/serviceescalation.cc @@ -23,6 +23,7 @@ #include "com/centreon/engine/configuration/serviceescalation.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" +#include "com/centreon/engine/logging/logger.hh" using namespace com::centreon::engine::configuration; diff --git a/engine/src/configuration/applier/timeperiod.cc b/engine/src/configuration/applier/timeperiod.cc index cd1b6aa03b4..3140a879660 100644 --- a/engine/src/configuration/applier/timeperiod.cc +++ b/engine/src/configuration/applier/timeperiod.cc @@ -25,6 +25,7 @@ #include "com/centreon/engine/deleter/listmember.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" +#include "com/centreon/engine/logging/logger.hh" using namespace com::centreon::engine::configuration; diff --git a/engine/src/configuration/command.cc b/engine/src/configuration/command.cc index 2cde3522942..28bf2b34856 100644 --- a/engine/src/configuration/command.cc +++ b/engine/src/configuration/command.cc @@ -18,10 +18,11 @@ * */ #include "com/centreon/engine/configuration/command.hh" -#include "com/centreon/engine/exceptions/error.hh" +#include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon; using namespace com::centreon::engine::configuration; +using com::centreon::exceptions::msg_fmt; #define SETTER(type, method) \ &object::setter::generic @@ -114,10 +115,10 @@ bool command::operator<(command const& right) const throw() { */ void command::check_validity() const { if (_command_name.empty()) - throw(engine_error() << "Command has no name (property 'command_name')"); + throw msg_fmt("Command has no name (property 'command_name')"); if (_command_line.empty()) - throw(engine_error() << "Command '" << _command_name - << "' has no command line (property 'command_line')"); + throw msg_fmt("Command '{}' has no command line (property 'command_line')", + _command_name); } /** @@ -136,7 +137,8 @@ command::key_type const& command::key() const throw() { */ void command::merge(object const& obj) { if (obj.type() != _type) - throw(engine_error() << "Cannot merge command with '" << obj.type() << "'"); + throw msg_fmt("Cannot merge command with '{}'", + static_cast(obj.type())); command const& tmpl(static_cast(obj)); MRG_DEFAULT(_command_line); diff --git a/engine/src/configuration/connector.cc b/engine/src/configuration/connector.cc index 83c637b8510..5f67da8927a 100644 --- a/engine/src/configuration/connector.cc +++ b/engine/src/configuration/connector.cc @@ -18,11 +18,11 @@ * */ #include "com/centreon/engine/configuration/connector.hh" -#include "com/centreon/engine/checks/checker.hh" -#include "com/centreon/engine/exceptions/error.hh" +#include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon; using namespace com::centreon::engine::configuration; +using com::centreon::exceptions::msg_fmt; #define SETTER(type, method) \ &object::setter::generic @@ -114,12 +114,11 @@ bool connector::operator<(connector const& right) const throw() { */ void connector::check_validity() const { if (_connector_name.empty()) - throw( - engine_error() << "Connector has no name (property 'connector_name')"); + throw msg_fmt("Connector has no name (property 'connector_name')"); if (_connector_line.empty()) - throw( - engine_error() << "Connector '" << _connector_name - << "' has no command line (property 'connector_line')"); + throw msg_fmt( + "Connector '{}' has no command line (property 'connector_line')", + _connector_name); } /** @@ -138,8 +137,8 @@ connector::key_type const& connector::key() const throw() { */ void connector::merge(object const& obj) { if (obj.type() != _type) - throw(engine_error() << "Cannot merge connector with '" << obj.type() - << "'"); + throw msg_fmt("Cannot merge connector with '{}'", + static_cast(obj.type())); connector const& tmpl(static_cast(obj)); MRG_DEFAULT(_connector_line); diff --git a/engine/src/configuration/contact.cc b/engine/src/configuration/contact.cc index 381839ab1e7..65900b90d60 100644 --- a/engine/src/configuration/contact.cc +++ b/engine/src/configuration/contact.cc @@ -16,15 +16,15 @@ * For more information : contact@centreon.com * */ - #include "com/centreon/engine/configuration/contact.hh" #include "com/centreon/engine/configuration/host.hh" #include "com/centreon/engine/configuration/service.hh" -#include "com/centreon/engine/exceptions/error.hh" +#include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon; using namespace com::centreon::engine; using namespace com::centreon::engine::configuration; +using com::centreon::exceptions::msg_fmt; #define SETTER(type, method) \ &object::setter::generic @@ -232,7 +232,7 @@ bool contact::operator<(contact const& other) const noexcept { */ void contact::check_validity() const { if (_contact_name.empty()) - throw(engine_error() << "Contact has no name (property 'contact_name')"); + throw msg_fmt("Contact has no name (property 'contact_name')"); } /** @@ -251,7 +251,8 @@ contact::key_type const& contact::key() const noexcept { */ void contact::merge(object const& obj) { if (obj.type() != _type) - throw(engine_error() << "Cannot merge contact with '" << obj.type() << "'"); + throw msg_fmt("Cannot merge contact with '{}'", + static_cast(obj.type())); contact const& tmpl(static_cast(obj)); MRG_TAB(_address); diff --git a/engine/src/configuration/contactgroup.cc b/engine/src/configuration/contactgroup.cc index c9c05c5dd8b..9e0e4a484c6 100644 --- a/engine/src/configuration/contactgroup.cc +++ b/engine/src/configuration/contactgroup.cc @@ -17,10 +17,11 @@ * */ #include "com/centreon/engine/configuration/contactgroup.hh" -#include "com/centreon/engine/exceptions/error.hh" +#include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon; using namespace com::centreon::engine::configuration; +using com::centreon::exceptions::msg_fmt; #define SETTER(type, method) \ &object::setter::generic @@ -122,8 +123,7 @@ bool contactgroup::operator<(contactgroup const& right) const throw() { */ void contactgroup::check_validity() const { if (_contactgroup_name.empty()) - throw(engine_error() << "Contact group has no name " - "(property 'contactgroup_name')"); + throw msg_fmt("Contact group has no name (property 'contactgroup_name')"); } /** @@ -142,8 +142,8 @@ contactgroup::key_type const& contactgroup::key() const throw() { */ void contactgroup::merge(object const& obj) { if (obj.type() != _type) - throw(engine_error() << "Cannot merge contact group with '" << obj.type() - << "'"); + throw msg_fmt("Cannot merge contact group with '{}'", + static_cast(obj.type())); contactgroup const& tmpl(static_cast(obj)); MRG_DEFAULT(_alias); diff --git a/engine/src/configuration/host.cc b/engine/src/configuration/host.cc index 81dc5838a89..7d255c874ff 100644 --- a/engine/src/configuration/host.cc +++ b/engine/src/configuration/host.cc @@ -22,17 +22,15 @@ #include "absl/strings/numbers.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" -#include "com/centreon/engine/exceptions/error.hh" -#include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/host.hh" -#include "com/centreon/engine/logging/logger.hh" +#include "bbdo/neb.pb.h" +#include "com/centreon/exceptions/msg_fmt.hh" extern int config_warnings; extern int config_errors; using namespace com::centreon; using namespace com::centreon::engine::configuration; -using namespace com::centreon::engine::logging; +using com::centreon::exceptions::msg_fmt; #define SETTER(type, method) &object::setter::generic @@ -122,7 +120,7 @@ static unsigned short const default_flap_detection_options(host::up | host::unreachable); static unsigned int const default_freshness_threshold(0); static unsigned int const default_high_flap_threshold(0); -static unsigned short const default_initial_state(engine::host::state_up); +static unsigned short const default_initial_state(broker::Host_State_UP); static unsigned int const default_low_flap_threshold(0); static unsigned int const default_max_check_attempts(3); static bool const default_notifications_enabled(true); @@ -434,10 +432,9 @@ bool host::operator<(host const& other) const noexcept { */ void host::check_validity() const { if (_host_name.empty()) - throw engine_error() << "Host has no name (property 'host_name')"; + throw msg_fmt("Host has no name (property 'host_name')"); if (_address.empty()) - throw engine_error() << "Host '" << _host_name - << "' has no address (property 'address')"; + throw msg_fmt("Host '{}' has no address (property 'address')", _host_name); } /** @@ -456,7 +453,8 @@ host::key_type host::key() const noexcept { */ void host::merge(object const& obj) { if (obj.type() != _type) - throw engine_error() << "Cannot merge host with '" << obj.type() << "'"; + throw msg_fmt("Cannot merge host with '{}'", + static_cast(obj.type())); host const& tmpl(static_cast(obj)); MRG_OPTION(_acknowledgement_timeout); @@ -1439,11 +1437,11 @@ bool host::_set_initial_state(std::string const& value) { std::string_view data(value); data = absl::StripAsciiWhitespace(data); if (data == "o" || data == "up") - _initial_state = engine::host::state_up; + _initial_state = broker::Host_State_UP; else if (data == "d" || data == "down") - _initial_state = engine::host::state_down; + _initial_state = broker::Host_State_DOWN; else if (data == "u" || data == "unreachable") - _initial_state = engine::host::state_unreachable; + _initial_state = broker::Host_State_UNREACHABLE; else return false; return true; @@ -1718,7 +1716,7 @@ bool host::_set_category_tags(const std::string& value) { for (std::set>::iterator it(_tags.begin()), end(_tags.end()); it != end;) { - if (it->second == tag::hostcategory) + if (it->second == broker::HOSTCATEGORY) it = _tags.erase(it); else ++it; @@ -1729,7 +1727,7 @@ bool host::_set_category_tags(const std::string& value) { bool parse_ok; parse_ok = absl::SimpleAtoi(tag, &id); if (parse_ok) { - _tags.emplace(id, tag::hostcategory); + _tags.emplace(id, broker::HOSTCATEGORY); } else { _logger->warn("Warning: host ({}) error for parsing tag {}", _host_id, value); @@ -1752,7 +1750,7 @@ bool host::_set_group_tags(const std::string& value) { for (std::set>::iterator it(_tags.begin()), end(_tags.end()); it != end;) { - if (it->second == tag::hostgroup) + if (it->second == broker::HOSTGROUP) it = _tags.erase(it); else ++it; @@ -1763,7 +1761,7 @@ bool host::_set_group_tags(const std::string& value) { bool parse_ok; parse_ok = absl::SimpleAtoi(tag, &id); if (parse_ok) { - _tags.emplace(id, tag::hostgroup); + _tags.emplace(id, broker::HOSTGROUP); } else { _logger->warn("Warning: host ({}) error for parsing tag {}", _host_id, value); diff --git a/engine/src/configuration/hostdependency.cc b/engine/src/configuration/hostdependency.cc index 251953ee007..5ccf7ddb8aa 100644 --- a/engine/src/configuration/hostdependency.cc +++ b/engine/src/configuration/hostdependency.cc @@ -19,16 +19,15 @@ */ #include "com/centreon/engine/configuration/hostdependency.hh" -#include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/logging/logger.hh" +#include "com/centreon/exceptions/msg_fmt.hh" extern int config_warnings; extern int config_errors; using namespace com::centreon; using namespace com::centreon::engine::configuration; -using namespace com::centreon::engine::logging; +using com::centreon::exceptions::msg_fmt; #define SETTER(type, method) \ &object::setter::generic @@ -184,15 +183,14 @@ bool hostdependency::operator<(hostdependency const& right) const { */ void hostdependency::check_validity() const { if (_hosts->empty() && _hostgroups->empty()) - throw(engine_error() << "Host dependency is not attached to any " - << "host or host group (properties 'host_name' or " - << "'hostgroup_name', respectively)"); + throw msg_fmt( + "Host dependency is not attached to any host or host group (properties " + "'host_name' or 'hostgroup_name', respectively)"); if (_dependent_hosts->empty() && _dependent_hostgroups->empty()) - throw(engine_error() - << "Host dependency is not attached to any " - << "dependent host or dependent host group (properties " - << "'dependent_host_name' or 'dependent_hostgroup_name', " - << "respectively)"); + throw msg_fmt( + "Host dependency is not attached to any dependent host or dependent " + "host group (properties 'dependent_host_name' or " + "'dependent_hostgroup_name', respectively)"); if (!_execution_failure_options && !_notification_failure_options) { ++config_warnings; @@ -224,8 +222,8 @@ hostdependency::key_type const& hostdependency::key() const noexcept { */ void hostdependency::merge(object const& obj) { if (obj.type() != _type) - throw(engine_error() << "Cannot merge host dependency with '" << obj.type() - << "'"); + throw msg_fmt("Cannot merge host dependency with '{}'", + static_cast(obj.type())); hostdependency const& tmpl(static_cast(obj)); MRG_DEFAULT(_dependency_period); diff --git a/engine/src/configuration/hostescalation.cc b/engine/src/configuration/hostescalation.cc index 0110f5e892d..8c9853c99b6 100644 --- a/engine/src/configuration/hostescalation.cc +++ b/engine/src/configuration/hostescalation.cc @@ -18,10 +18,11 @@ * */ #include "com/centreon/engine/configuration/hostescalation.hh" -#include "com/centreon/engine/exceptions/error.hh" +#include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon; using namespace com::centreon::engine::configuration; +using com::centreon::exceptions::msg_fmt; #define SETTER(type, method) \ &object::setter::generic @@ -163,9 +164,9 @@ bool hostescalation::operator<(hostescalation const& right) const { */ void hostescalation::check_validity() const { if (_hosts->empty() && _hostgroups->empty()) - throw(engine_error() << "Host escalation is not attached to any " - << "host or host group (properties 'host_name' or " - << "'hostgroup_name', respectively)"); + throw msg_fmt( + "Host escalation is not attached to any host or host group (properties " + "'host_name' or 'hostgroup_name', respectively)"); } /** @@ -184,8 +185,8 @@ hostescalation::key_type const& hostescalation::key() const throw() { */ void hostescalation::merge(object const& obj) { if (obj.type() != _type) - throw(engine_error() << "Cannot merge host escalation with '" << obj.type() - << "'"); + throw msg_fmt("Cannot merge host escalation with '{}'", + static_cast(obj.type())); hostescalation const& tmpl(static_cast(obj)); MRG_INHERIT(_contactgroups); diff --git a/engine/src/configuration/hostgroup.cc b/engine/src/configuration/hostgroup.cc index a9c66e163bd..b8ea44beccd 100644 --- a/engine/src/configuration/hostgroup.cc +++ b/engine/src/configuration/hostgroup.cc @@ -16,15 +16,12 @@ * For more information : contact@centreon.com * */ - #include "com/centreon/engine/configuration/hostgroup.hh" -#include "com/centreon/engine/exceptions/error.hh" -#include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/logging/logger.hh" +#include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon; using namespace com::centreon::engine::configuration; -using namespace com::centreon::engine::logging; +using com::centreon::exceptions::msg_fmt; #define SETTER(type, method) \ &object::setter::generic @@ -172,9 +169,7 @@ bool hostgroup::operator<(hostgroup const& right) const throw() { */ void hostgroup::check_validity() const { if (_hostgroup_name.empty()) - throw(engine_error() << "Host group has no name " - "(property 'hostgroup_name')"); - return; + throw msg_fmt("Host group has no name (property 'hostgroup_name')"); } /** @@ -193,8 +188,8 @@ hostgroup::key_type const& hostgroup::key() const throw() { */ void hostgroup::merge(object const& obj) { if (obj.type() != _type) - throw(engine_error() << "Cannot merge host group with '" << obj.type() - << "'"); + throw msg_fmt("Cannot merge host group with '{}'", + static_cast(obj.type())); hostgroup const& tmpl(static_cast(obj)); MRG_DEFAULT(_action_url); MRG_DEFAULT(_alias); diff --git a/engine/src/configuration/object.cc b/engine/src/configuration/object.cc index 5cdbd69694e..cecce38f068 100644 --- a/engine/src/configuration/object.cc +++ b/engine/src/configuration/object.cc @@ -34,12 +34,13 @@ #include "com/centreon/engine/configuration/severity.hh" #include "com/centreon/engine/configuration/tag.hh" #include "com/centreon/engine/configuration/timeperiod.hh" -#include "com/centreon/engine/exceptions/error.hh" +#include "com/centreon/exceptions/msg_fmt.hh" #include "common/log_v2/log_v2.hh" using namespace com::centreon; using namespace com::centreon::engine::configuration; using com::centreon::common::log_v2::log_v2; +using com::centreon::exceptions::msg_fmt; #define SETTER(type, method) \ &object::setter::generic @@ -217,7 +218,7 @@ void object::resolve_template(map_object& templates) { for (std::string& s : _templates) { map_object::iterator tmpl = templates.find(s); if (tmpl == templates.end()) - throw engine_error() << "Cannot merge object of type '" << s << "'"; + throw msg_fmt("Cannot merge object of type '{}'", s); tmpl->second->resolve_template(templates); merge(*tmpl->second); } diff --git a/engine/src/configuration/parser.cc b/engine/src/configuration/parser.cc index 29cd8f032ae..d893b3665e1 100644 --- a/engine/src/configuration/parser.cc +++ b/engine/src/configuration/parser.cc @@ -17,8 +17,8 @@ * */ #include "com/centreon/engine/configuration/parser.hh" -#include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" +#include "com/centreon/exceptions/msg_fmt.hh" #include "com/centreon/io/directory_entry.hh" #include "common/log_v2/log_v2.hh" @@ -26,6 +26,7 @@ using namespace com::centreon; using namespace com::centreon::engine::configuration; using namespace com::centreon::io; using com::centreon::common::log_v2::log_v2; +using com::centreon::exceptions::msg_fmt; parser::store parser::_store[] = { &parser::_store_into_map, @@ -140,7 +141,6 @@ void parser::parse(std::string const& path, state& config) { void parser::_add_object(object_ptr obj) { if (obj->should_register()) (this->*_store[obj->type()])(obj); - return; } /** @@ -151,15 +151,12 @@ void parser::_add_object(object_ptr obj) { void parser::_add_template(object_ptr obj) { std::string const& name(obj->name()); if (name.empty()) - throw engine_error() << "Parsing of " << obj->type_name() << " failed " - << _get_file_info(obj.get()) - << ": Property 'name' " - "is missing"; + throw msg_fmt("Parsing of {} failed {}: Property 'name' is missing", + obj->type_name(), _get_file_info(obj.get())); map_object& tmpl(_templates[obj->type()]); if (tmpl.find(name) != tmpl.end()) - throw engine_error() << "Parsing of " << obj->type_name() << " failed " - << _get_file_info(obj.get()) << ": " << name - << " already exists"; + throw msg_fmt("Parsing of {} failed {}: {} already exists", + obj->type_name(), _get_file_info(obj.get()), name); tmpl[name] = obj; } @@ -190,8 +187,8 @@ file_info const& parser::_get_file_info(object* obj) const { if (it != _objects_info.end()) return it->second; } - throw engine_error() << "Parsing failed: Object not " - "found into the file information cache"; + throw msg_fmt( + "Parsing failed: Object not found into the file information cache"); } /** @@ -255,7 +252,6 @@ void parser::_insert(list_object const& from, std::set& to) { for (list_object::const_iterator it(from.begin()), end(from.end()); it != end; ++it) to.insert(*static_cast(it->get())); - return; } /** @@ -269,7 +265,6 @@ void parser::_insert(map_object const& from, std::set& to) { for (map_object::const_iterator it(from.begin()), end(from.end()); it != end; ++it) to.insert(*static_cast(it->second.get())); - return; } /** @@ -311,9 +306,8 @@ void parser::_parse_global_configuration(const std::string& path) { std::ifstream stream(path.c_str(), std::ios::binary); if (!stream.is_open()) - throw engine_error() << "Parsing of global " - "configuration failed: Can't open file '" - << path << "'"; + throw msg_fmt( + "Parsing of global configuration failed: Can't open file '{}'", path); _config->cfg_main(path); @@ -332,9 +326,10 @@ void parser::_parse_global_configuration(const std::string& path) { if (_config->set(key, value)) continue; } - throw engine_error() << "Parsing of global configuration failed in file '" - << path << "' on line " << _current_line - << ": Invalid line '" << input << "'"; + throw msg_fmt( + "Parsing of global configuration failed in file '{}' on line {}: " + "Invalid line '{}'", + path, _current_line, input); } } @@ -348,8 +343,8 @@ void parser::_parse_object_definitions(std::string const& path) { std::ifstream stream(path, std::ios::binary); if (!stream.is_open()) - throw engine_error() << "Parsing of object definition failed: " - << "Can't open file '" << path << "'"; + throw msg_fmt("Parsing of object definition failed: Can't open file '{}'", + path); _current_line = 0; _current_path = path; @@ -370,25 +365,26 @@ void parser::_parse_object_definitions(std::string const& path) { // Check if is a valid object. if (obj == nullptr) { if (input.find("define") || !std::isspace(input[6])) - throw engine_error() - << "Parsing of object definition failed " - << "in file '" << _current_path << "' on line " << _current_line - << ": Unexpected start definition"; + throw msg_fmt( + "Parsing of object definition failed in file '{}' on line {}: " + "Unexpected start definition", + _current_path, _current_line); input.erase(0, 6); absl::StripLeadingAsciiWhitespace(&input); std::size_t last = input.size() - 1; if (input.empty() || input[last] != '{') - throw engine_error() - << "Parsing of object definition failed in file '" << _current_path - << "' on line " << _current_line << ": Unexpected start definition"; + throw msg_fmt( + "Parsing of object definition failed in file '{}' on line {}: " + "Unexpected start definition", + _current_path, _current_line); input.erase(last); absl::StripTrailingAsciiWhitespace(&input); obj = object::create(input); if (obj == nullptr) - throw engine_error() - << "Parsing of object definition failed " - << "in file '" << _current_path << "' on line " << _current_line - << ": Unknown object type name '" << input << "'"; + throw msg_fmt( + "Parsing of object definition failed in file '{}' on line {}: " + "Unknown object type name '{}'", + _current_path, _current_line, input); parse_object = (_read_options & (1 << obj->type())); _objects_info[obj.get()] = file_info(path, _current_line); } @@ -396,10 +392,10 @@ void parser::_parse_object_definitions(std::string const& path) { else if (input != "}") { if (parse_object) { if (!obj->parse(input)) - throw engine_error() - << "Parsing of object definition " - << "failed in file '" << _current_path << "' on line " - << _current_line << ": Invalid line '" << input << "'"; + throw msg_fmt( + "Parsing of object definition failed in file '{}' on line {}: " + "Invalid line '{}'", + _current_path, _current_line, input); } } // End of the current object. @@ -425,8 +421,8 @@ void parser::_parse_resource_file(std::string const& path) { std::ifstream stream(path.c_str(), std::ios::binary); if (!stream.is_open()) - throw engine_error() << "Parsing of resource file failed: " - << "can't open file '" << path << "'"; + throw msg_fmt("Parsing of resource file failed: can't open file '{}'", + path); _current_line = 0; _current_path = path; @@ -443,14 +439,15 @@ void parser::_parse_resource_file(std::string const& path) { std::string value = *it; _config->user(key, value); } else - throw engine_error() << "Parsing of resource file '" << _current_path - << "' failed on line " << _current_line - << ": Invalid line '" << input << "'"; + throw msg_fmt( + "Parsing of resource file '{}' failed on line {}: Invalid line " + "'{}'", + _current_path, _current_line, input); } catch (std::exception const& e) { (void)e; - throw engine_error() << "Parsing of resource file '" << _current_path - << "' failed on line " << _current_line - << ": Invalid line '" << input << "'"; + throw msg_fmt( + "Parsing of resource file '{}' failed on line {}: Invalid line '{}'", + _current_path, _current_line, input); } } } @@ -474,8 +471,8 @@ void parser::_resolve_template() { try { (*it)->check_validity(); } catch (std::exception const& e) { - throw engine_error() << "Configuration parsing failed " - << _get_file_info(it->get()) << ": " << e.what(); + throw msg_fmt("Configuration parsing failed {}: {}", + _get_file_info(it->get()), e.what()); } } } @@ -489,9 +486,8 @@ void parser::_resolve_template() { try { it->second->check_validity(); } catch (std::exception const& e) { - throw engine_error() - << "Configuration parsing failed " - << _get_file_info(it->second.get()) << ": " << e.what(); + throw msg_fmt("Configuration parsing failed {}: {}", + _get_file_info(it->second.get()), e.what()); } } } @@ -516,8 +512,7 @@ void parser::_store_into_map(object_ptr obj) { std::shared_ptr real(std::static_pointer_cast(obj)); map_object::iterator it(_map_objects[obj->type()].find((real.get()->*ptr)())); if (it != _map_objects[obj->type()].end()) - throw engine_error() << "Parsing of " << obj->type_name() << " failed " - << _get_file_info(obj.get()) << ": " << obj->name() - << " alrealdy exists"; + throw msg_fmt("Parsing of {} failed {}: {} already exists", + obj->type_name(), _get_file_info(obj.get()), obj->name()); _map_objects[obj->type()][(real.get()->*ptr)()] = real; } diff --git a/engine/src/configuration/service.cc b/engine/src/configuration/service.cc index 19fbe425fb3..916eddbae91 100644 --- a/engine/src/configuration/service.cc +++ b/engine/src/configuration/service.cc @@ -21,17 +21,16 @@ #include #include #include -#include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" #include "com/centreon/engine/host.hh" -#include "com/centreon/engine/logging/logger.hh" +#include "com/centreon/exceptions/msg_fmt.hh" extern int config_warnings; extern int config_errors; using namespace com::centreon; using namespace com::centreon::engine::configuration; -using namespace com::centreon::engine::logging; +using com::centreon::exceptions::msg_fmt; #define SETTER(type, method) \ &object::setter::generic @@ -574,7 +573,6 @@ bool service::operator!=(service const& other) const noexcept { * @return True if this object is less than right. */ bool service::operator<(service const& other) const noexcept { - // hosts and service_description have to be first in this operator. // The configuration diff mechanism relies on this. if (_host_id != other._host_id) return _host_id < other._host_id; @@ -680,16 +678,17 @@ bool service::operator<(service const& other) const noexcept { */ void service::check_validity() const { if (_service_description.empty()) - throw engine_error() << "Service has no description (property " - << "'service_description')"; + throw msg_fmt( + "Service has no description (property 'service_description')"); if (_host_name.empty()) - throw engine_error() - << "Service '" << _service_description - << "' is not attached to any host or host group (properties " - << "'host_name' or 'hostgroup_name', respectively)"; + throw msg_fmt( + "Service '{}' is not attached to any host or host group (properties " + "'host_name' or 'hostgroup_name', respectively)", + _service_description); if (_check_command.empty()) - throw engine_error() << "Service '" << _service_description - << "' has no check command (property 'check_command')"; + throw msg_fmt( + "Service '{}' has no check command (property 'check_command')", + _service_description); } /** @@ -709,7 +708,8 @@ service::key_type service::key() const { */ void service::merge(object const& obj) { if (obj.type() != _type) - throw(engine_error() << "Cannot merge service with '" << obj.type() << "'"); + throw msg_fmt("Cannot merge service with '{}'", + static_cast(obj.type())); service const& tmpl(static_cast(obj)); MRG_OPTION(_acknowledgement_timeout); diff --git a/engine/src/configuration/servicedependency.cc b/engine/src/configuration/servicedependency.cc index 411cb62c914..98f00491d1a 100644 --- a/engine/src/configuration/servicedependency.cc +++ b/engine/src/configuration/servicedependency.cc @@ -19,16 +19,15 @@ */ #include "com/centreon/engine/configuration/servicedependency.hh" -#include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/logging/logger.hh" +#include "com/centreon/exceptions/msg_fmt.hh" extern int config_warnings; extern int config_errors; using namespace com::centreon; using namespace com::centreon::engine::configuration; -using namespace com::centreon::engine::logging; +using com::centreon::exceptions::msg_fmt; namespace com::centreon::engine::configuration { size_t servicedependency_key(const servicedependency& sd) { @@ -235,31 +234,28 @@ void servicedependency::check_validity() const { // Check base service(s). if (_servicegroups->empty()) { if (_service_description->empty()) - throw(engine_error() << "Service dependency is not attached to " - << "any service or service group (properties " - << "'service_description' or 'servicegroup_name', " - << "respectively)"); + throw msg_fmt( + "Service dependency is not attached to any service or service group " + "(properties 'service_description' or 'servicegroup_name', " + "respectively)"); else if (_hosts->empty() && _hostgroups->empty()) - throw( - engine_error() << "Service dependency is not attached to " - << "any host or host group (properties 'host_name' or " - << "'hostgroup_name', respectively)"); + throw msg_fmt( + "Service dependency is not attached to any host or host group " + "(properties 'host_name' or 'hostgroup_name', respectively)"); } // Check dependent service(s). if (_dependent_servicegroups->empty()) { if (_dependent_service_description->empty()) - throw( - engine_error() << "Service dependency is not attached to " - << "any dependent service or dependent service group " - << "(properties 'dependent_service_description' or " - << "'dependent_servicegroup_name', respectively)"); + throw msg_fmt( + "Service dependency is not attached to any dependent service or " + "dependent service group (properties 'dependent_service_description' " + "or 'dependent_servicegroup_name', respectively)"); else if (_dependent_hosts->empty() && _dependent_hostgroups->empty()) - throw(engine_error() - << "Service dependency is not attached to " - << "any dependent host or dependent host group (properties " - << "'dependent_host_name' or 'dependent_hostgroup_name', " - << "respectively)"); + throw msg_fmt( + "Service dependency is not attached to any dependent host or " + "dependent host group (properties 'dependent_host_name' or " + "'dependent_hostgroup_name', respectively)"); } // With no execution or failure options this dependency is useless. @@ -306,8 +302,8 @@ servicedependency::key_type const& servicedependency::key() const throw() { */ void servicedependency::merge(object const& obj) { if (obj.type() != _type) - throw(engine_error() << "Cannot merge service dependency with '" - << obj.type() << "'"); + throw msg_fmt("Cannot merge service dependency with '{}'", + static_cast(obj.type())); servicedependency const& tmpl(static_cast(obj)); MRG_DEFAULT(_dependency_period); diff --git a/engine/src/configuration/serviceescalation.cc b/engine/src/configuration/serviceescalation.cc index 397fb3abcd8..4cf59dcb8f5 100644 --- a/engine/src/configuration/serviceescalation.cc +++ b/engine/src/configuration/serviceescalation.cc @@ -18,13 +18,12 @@ */ #include "com/centreon/engine/configuration/serviceescalation.hh" -#include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/logging/logger.hh" +#include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon; using namespace com::centreon::engine::configuration; -using namespace com::centreon::engine::logging; +using com::centreon::exceptions::msg_fmt; #define SETTER(type, method) \ &object::setter::generic @@ -242,15 +241,14 @@ bool serviceescalation::operator<(serviceescalation const& right) const { void serviceescalation::check_validity() const { if (_servicegroups->empty()) { if (_service_description->empty()) - throw(engine_error() << "Service escalation is not attached to " - << "any service or service group (properties " - << "'service_description' and 'servicegroup_name', " - << "respectively)"); + throw msg_fmt( + "Service escalation is not attached to any service or service group " + "(properties 'service_description' and 'servicegroup_name', " + "respectively)"); else if (_hosts->empty() && _hostgroups->empty()) - throw( - engine_error() << "Service escalation is not attached to " - << "any host or host group (properties 'host_name' or " - << "'hostgroup_name', respectively)"); + throw msg_fmt( + "Service escalation is not attached to any host or host group " + "(properties 'host_name' or 'hostgroup_name', respectively)"); } } @@ -270,8 +268,8 @@ serviceescalation::key_type const& serviceescalation::key() const noexcept { */ void serviceescalation::merge(object const& obj) { if (obj.type() != _type) - throw(engine_error() << "Cannot merge service escalation with '" - << obj.type() << "'"); + throw msg_fmt("Cannot merge service escalation with '{}'", + static_cast(obj.type())); serviceescalation const& tmpl(static_cast(obj)); MRG_INHERIT(_contactgroups); diff --git a/engine/src/configuration/servicegroup.cc b/engine/src/configuration/servicegroup.cc index 3855ff80897..c15dceb50bf 100644 --- a/engine/src/configuration/servicegroup.cc +++ b/engine/src/configuration/servicegroup.cc @@ -1,5 +1,5 @@ /** - * Copyright 2011-2013,2017 Centreon + * Copyright 2011-2013,2017-2024 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,10 +17,11 @@ * */ #include "com/centreon/engine/configuration/servicegroup.hh" -#include "com/centreon/engine/exceptions/error.hh" +#include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon; using namespace com::centreon::engine::configuration; +using com::centreon::exceptions::msg_fmt; #define SETTER(type, method) \ &object::setter::generic @@ -142,9 +143,7 @@ bool servicegroup::operator<(servicegroup const& right) const throw() { */ void servicegroup::check_validity() const { if (_servicegroup_name.empty()) - throw(engine_error() << "Service group has no name " - "(property 'servicegroup_name')"); - return; + throw msg_fmt("Service group has no name (property 'servicegroup_name')"); } /** @@ -163,8 +162,8 @@ servicegroup::key_type const& servicegroup::key() const throw() { */ void servicegroup::merge(object const& obj) { if (obj.type() != _type) - throw(engine_error() << "Cannot merge service group with '" << obj.type() - << "'"); + throw msg_fmt("Cannot merge service group with '{}'", + static_cast(obj.type())); servicegroup const& tmpl(static_cast(obj)); MRG_DEFAULT(_action_url); diff --git a/engine/src/configuration/severity.cc b/engine/src/configuration/severity.cc index e31a0eb5fce..3ec4ace32e5 100644 --- a/engine/src/configuration/severity.cc +++ b/engine/src/configuration/severity.cc @@ -1,5 +1,5 @@ /** - * Copyright 2022 Centreon (https://www.centreon.com/) + * Copyright 2022-2024 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,13 +16,13 @@ * For more information : contact@centreon.com * */ - #include "com/centreon/engine/configuration/severity.hh" -#include "com/centreon/engine/exceptions/error.hh" +#include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon; using namespace com::centreon::engine; using namespace com::centreon::engine::configuration; +using com::centreon::exceptions::msg_fmt; #define SETTER(type, method) \ &object::setter::generic @@ -131,15 +131,13 @@ bool severity::operator<(const severity& other) const noexcept { */ void severity::check_validity() const { if (_severity_name.empty()) - throw engine_error() << "Severity has no name (property 'severity_name')"; + throw msg_fmt("Severity has no name (property 'severity_name')"); if (_key.first == 0) - throw engine_error() - << "Severity id must not be less than 1 (property 'id')"; + throw msg_fmt("Severity id must not be less than 1 (property 'id')"); if (_level == 0) - throw engine_error() - << "Severity level must not be less than 1 (property 'level')"; + throw msg_fmt("Severity level must not be less than 1 (property 'level')"); if (_key.second == severity::none) - throw engine_error() << "Severity type must be one of 'service' or 'host'"; + throw msg_fmt("Severity type must be one of 'service' or 'host'"); } /** diff --git a/engine/src/configuration/state.cc b/engine/src/configuration/state.cc index 6d532eac453..47eb38de128 100644 --- a/engine/src/configuration/state.cc +++ b/engine/src/configuration/state.cc @@ -19,16 +19,16 @@ #include "com/centreon/engine/configuration/state.hh" #include "com/centreon/common/rapidjson_helper.hh" #include "com/centreon/engine/broker.hh" -#include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" +#include "com/centreon/exceptions/msg_fmt.hh" #include "com/centreon/io/file_entry.hh" #include "compatibility/locations.h" using namespace com::centreon; using namespace com::centreon::engine; using namespace com::centreon::engine::configuration; -using namespace com::centreon::engine::logging; using com::centreon::common::log_v2::log_v2; +using com::centreon::exceptions::msg_fmt; namespace com::centreon::engine::configuration::detail { template @@ -1128,7 +1128,7 @@ unsigned int state::auto_rescheduling_interval() const noexcept { */ void state::auto_rescheduling_interval(unsigned int value) { if (!value) - throw engine_error() << "auto_rescheduling_interval cannot be 0"; + throw msg_fmt("auto_rescheduling_interval cannot be 0"); _auto_rescheduling_interval = value; } @@ -1148,7 +1148,7 @@ unsigned int state::auto_rescheduling_window() const noexcept { */ void state::auto_rescheduling_window(unsigned int value) { if (!value) - throw engine_error() << "auto_rescheduling_window cannot be 0"; + throw msg_fmt("auto_rescheduling_window cannot be 0"); _auto_rescheduling_window = value; } @@ -1354,7 +1354,7 @@ unsigned int state::check_reaper_interval() const noexcept { */ void state::check_reaper_interval(unsigned int value) { if (!value) - throw engine_error() << "check_reaper_interval cannot be 0"; + throw msg_fmt("check_reaper_interval cannot be 0"); _check_reaper_interval = value; } @@ -1483,9 +1483,9 @@ int state::command_check_interval() const noexcept { */ void state::command_check_interval(int value) { if (value < -1 || !value) - throw engine_error() - << "command_check_interval must be either positive or -1 (" << value - << " provided)"; + throw msg_fmt( + "command_check_interval must be either positive or -1 ({} provided)", + value); _command_check_interval = value; @@ -1751,7 +1751,7 @@ int64_t state::debug_level() const noexcept { */ void state::debug_level(int64_t value) { if (value == -1) - _debug_level = all; + _debug_level = state::ALL; else _debug_level = value; } @@ -1771,8 +1771,8 @@ unsigned int state::debug_verbosity() const noexcept { * @param[in] value The new debug_verbosity value. */ void state::debug_verbosity(unsigned int value) { - if (value > most) - _debug_verbosity = static_cast(most); + if (value > state::MOST) + _debug_verbosity = static_cast(state::MOST); else _debug_verbosity = value; } @@ -1920,7 +1920,7 @@ unsigned int state::event_handler_timeout() const noexcept { */ void state::event_handler_timeout(unsigned int value) { if (!value) - throw engine_error() << "event_handler_timeout cannot be 0"; + throw msg_fmt("event_handler_timeout cannot be 0"); _event_handler_timeout = value; } @@ -2030,8 +2030,9 @@ float state::high_host_flap_threshold() const noexcept { */ void state::high_host_flap_threshold(float value) { if (value <= 0.0 || value >= 100.0) - throw engine_error() << "high_host_flap_threshold must " - << "be between 0.0 and 100.0, both excluded"; + throw msg_fmt( + "high_host_flap_threshold must be between 0.0 and 100.0, both " + "excluded"); _high_host_flap_threshold = value; } @@ -2051,8 +2052,9 @@ float state::high_service_flap_threshold() const noexcept { */ void state::high_service_flap_threshold(float value) { if (value <= 0.0 || value >= 100.0) - throw engine_error() << "high_service_flap_threshold " - << "must be between 0.0 and 100.0, both excluded"; + throw msg_fmt( + "high_service_flap_threshold must be between 0.0 and 100.0, both " + "excluded"); _high_service_flap_threshold = value; } @@ -2224,7 +2226,7 @@ unsigned int state::host_check_timeout() const noexcept { */ void state::host_check_timeout(unsigned int value) { if (!value) - throw engine_error() << "host_check_timeout cannot be 0"; + throw msg_fmt("host_check_timeout cannot be 0"); _host_check_timeout = value; } @@ -2425,7 +2427,7 @@ unsigned int state::interval_length() const noexcept { */ void state::interval_length(unsigned int value) { if (!value) - throw engine_error() << "interval_length cannot be 0"; + throw msg_fmt("interval_length cannot be 0"); if (!_command_check_interval_is_seconds && _command_check_interval != -1) { _command_check_interval /= _interval_length; @@ -2604,8 +2606,9 @@ float state::low_host_flap_threshold() const noexcept { */ void state::low_host_flap_threshold(float value) { if (value <= 0.0 || value >= 100.0) - throw engine_error() << "low_host_flap_threshold " - << "must be between 0.0 and 100.0, both excluded"; + throw msg_fmt( + "low_host_flap_threshold " + "must be between 0.0 and 100.0, both excluded"); _low_host_flap_threshold = value; } @@ -2625,8 +2628,9 @@ float state::low_service_flap_threshold() const noexcept { */ void state::low_service_flap_threshold(float value) { if (value <= 0.0 || value >= 100.0) - throw engine_error() << "low_service_flap_threshold " - << "must be between 0.0 and 100.0, both excluded"; + throw msg_fmt( + "low_service_flap_threshold must be between 0.0 and 100.0, both " + "excluded"); _low_service_flap_threshold = value; } @@ -2664,7 +2668,7 @@ unsigned int state::max_host_check_spread() const noexcept { */ void state::max_host_check_spread(unsigned int value) { if (!value) - throw engine_error() << "max_host_check_spread cannot be 0"; + throw msg_fmt("max_host_check_spread cannot be 0"); _max_host_check_spread = value; } @@ -2738,7 +2742,7 @@ unsigned int state::max_service_check_spread() const noexcept { */ void state::max_service_check_spread(unsigned int value) { if (!value) - throw engine_error() << "max_service_check_spread cannot be 0"; + throw msg_fmt("max_service_check_spread cannot be 0"); _max_service_check_spread = value; } @@ -2758,7 +2762,7 @@ unsigned int state::notification_timeout() const noexcept { */ void state::notification_timeout(unsigned int value) { if (!value) - throw engine_error() << "notification_timeout cannot be 0"; + throw msg_fmt("notification_timeout cannot be 0"); _notification_timeout = value; } @@ -2832,7 +2836,7 @@ unsigned int state::ochp_timeout() const noexcept { */ void state::ochp_timeout(unsigned int value) { if (!value) - throw engine_error() << "ochp_timeout cannot be 0"; + throw msg_fmt("ochp_timeout cannot be 0"); _ochp_timeout = value; } @@ -2870,7 +2874,7 @@ unsigned int state::ocsp_timeout() const noexcept { */ void state::ocsp_timeout(unsigned int value) { if (!value) - throw engine_error() << "ocsp_timeout cannot be 0"; + throw msg_fmt("ocsp_timeout cannot be 0"); _ocsp_timeout = value; } @@ -3106,7 +3110,7 @@ unsigned int state::retention_scheduling_horizon() const noexcept { */ void state::retention_scheduling_horizon(unsigned int value) { if (!value) - throw engine_error() << "retention_scheduling_horizon cannot be 0"; + throw msg_fmt("retention_scheduling_horizon cannot be 0"); _retention_scheduling_horizon = value; } @@ -3126,7 +3130,7 @@ unsigned int state::retention_update_interval() const noexcept { */ void state::retention_update_interval(unsigned int value) { if (!value) - throw engine_error() << "retention_update_interval cannot be 0"; + throw msg_fmt("retention_update_interval cannot be 0"); _retention_update_interval = value; } @@ -3368,7 +3372,7 @@ unsigned int state::service_check_timeout() const noexcept { */ void state::service_check_timeout(unsigned int value) { if (!value) - throw engine_error() << "service_check_timeout cannot be 0"; + throw msg_fmt("service_check_timeout cannot be 0"); _service_check_timeout = value; } @@ -3388,7 +3392,7 @@ unsigned int state::service_freshness_check_interval() const noexcept { */ void state::service_freshness_check_interval(unsigned int value) { if (!value) - throw engine_error() << "service_freshness_check_interval cannot be 0"; + throw msg_fmt("service_freshness_check_interval cannot be 0"); _service_freshness_check_interval = value; } @@ -3555,8 +3559,8 @@ float state::sleep_time() const noexcept { */ void state::sleep_time(float value) { if (value <= 0.0) - throw engine_error() << "sleep_time cannot be less or equal to 0 (" << value - << " provided)"; + throw msg_fmt("sleep_time cannot be less or equal to 0 ({} provided)", + value); _sleep_time = value; } @@ -3636,8 +3640,8 @@ unsigned int state::status_update_interval() const noexcept { */ void state::status_update_interval(unsigned int value) { if (value < 2) - throw engine_error() << "status_update_interval cannot be less than 2 (" - << value << " provided)"; + throw msg_fmt("status_update_interval cannot be less than 2 ({} provided)", + value); _status_update_interval = value; } @@ -3654,7 +3658,7 @@ bool state::set(char const* key, char const* value) { auto it = _setters.find(std::string_view(key)); if (it != _setters.end()) return (it->second)->apply_from_cfg(*this, value); - } catch (std::exception const& e) { + } catch (const std::exception& e) { _logger->error(e.what()); return false; } @@ -3733,8 +3737,8 @@ unsigned int state::time_change_threshold() const noexcept { */ void state::time_change_threshold(unsigned int value) { if (value < 6) - throw engine_error() << "time_change_threshold cannot be less than 6 (" - << value << " provided)"; + throw msg_fmt("time_change_threshold cannot be less than 6 ({} provided)", + value); _time_change_threshold = value; } @@ -3765,7 +3769,7 @@ void state::user(std::unordered_map const& value) { */ void state::user(const std::string& key, std::string const& value) { if (key.size() < 3 || key[0] != '$' || key[key.size() - 1] != '$') - throw engine_error() << "Invalid user key '" << key << "'"; + throw msg_fmt("Invalid user key '{}'", key); std::string new_key = key; new_key.erase(new_key.begin(), new_key.begin() + 1); new_key.erase(new_key.end() - 1, new_key.end()); @@ -3975,7 +3979,7 @@ const std::string& state::log_v2_logger() const noexcept { */ void state::log_v2_logger(const std::string& value) { if (value.empty()) - throw engine_error() << "log_v2_logger cannot be empty"; + throw msg_fmt("log_v2_logger cannot be empty"); _log_v2_logger = value; } @@ -3997,7 +4001,7 @@ void state::log_level_functions(const std::string& value) { if (log_v2::instance().contains_level(value)) _log_level_functions = value; else - throw engine_error() << "error wrong level setted for log_level_functions"; + throw msg_fmt("error wrong level setted for log_level_functions"); } /** @@ -4018,7 +4022,7 @@ void state::log_level_config(const std::string& value) { if (log_v2::instance().contains_level(value)) _log_level_config = value; else - throw engine_error() << "error wrong level setted for log_level_config"; + throw msg_fmt("error wrong level setted for log_level_config"); } /** @@ -4039,7 +4043,7 @@ void state::log_level_events(const std::string& value) { if (log_v2::instance().contains_level(value)) _log_level_events = value; else - throw engine_error() << "error wrong level setted for log_level_events"; + throw msg_fmt("error wrong level setted for log_level_events"); } /** @@ -4060,7 +4064,7 @@ void state::log_level_checks(const std::string& value) { if (log_v2::instance().contains_level(value)) _log_level_checks = value; else - throw engine_error() << "error wrong level setted for log_level_checks"; + throw msg_fmt("error wrong level setted for log_level_checks"); } /** @@ -4081,8 +4085,7 @@ void state::log_level_notifications(const std::string& value) { if (log_v2::instance().contains_level(value)) _log_level_notifications = value; else - throw engine_error() - << "error wrong level setted for log_level_notifications"; + throw msg_fmt("error wrong level setted for log_level_notifications"); } /** @@ -4103,8 +4106,7 @@ void state::log_level_eventbroker(const std::string& value) { if (log_v2::instance().contains_level(value)) _log_level_eventbroker = value; else - throw engine_error() - << "error wrong level setted for log_level_eventbroker"; + throw msg_fmt("error wrong level setted for log_level_eventbroker"); } /** @@ -4125,8 +4127,7 @@ void state::log_level_external_command(const std::string& value) { if (log_v2::instance().contains_level(value)) _log_level_external_command = value; else - throw engine_error() - << "error wrong level setted for log_level_external_command"; + throw msg_fmt("error wrong level setted for log_level_external_command"); } /** @@ -4147,7 +4148,7 @@ void state::log_level_commands(const std::string& value) { if (log_v2::instance().contains_level(value)) _log_level_commands = value; else - throw engine_error() << "error wrong level setted for log_level_commands"; + throw msg_fmt("error wrong level setted for log_level_commands"); } /** @@ -4168,7 +4169,7 @@ void state::log_level_downtimes(const std::string& value) { if (log_v2::instance().contains_level(value)) _log_level_downtimes = value; else - throw engine_error() << "error wrong level setted for log_level_downtimes"; + throw msg_fmt("error wrong level setted for log_level_downtimes"); } /** @@ -4189,7 +4190,7 @@ void state::log_level_comments(const std::string& value) { if (log_v2::instance().contains_level(value)) _log_level_comments = value; else - throw engine_error() << "error wrong level setted for log_level_comments"; + throw msg_fmt("error wrong level setted for log_level_comments"); } /** @@ -4210,7 +4211,7 @@ void state::log_level_macros(const std::string& value) { if (log_v2::instance().contains_level(value)) _log_level_macros = value; else - throw engine_error() << "error wrong level setted for log_level_macros"; + throw msg_fmt("error wrong level setted for log_level_macros"); } /** @@ -4231,7 +4232,7 @@ void state::log_level_process(const std::string& value) { if (log_v2::instance().contains_level(value)) _log_level_process = value; else - throw engine_error() << "error wrong level setted for log_level_process"; + throw msg_fmt("error wrong level setted for log_level_process"); } /** @@ -4252,7 +4253,7 @@ void state::log_level_runtime(const std::string& value) { if (log_v2::instance().contains_level(value)) _log_level_runtime = value; else - throw engine_error() << "error wrong level setted for log_level_runtime"; + throw msg_fmt("error wrong level setted for log_level_runtime"); } /** @@ -4273,7 +4274,7 @@ void state::log_level_otl(const std::string& value) { if (log_v2::instance().contains_level(value)) _log_level_otl = value; else - throw engine_error() << "error wrong level setted for log_level_otl"; + throw msg_fmt("error wrong level setted for log_level_otl"); } /** @@ -4487,7 +4488,6 @@ void state::_set_enable_failure_prediction(const std::string& value [[maybe_unused]]) { _logger->warn("Warning: enable_failure_prediction variable ignored"); ++config_warnings; - return; } /** @@ -4531,10 +4531,11 @@ void state::_set_host_inter_check_delay_method(const std::string& value) { _host_inter_check_delay_method = icd_user; if (!absl::SimpleAtod(value, &scheduling_info.host_inter_check_delay) || scheduling_info.host_inter_check_delay <= 0.0) - throw engine_error() - << "Invalid value for host_inter_check_delay_method, must " - << "be one of 'n' (none), 'd' (dumb), 's' (smart) or a " - << "stricly positive value (" << value << " provided)"; + throw msg_fmt( + "Invalid value for host_inter_check_delay_method, must be one of 'n' " + "(none), 'd' (dumb), 's' (smart) or a stricly positive value ({} " + "provided)", + value); } } @@ -4580,7 +4581,6 @@ void state::_set_log_archive_path(const std::string& value [[maybe_unused]]) { void state::_set_log_initial_states(const std::string& value [[maybe_unused]]) { _logger->warn("Warning: log_initial_states variable ignored"); ++config_warnings; - return; } /** @@ -4700,10 +4700,11 @@ void state::_set_service_inter_check_delay_method(const std::string& value) { _service_inter_check_delay_method = icd_user; if (!absl::SimpleAtod(value, &scheduling_info.service_inter_check_delay) || scheduling_info.service_inter_check_delay <= 0.0) - throw engine_error() - << "Invalid value for service_inter_check_delay_method, " - << "must be one of 'n' (none), 'd' (dumb), 's' (smart) or " - << "a strictly positive value (" << value << " provided)"; + throw msg_fmt( + "Invalid value for service_inter_check_delay_method, must be one of " + "'n' (none), 'd' (dumb), 's' (smart) or a strictly positive value " + "({} provided)", + value); } } diff --git a/engine/src/configuration/tag.cc b/engine/src/configuration/tag.cc index b1698531410..c25b2a53194 100644 --- a/engine/src/configuration/tag.cc +++ b/engine/src/configuration/tag.cc @@ -1,5 +1,5 @@ /** - * Copyright 2022 Centreon (https://www.centreon.com/) + * Copyright 2022-2024 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,13 +16,13 @@ * For more information : contact@centreon.com * */ - #include "com/centreon/engine/configuration/tag.hh" -#include "com/centreon/engine/exceptions/error.hh" +#include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon; using namespace com::centreon::engine; using namespace com::centreon::engine::configuration; +using com::centreon::exceptions::msg_fmt; #define SETTER(type, method) &object::setter::generic @@ -112,11 +112,11 @@ bool tag::operator<(const tag& other) const noexcept { */ void tag::check_validity() const { if (_tag_name.empty()) - throw engine_error() << "Tag has no name (property 'tag_name')"; + throw msg_fmt("Tag has no name (property 'tag_name')"); if (_key.first == 0) - throw engine_error() << "Tag id must not be less than 1 (property 'id')"; + throw msg_fmt("Tag id must not be less than 1 (property 'id')"); if (_key.second == static_cast(-1)) - throw engine_error() << "Tag type must be defined (property 'type')"; + throw msg_fmt("Tag type must be defined (property 'type')"); } /** diff --git a/engine/src/configuration/timeperiod.cc b/engine/src/configuration/timeperiod.cc index 8f8899afdf3..9b6afdb1f65 100644 --- a/engine/src/configuration/timeperiod.cc +++ b/engine/src/configuration/timeperiod.cc @@ -19,13 +19,13 @@ */ #include "com/centreon/engine/configuration/timeperiod.hh" -#include "com/centreon/engine/common.hh" -#include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/timerange.hh" +#include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon; using namespace com::centreon::engine; using namespace com::centreon::engine::configuration; +using com::centreon::exceptions::msg_fmt; #define SETTER(type, method) \ &object::setter::generic @@ -128,9 +128,7 @@ bool timeperiod::operator<(timeperiod const& right) const { */ void timeperiod::check_validity() const { if (_timeperiod_name.empty()) - throw(engine_error() - << "Time period has no name (property 'timeperiod_name')"); - return; + throw msg_fmt("Time period has no name (property 'timeperiod_name')"); } /** @@ -149,8 +147,8 @@ timeperiod::key_type const& timeperiod::key() const noexcept { */ void timeperiod::merge(object const& obj) { if (obj.type() != _type) - throw(engine_error() << "Cannot merge time period with '" << obj.type() - << "'"); + throw msg_fmt("Cannot merge time period with '{}'", + static_cast(obj.type())); timeperiod const& tmpl(static_cast(obj)); MRG_DEFAULT(_alias); diff --git a/engine/src/events/sched_info.cc b/engine/src/events/sched_info.cc index 34275aebf0f..69701f6ca24 100644 --- a/engine/src/events/sched_info.cc +++ b/engine/src/events/sched_info.cc @@ -190,8 +190,6 @@ void display_scheduling_info() { if (suggestions == 0) { std::cout << "I have no suggestions - things look okay.\n"; } - - return; } /** diff --git a/engine/src/hostescalation.cc b/engine/src/hostescalation.cc index ae35f3f81b4..5d0e4bba3ce 100644 --- a/engine/src/hostescalation.cc +++ b/engine/src/hostescalation.cc @@ -127,6 +127,15 @@ void hostescalation::resolve(int& w, int& e) { } } +/** + * @brief Checks that this hostescalation corresponds to the Configuration + * object obj. This function doesn't check contactgroups as it is usually used + * to modify them. + * + * @param obj A host escalation configuration object. + * + * @return A boolean that is True if they match. + */ bool hostescalation::matches(const configuration::hostescalation& obj) const { uint32_t escalate_on = ((obj.escalation_options() & configuration::hostescalation::down) diff --git a/engine/src/retention/dump.cc b/engine/src/retention/dump.cc index 5e8962e3917..cc129497c71 100644 --- a/engine/src/retention/dump.cc +++ b/engine/src/retention/dump.cc @@ -29,6 +29,7 @@ #include "com/centreon/engine/downtimes/service_downtime.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" +#include "com/centreon/engine/logging/logger.hh" using namespace com::centreon::engine; using namespace com::centreon::engine::configuration::applier; diff --git a/engine/src/serviceescalation.cc b/engine/src/serviceescalation.cc index 796177a022a..41db8011492 100644 --- a/engine/src/serviceescalation.cc +++ b/engine/src/serviceescalation.cc @@ -124,6 +124,15 @@ void serviceescalation::resolve(int& w, int& e) { } } +/** + * @brief Checks that this serviceescalation corresponds to the Configuration + * object obj. This function doesn't check contactgroups as it is usually used + * to modify them. + * + * @param obj A service escalation configuration object. + * + * @return A boolean that is True if they match. + */ bool serviceescalation::matches( const configuration::serviceescalation& obj) const { uint32_t escalate_on = diff --git a/engine/tests/configuration/applier/applier-service.cc b/engine/tests/configuration/applier/applier-service.cc index a77d25e71e0..1f5b0d20a6f 100644 --- a/engine/tests/configuration/applier/applier-service.cc +++ b/engine/tests/configuration/applier/applier-service.cc @@ -32,6 +32,7 @@ #include "com/centreon/engine/contact.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/host.hh" +#include "com/centreon/exceptions/msg_fmt.hh" #include "helper.hh" using namespace com::centreon; @@ -269,18 +270,18 @@ TEST_F(ApplierService, ServicesCheckValidity) { configuration::service csvc; // No service description - ASSERT_THROW(csvc.check_validity(), engine::exceptions::error); + ASSERT_THROW(csvc.check_validity(), com::centreon::exceptions::msg_fmt); ASSERT_TRUE(csvc.parse("service_description", "check description")); ASSERT_TRUE(csvc.parse("service_id", "53")); // No host attached to - ASSERT_THROW(csvc.check_validity(), engine::exceptions::error); + ASSERT_THROW(csvc.check_validity(), com::centreon::exceptions::msg_fmt); ASSERT_TRUE(csvc.parse("hosts", "test_host")); // No check command attached to - ASSERT_THROW(csvc.check_validity(), engine::exceptions::error); + ASSERT_THROW(csvc.check_validity(), com::centreon::exceptions::msg_fmt); configuration::applier::command cmd_aply; configuration::command cmd("cmd"); @@ -765,7 +766,7 @@ TEST_F(ApplierService, ServicesCheckValidityTags) { configuration::service csvc; // No service description - ASSERT_THROW(csvc.check_validity(), engine::exceptions::error); + ASSERT_THROW(csvc.check_validity(), com::centreon::exceptions::msg_fmt); ASSERT_TRUE(csvc.parse("service_description", "check description")); ASSERT_TRUE(csvc.parse("service_id", "53")); @@ -773,12 +774,12 @@ TEST_F(ApplierService, ServicesCheckValidityTags) { ASSERT_TRUE(csvc.parse("category_tags", "3")); // No host attached to - ASSERT_THROW(csvc.check_validity(), engine::exceptions::error); + ASSERT_THROW(csvc.check_validity(), com::centreon::exceptions::msg_fmt); ASSERT_TRUE(csvc.parse("hosts", "test_host")); // No check command attached to - ASSERT_THROW(csvc.check_validity(), engine::exceptions::error); + ASSERT_THROW(csvc.check_validity(), com::centreon::exceptions::msg_fmt); configuration::applier::command cmd_aply; configuration::command cmd("cmd"); diff --git a/engine/tests/configuration/contact.cc b/engine/tests/configuration/contact.cc index 6c1cc81c527..8a3bfea06cf 100644 --- a/engine/tests/configuration/contact.cc +++ b/engine/tests/configuration/contact.cc @@ -1,5 +1,5 @@ /** - * Copyright 2017 - 2019 Centreon (https://www.centreon.com/) + * Copyright 2017 - 2024 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,6 @@ * For more information : contact@centreon.com * */ - #include "com/centreon/engine/configuration/contact.hh" #include From 40b54ceabc424af157086e735e3981dac323db59 Mon Sep 17 00:00:00 2001 From: tuntoja <58987095+tuntoja@users.noreply.github.com> Date: Tue, 18 Jun 2024 11:40:14 +0200 Subject: [PATCH 45/60] enh(release-trigger): add option to trigger develop (#1449) --- .github/workflows/release-trigger-builds.yml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/workflows/release-trigger-builds.yml b/.github/workflows/release-trigger-builds.yml index 36189338315..0fbd70c5989 100644 --- a/.github/workflows/release-trigger-builds.yml +++ b/.github/workflows/release-trigger-builds.yml @@ -51,8 +51,9 @@ jobs: COMPONENTS_COLLECT_FULL=("Centreon collect") RUNS_URL="" - if [[ ${{ inputs.dispatch_target_release_branch }} =~ ^release-2[0-9]\.[0-9]+-next$ ]];then - echo "Using ${{ inputs.dispatch_target_release_branch }} as release branch to build testing packages." + # Accept release prefixed or develop branches, nothing else + if [[ ${{ inputs.dispatch_target_release_branch }} =~ ^release-2[0-9]\.[0-9]+-next$ ]] || [[ ${{ inputs.dispatch_target_release_branch }} == "develop" ]];then + echo "Using ${{ inputs.dispatch_target_release_branch }} as branch to build testing packages." RUNS_URL="https://github.com/centreon/centreon-collect/actions?query=branch%3A${{ inputs.dispatch_target_release_branch }}" else echo "::error::Invalid release branch name, please check the release branch name." From 835b04fb5efa027d73c0bb18d1a9be9e95baeea9 Mon Sep 17 00:00:00 2001 From: tuntoja <58987095+tuntoja@users.noreply.github.com> Date: Wed, 19 Jun 2024 09:09:15 +0200 Subject: [PATCH 46/60] fix(release): add release_id to data sent to JIRA release (#1450) --- .github/actions/release/action.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/actions/release/action.yml b/.github/actions/release/action.yml index 1fcb0b03a98..16454153e66 100644 --- a/.github/actions/release/action.yml +++ b/.github/actions/release/action.yml @@ -185,6 +185,7 @@ runs: JIRA_RELEASE_NAME="" JIRA_PROJECT_ID="${{ inputs.jira_project_id }}" JIRA_RELEASE_RELEASED="false" + JIRA_RELEASE_ID="$(git log |grep -E "^\s+Centreon.*#[0-9]{5,}#)" |grep -Eo "([0-9]{5,})" |head -n 1)" # Create JIRA version for each released component echo "Creating JIRA releases." @@ -194,7 +195,7 @@ runs: # Build JSON with release information for JIRA API JIRA_RELEASE_DATA=$(jq -nc \ --arg archived "$JIRA_RELEASE_ARCHIVED" \ - --arg description "$TAG" \ + --arg description "$JIRA_RELEASE_ID $TAG" \ --arg releaseDate "$JIRA_RELEASE_DATE" \ --arg name "$TAG" \ --arg projectId "$JIRA_PROJECT_ID" \ From 490f16a31447a8540c246d9c835fc5db9e5b0282 Mon Sep 17 00:00:00 2001 From: David Boucher Date: Wed, 19 Jun 2024 13:21:13 +0200 Subject: [PATCH 47/60] Mon 34072 move opt to common (#1451) * enh(engine/common): opt moved to common * cleanup(common): a comment added for opt REFS: MON-34072 --- broker/neb/CMakeLists.txt | 2 +- .../inc/com/centreon/common}/opt.hh | 16 ++++--- engine/CMakeLists.txt | 3 +- .../engine/configuration/anomalydetection.hh | 4 +- .../centreon/engine/configuration/contact.hh | 4 +- .../engine/configuration/contactgroup.hh | 2 +- .../com/centreon/engine/configuration/host.hh | 4 +- .../engine/configuration/hostdependency.hh | 4 +- .../engine/configuration/hostescalation.hh | 4 +- .../engine/configuration/hostgroup.hh | 2 +- .../centreon/engine/configuration/service.hh | 4 +- .../engine/configuration/servicedependency.hh | 4 +- .../engine/configuration/serviceescalation.hh | 4 +- .../engine/configuration/servicegroup.hh | 2 +- .../engine/configuration/timeperiod.hh | 2 +- .../com/centreon/engine/retention/contact.hh | 44 ++++++++++--------- .../inc/com/centreon/engine/retention/host.hh | 43 +++++++++--------- .../com/centreon/engine/retention/program.hh | 44 ++++++++++--------- .../com/centreon/engine/retention/service.hh | 43 +++++++++--------- engine/modules/CMakeLists.txt | 3 ++ .../modules/external_commands/CMakeLists.txt | 2 +- engine/src/host.cc | 4 +- engine/src/retention/anomalydetection.cc | 37 ++++++++-------- engine/src/retention/contact.cc | 37 ++++++++-------- engine/src/retention/host.cc | 26 +++++------ engine/src/retention/program.cc | 35 +++++++-------- engine/src/retention/service.cc | 26 +++++------ 27 files changed, 213 insertions(+), 192 deletions(-) rename {engine/inc/com/centreon/engine => common/inc/com/centreon/common}/opt.hh (86%) diff --git a/broker/neb/CMakeLists.txt b/broker/neb/CMakeLists.txt index 7e1836bf98d..50fa3d67cca 100644 --- a/broker/neb/CMakeLists.txt +++ b/broker/neb/CMakeLists.txt @@ -20,7 +20,7 @@ set(INC_DIR "${PROJECT_SOURCE_DIR}/neb/inc") set(SRC_DIR "${PROJECT_SOURCE_DIR}/neb/src") set(TEST_DIR "${PROJECT_SOURCE_DIR}/neb/test") -include_directories("${INC_DIR}") +include_directories("${INC_DIR}" ${CMAKE_SOURCE_DIR}/common/inc) # NEB sources. set(NEB_SOURCES diff --git a/engine/inc/com/centreon/engine/opt.hh b/common/inc/com/centreon/common/opt.hh similarity index 86% rename from engine/inc/com/centreon/engine/opt.hh rename to common/inc/com/centreon/common/opt.hh index e6504fafdb7..e2fe926a501 100644 --- a/engine/inc/com/centreon/engine/opt.hh +++ b/common/inc/com/centreon/common/opt.hh @@ -17,11 +17,17 @@ * For more information : contact@centreon.com * */ -#ifndef CCE_OPT_HH -#define CCE_OPT_HH +#ifndef CCC_OPT_HH +#define CCC_OPT_HH -namespace com::centreon::engine { +namespace com::centreon::common { +/** + * @brief This class is kept because already used in Engine. But please, do + * not use it anymore, prefer std::optional that plays almost the same role. + * + * @tparam T + */ template class opt { T _data; @@ -69,6 +75,6 @@ class opt { } }; -} // namespace com::centreon::engine +} // namespace com::centreon::common -#endif // !CCE_OPT_HH +#endif // !CCC_OPT_HH diff --git a/engine/CMakeLists.txt b/engine/CMakeLists.txt index 6b10ba0401a..0b9a62ebaaf 100644 --- a/engine/CMakeLists.txt +++ b/engine/CMakeLists.txt @@ -47,7 +47,7 @@ set(PRECOMP_HEADER "${PROJECT_SOURCE_DIR}/precomp_inc/precomp.hh") set(ENGINE_MODULES_DIR "${CMAKE_INSTALL_PREFIX}/lib64/centreon-engine/") -include_directories("${INC_DIR}" "${INC_DIR}/compatibility") +include_directories("${INC_DIR}" "${INC_DIR}/compatibility" "${CMAKE_SOURCE_DIR}/common/inc") link_directories(${CMAKE_SOURCE_DIR}/build/centreon-clib/) @@ -449,7 +449,6 @@ set(FILES "${INC_DIR}/com/centreon/engine/notification.hh" "${INC_DIR}/com/centreon/engine/notifier.hh" "${INC_DIR}/com/centreon/engine/objects.hh" - "${INC_DIR}/com/centreon/engine/opt.hh" "${INC_DIR}/com/centreon/engine/sehandlers.hh" "${INC_DIR}/com/centreon/engine/service.hh" "${INC_DIR}/com/centreon/engine/servicedependency.hh" diff --git a/engine/inc/com/centreon/engine/configuration/anomalydetection.hh b/engine/inc/com/centreon/engine/configuration/anomalydetection.hh index 52be0782d96..3c297fc5b36 100644 --- a/engine/inc/com/centreon/engine/configuration/anomalydetection.hh +++ b/engine/inc/com/centreon/engine/configuration/anomalydetection.hh @@ -20,10 +20,12 @@ #define CCE_CONFIGURATION_ANOMALYDETECTION_HH #include "bbdo/neb.pb.h" +#include "com/centreon/common/opt.hh" #include "com/centreon/engine/configuration/customvariable.hh" #include "com/centreon/engine/configuration/group.hh" #include "com/centreon/engine/configuration/object.hh" -#include "com/centreon/engine/opt.hh" + +using com::centreon::common::opt; namespace com::centreon::engine { diff --git a/engine/inc/com/centreon/engine/configuration/contact.hh b/engine/inc/com/centreon/engine/configuration/contact.hh index fc2651fb4b1..987dcdb2b77 100644 --- a/engine/inc/com/centreon/engine/configuration/contact.hh +++ b/engine/inc/com/centreon/engine/configuration/contact.hh @@ -21,10 +21,12 @@ #include +#include "com/centreon/common/opt.hh" #include "com/centreon/engine/configuration/customvariable.hh" #include "com/centreon/engine/configuration/group.hh" #include "com/centreon/engine/configuration/object.hh" -#include "com/centreon/engine/opt.hh" + +using com::centreon::common::opt; typedef std::vector tab_string; diff --git a/engine/inc/com/centreon/engine/configuration/contactgroup.hh b/engine/inc/com/centreon/engine/configuration/contactgroup.hh index ea3fdfd1f10..0eaae3987df 100644 --- a/engine/inc/com/centreon/engine/configuration/contactgroup.hh +++ b/engine/inc/com/centreon/engine/configuration/contactgroup.hh @@ -19,9 +19,9 @@ #ifndef CCE_CONFIGURATION_CONTACTGROUP_HH #define CCE_CONFIGURATION_CONTACTGROUP_HH +#include "com/centreon/common/opt.hh" #include "com/centreon/engine/configuration/group.hh" #include "com/centreon/engine/configuration/object.hh" -#include "com/centreon/engine/opt.hh" namespace com::centreon::engine::configuration { diff --git a/engine/inc/com/centreon/engine/configuration/host.hh b/engine/inc/com/centreon/engine/configuration/host.hh index 50efe049291..f91cfb8e844 100644 --- a/engine/inc/com/centreon/engine/configuration/host.hh +++ b/engine/inc/com/centreon/engine/configuration/host.hh @@ -19,12 +19,14 @@ #ifndef CCE_CONFIGURATION_HOST_HH #define CCE_CONFIGURATION_HOST_HH +#include "com/centreon/common/opt.hh" #include "com/centreon/engine/configuration/customvariable.hh" #include "com/centreon/engine/configuration/group.hh" #include "com/centreon/engine/configuration/object.hh" #include "com/centreon/engine/configuration/point_2d.hh" #include "com/centreon/engine/configuration/point_3d.hh" -#include "com/centreon/engine/opt.hh" + +using com::centreon::common::opt; namespace com::centreon::engine { diff --git a/engine/inc/com/centreon/engine/configuration/hostdependency.hh b/engine/inc/com/centreon/engine/configuration/hostdependency.hh index e3f3130bd82..1f708e47c94 100644 --- a/engine/inc/com/centreon/engine/configuration/hostdependency.hh +++ b/engine/inc/com/centreon/engine/configuration/hostdependency.hh @@ -19,9 +19,11 @@ #ifndef CCE_CONFIGURATION_HOSTDEPENDENCY_HH #define CCE_CONFIGURATION_HOSTDEPENDENCY_HH +#include "com/centreon/common/opt.hh" #include "com/centreon/engine/configuration/group.hh" #include "com/centreon/engine/configuration/object.hh" -#include "com/centreon/engine/opt.hh" + +using com::centreon::common::opt; namespace com::centreon::engine { diff --git a/engine/inc/com/centreon/engine/configuration/hostescalation.hh b/engine/inc/com/centreon/engine/configuration/hostescalation.hh index 9f6bb6f8e7c..87b6038e9bd 100644 --- a/engine/inc/com/centreon/engine/configuration/hostescalation.hh +++ b/engine/inc/com/centreon/engine/configuration/hostescalation.hh @@ -19,9 +19,11 @@ #ifndef CCE_CONFIGURATION_HOSTESCALATION_HH #define CCE_CONFIGURATION_HOSTESCALATION_HH +#include "com/centreon/common/opt.hh" #include "com/centreon/engine/configuration/group.hh" #include "com/centreon/engine/configuration/object.hh" -#include "com/centreon/engine/opt.hh" + +using com::centreon::common::opt; namespace com::centreon::engine { diff --git a/engine/inc/com/centreon/engine/configuration/hostgroup.hh b/engine/inc/com/centreon/engine/configuration/hostgroup.hh index 4fa758f48d2..e3d5bd538f3 100644 --- a/engine/inc/com/centreon/engine/configuration/hostgroup.hh +++ b/engine/inc/com/centreon/engine/configuration/hostgroup.hh @@ -19,9 +19,9 @@ #ifndef CCE_CONFIGURATION_HOSTGROUP_HH #define CCE_CONFIGURATION_HOSTGROUP_HH +#include "com/centreon/common/opt.hh" #include "com/centreon/engine/configuration/group.hh" #include "com/centreon/engine/configuration/object.hh" -#include "com/centreon/engine/opt.hh" namespace com::centreon::engine { diff --git a/engine/inc/com/centreon/engine/configuration/service.hh b/engine/inc/com/centreon/engine/configuration/service.hh index 135699e6144..90ff383f511 100644 --- a/engine/inc/com/centreon/engine/configuration/service.hh +++ b/engine/inc/com/centreon/engine/configuration/service.hh @@ -19,10 +19,12 @@ #ifndef CCE_CONFIGURATION_SERVICE_HH #define CCE_CONFIGURATION_SERVICE_HH +#include "com/centreon/common/opt.hh" #include "com/centreon/engine/configuration/customvariable.hh" #include "com/centreon/engine/configuration/group.hh" #include "com/centreon/engine/configuration/object.hh" -#include "com/centreon/engine/opt.hh" + +using com::centreon::common::opt; namespace com::centreon::engine::configuration { diff --git a/engine/inc/com/centreon/engine/configuration/servicedependency.hh b/engine/inc/com/centreon/engine/configuration/servicedependency.hh index aff57a849b4..61ea8f77c10 100644 --- a/engine/inc/com/centreon/engine/configuration/servicedependency.hh +++ b/engine/inc/com/centreon/engine/configuration/servicedependency.hh @@ -19,9 +19,11 @@ #ifndef CCE_CONFIGURATION_SERVICEDEPENDENCY_HH #define CCE_CONFIGURATION_SERVICEDEPENDENCY_HH +#include "com/centreon/common/opt.hh" #include "com/centreon/engine/configuration/group.hh" #include "com/centreon/engine/configuration/object.hh" -#include "com/centreon/engine/opt.hh" + +using com::centreon::common::opt; namespace com::centreon::engine { diff --git a/engine/inc/com/centreon/engine/configuration/serviceescalation.hh b/engine/inc/com/centreon/engine/configuration/serviceescalation.hh index b122c39315b..e093fce58e5 100644 --- a/engine/inc/com/centreon/engine/configuration/serviceescalation.hh +++ b/engine/inc/com/centreon/engine/configuration/serviceescalation.hh @@ -19,9 +19,11 @@ #ifndef CCE_CONFIGURATION_SERVICEESCALATION_HH #define CCE_CONFIGURATION_SERVICEESCALATION_HH +#include "com/centreon/common/opt.hh" #include "com/centreon/engine/configuration/group.hh" #include "com/centreon/engine/configuration/object.hh" -#include "com/centreon/engine/opt.hh" + +using com::centreon::common::opt; namespace com::centreon::engine::configuration { diff --git a/engine/inc/com/centreon/engine/configuration/servicegroup.hh b/engine/inc/com/centreon/engine/configuration/servicegroup.hh index db4c410aa61..879eacf999e 100644 --- a/engine/inc/com/centreon/engine/configuration/servicegroup.hh +++ b/engine/inc/com/centreon/engine/configuration/servicegroup.hh @@ -19,9 +19,9 @@ #ifndef CCE_CONFIGURATION_SERVICEGROUP_HH #define CCE_CONFIGURATION_SERVICEGROUP_HH +#include "com/centreon/common/opt.hh" #include "com/centreon/engine/configuration/group.hh" #include "com/centreon/engine/configuration/object.hh" -#include "com/centreon/engine/opt.hh" typedef std::set > set_pair_string; diff --git a/engine/inc/com/centreon/engine/configuration/timeperiod.hh b/engine/inc/com/centreon/engine/configuration/timeperiod.hh index 8b05a1e2535..7b09612bdf4 100644 --- a/engine/inc/com/centreon/engine/configuration/timeperiod.hh +++ b/engine/inc/com/centreon/engine/configuration/timeperiod.hh @@ -19,10 +19,10 @@ #ifndef CCE_CONFIGURATION_TIMEPERIOD_HH #define CCE_CONFIGURATION_TIMEPERIOD_HH +#include "com/centreon/common/opt.hh" #include "com/centreon/engine/configuration/group.hh" #include "com/centreon/engine/configuration/object.hh" #include "com/centreon/engine/daterange.hh" -#include "com/centreon/engine/opt.hh" namespace com::centreon::engine { diff --git a/engine/inc/com/centreon/engine/retention/contact.hh b/engine/inc/com/centreon/engine/retention/contact.hh index b0c42ca2b18..a419517da7a 100644 --- a/engine/inc/com/centreon/engine/retention/contact.hh +++ b/engine/inc/com/centreon/engine/retention/contact.hh @@ -1,29 +1,31 @@ -/* -** Copyright 2011-2013 Merethis -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2013 Merethis + * Copyright 2014-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCE_RETENTION_CONTACT_HH #define CCE_RETENTION_CONTACT_HH +#include "com/centreon/common/opt.hh" #include "com/centreon/engine/customvariable.hh" -#include "com/centreon/engine/opt.hh" #include "com/centreon/engine/retention/object.hh" +using com::centreon::common::opt; + namespace com::centreon::engine { namespace retention { @@ -84,6 +86,6 @@ typedef std::shared_ptr contact_ptr; typedef std::list list_contact; } // namespace retention -} +} // namespace com::centreon::engine #endif // !CCE_RETENTION_CONTACT_HH diff --git a/engine/inc/com/centreon/engine/retention/host.hh b/engine/inc/com/centreon/engine/retention/host.hh index d36470c7d7f..66efa85f9fa 100644 --- a/engine/inc/com/centreon/engine/retention/host.hh +++ b/engine/inc/com/centreon/engine/retention/host.hh @@ -1,29 +1,30 @@ -/* -** Copyright 2011-2013,2015-2016 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2013,2015-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCE_RETENTION_HOST_HH #define CCE_RETENTION_HOST_HH +#include "com/centreon/common/opt.hh" #include "com/centreon/engine/customvariable.hh" -#include "com/centreon/engine/opt.hh" #include "com/centreon/engine/retention/object.hh" +using com::centreon::common::opt; + namespace com::centreon::engine { namespace retention { @@ -227,6 +228,6 @@ typedef std::shared_ptr host_ptr; typedef std::list list_host; } // namespace retention -} +} // namespace com::centreon::engine #endif // !CCE_RETENTION_HOST_HH diff --git a/engine/inc/com/centreon/engine/retention/program.hh b/engine/inc/com/centreon/engine/retention/program.hh index 2b56cf0f14d..565345aa2d4 100644 --- a/engine/inc/com/centreon/engine/retention/program.hh +++ b/engine/inc/com/centreon/engine/retention/program.hh @@ -1,28 +1,30 @@ -/* -** Copyright 2011-2013,2015 Merethis -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2013,2015 Merethis + * Copyright 2016-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCE_RETENTION_PROGRAM_HH #define CCE_RETENTION_PROGRAM_HH -#include "com/centreon/engine/opt.hh" +#include "com/centreon/common/opt.hh" #include "com/centreon/engine/retention/object.hh" +using com::centreon::common::opt; + namespace com::centreon::engine { namespace retention { @@ -114,6 +116,6 @@ class program : public object { typedef std::shared_ptr program_ptr; } // namespace retention -} +} // namespace com::centreon::engine #endif // !CCE_RETENTION_PROGRAM_HH diff --git a/engine/inc/com/centreon/engine/retention/service.hh b/engine/inc/com/centreon/engine/retention/service.hh index 88c74ab4191..a7f59253b8c 100644 --- a/engine/inc/com/centreon/engine/retention/service.hh +++ b/engine/inc/com/centreon/engine/retention/service.hh @@ -1,29 +1,30 @@ -/* -** Copyright 2011-2013,2015-2016 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2013,2015-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCE_RETENTION_SERVICE_HH #define CCE_RETENTION_SERVICE_HH +#include "com/centreon/common/opt.hh" #include "com/centreon/engine/customvariable.hh" -#include "com/centreon/engine/opt.hh" #include "com/centreon/engine/retention/object.hh" +using com::centreon::common::opt; + namespace com::centreon::engine { namespace retention { @@ -241,6 +242,6 @@ typedef std::shared_ptr service_ptr; typedef std::list list_service; } // namespace retention -} +} // namespace com::centreon::engine #endif // !CCE_RETENTION_SERVICE_HH diff --git a/engine/modules/CMakeLists.txt b/engine/modules/CMakeLists.txt index fc4be6d17d5..6f6e0c8b3b7 100644 --- a/engine/modules/CMakeLists.txt +++ b/engine/modules/CMakeLists.txt @@ -18,6 +18,9 @@ # External commands module is required. add_subdirectory("external_commands") + +include_directories(${CMAKE_SOURCE_DIR}/clib/inc) + set(EXTERNALCMD_MODULE "${EXTERNALCMD_MODULE}" PARENT_SCOPE) diff --git a/engine/modules/external_commands/CMakeLists.txt b/engine/modules/external_commands/CMakeLists.txt index 2887e9fd75c..9a742cc7a53 100644 --- a/engine/modules/external_commands/CMakeLists.txt +++ b/engine/modules/external_commands/CMakeLists.txt @@ -23,7 +23,7 @@ set(SRC_DIR "${MODULE_DIR}/src") set(INC_DIR "${MODULE_DIR}/inc/com/centreon/engine/modules/external_commands") # Include directories. -include_directories("${MODULE_DIR}/inc") +include_directories(${MODULE_DIR}/inc ${CMAKE_SOURCE_DIR}/clib/inc) link_directories(${CMAKE_SOURCE_DIR}/build/centreon-clib/) # mod_externalcmd target. diff --git a/engine/src/host.cc b/engine/src/host.cc index 62508f113b9..802b4c85ceb 100644 --- a/engine/src/host.cc +++ b/engine/src/host.cc @@ -4105,8 +4105,6 @@ void host::_switch_all_services_to_unknown() { std::string output = fmt::format("host {} is down", name()); - time_t now = time(nullptr); - for (auto serv_iter = service::services_by_id.lower_bound({_id, 0}); serv_iter != service::services_by_id.end() && serv_iter->first.first == _id; @@ -4117,4 +4115,4 @@ void host::_switch_all_services_to_unknown() { service::state_unknown, output); checks::checker::instance().add_check_result_to_reap(result); } -} \ No newline at end of file +} diff --git a/engine/src/retention/anomalydetection.cc b/engine/src/retention/anomalydetection.cc index d2125f69946..eb32833d3e1 100644 --- a/engine/src/retention/anomalydetection.cc +++ b/engine/src/retention/anomalydetection.cc @@ -1,26 +1,25 @@ /** -* Copyright 2022 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ - + * Copyright 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include "com/centreon/engine/retention/anomalydetection.hh" +using com::centreon::common::opt; using com::centreon::engine::map_customvar; -using com::centreon::engine::opt; using namespace com::centreon::engine::retention; anomalydetection::anomalydetection() : service(object::anomalydetection) {} diff --git a/engine/src/retention/contact.cc b/engine/src/retention/contact.cc index 21ea2aa585a..3299137716d 100644 --- a/engine/src/retention/contact.cc +++ b/engine/src/retention/contact.cc @@ -1,24 +1,23 @@ /** -* Copyright 2011-2013 Merethis -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ - + * Copyright 2011-2013 Merethis + * Copyright 2014-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include "com/centreon/engine/retention/contact.hh" -#include "com/centreon/engine/string.hh" using namespace com::centreon::engine; using namespace com::centreon::engine::retention; diff --git a/engine/src/retention/host.cc b/engine/src/retention/host.cc index 231d69a4d12..874190bfb9e 100644 --- a/engine/src/retention/host.cc +++ b/engine/src/retention/host.cc @@ -1,22 +1,21 @@ /** - * Copyright 2011-2013,2016 Centreon + * Copyright 2011-2013,2016-2024 Centreon * - * This file is part of Centreon Engine. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Centreon Engine is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License version 2 - * as published by the Free Software Foundation. + * http://www.apache.org/licenses/LICENSE-2.0 * - * Centreon Engine is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com * - * You should have received a copy of the GNU General Public License - * along with Centreon Engine. If not, see - * . */ - #include "com/centreon/engine/retention/host.hh" #include "com/centreon/engine/common.hh" @@ -26,7 +25,6 @@ #include "com/centreon/engine/string.hh" using com::centreon::engine::map_customvar; -using com::centreon::engine::opt; using namespace com::centreon::engine::logging; using namespace com::centreon::engine::retention; diff --git a/engine/src/retention/program.cc b/engine/src/retention/program.cc index 5391fe5c5f4..6d571448095 100644 --- a/engine/src/retention/program.cc +++ b/engine/src/retention/program.cc @@ -1,22 +1,21 @@ /** -* Copyright 2011-2013,2015 Merethis -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ - + * Copyright 2011-2013,2015-2024 Merethis + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #include "com/centreon/engine/retention/program.hh" using namespace com::centreon::engine; diff --git a/engine/src/retention/service.cc b/engine/src/retention/service.cc index d8be0959b7c..dfd624430b8 100644 --- a/engine/src/retention/service.cc +++ b/engine/src/retention/service.cc @@ -1,22 +1,21 @@ /** - * Copyright 2011-2013,2015-2016 Centreon + * Copyright 2011-2013,2015-2024 Centreon * - * This file is part of Centreon Engine. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Centreon Engine is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License version 2 - * as published by the Free Software Foundation. + * http://www.apache.org/licenses/LICENSE-2.0 * - * Centreon Engine is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com * - * You should have received a copy of the GNU General Public License - * along with Centreon Engine. If not, see - * . */ - #include "com/centreon/engine/retention/service.hh" #include "com/centreon/engine/common.hh" @@ -26,7 +25,6 @@ #include "com/centreon/engine/string.hh" using com::centreon::engine::map_customvar; -using com::centreon::engine::opt; using namespace com::centreon::engine::logging; using namespace com::centreon::engine::retention; From 1c3e47ffb894f2d5dc0ec8e101f9b3e5a65cf048 Mon Sep 17 00:00:00 2001 From: tuntoja <58987095+tuntoja@users.noreply.github.com> Date: Thu, 20 Jun 2024 18:25:04 +0200 Subject: [PATCH 48/60] fix(release): fix checkout depth in release action (#1458) --- .github/actions/release/action.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/actions/release/action.yml b/.github/actions/release/action.yml index 16454153e66..74746c3b447 100644 --- a/.github/actions/release/action.yml +++ b/.github/actions/release/action.yml @@ -25,6 +25,8 @@ runs: steps: - name: Checkout sources uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + with: + fetch-depth: 0 - name: Get released versions for components run: | From 2e726ddc4d38203d51465f615ca470357e128f02 Mon Sep 17 00:00:00 2001 From: David Boucher Date: Mon, 24 Jun 2024 17:21:59 +0200 Subject: [PATCH 49/60] enh(engine/configuration): globals.hh removed from configuration files (#1465) * enh(engine/configuration): config_warnings and config_errors are removed as global variables. * enh(engine/configuration): almost all globals.hh used in configuration are removed * fix(engine/tests): little change in cfg files comments * cleanup(engine/configuration): headers removed when not needed * enh(collect): copyright info are updated automatically now. * fix(engine/configuration): scheduling configuration is fixed. * fix(engine): errors counts were badly propagated. * fix(engine): not needed headers removed * fix(engine): comments removed * fix(engine): fix after review on sched_info_config REFS: MON-34072 --- CMakeLists.txt | 3 + .../centreon/broker/config/applier/state.hh | 2 +- broker/core/src/main.cc | 4 +- .../com/centreon/engine/anomalydetection.hh | 39 +-- engine/inc/com/centreon/engine/config.hh | 41 ++- .../engine/configuration/anomalydetection.hh | 5 +- .../configuration/applier/anomalydetection.hh | 27 +- .../engine/configuration/applier/command.hh | 26 +- .../engine/configuration/applier/connector.hh | 28 +- .../engine/configuration/applier/contact.hh | 28 +- .../configuration/applier/contactgroup.hh | 28 +- .../engine/configuration/applier/host.hh | 43 ++- .../configuration/applier/hostdependency.hh | 4 +- .../configuration/applier/hostescalation.hh | 3 +- .../engine/configuration/applier/hostgroup.hh | 42 +-- .../engine/configuration/applier/service.hh | 42 +-- .../applier/servicedependency.hh | 5 +- .../applier/serviceescalation.hh | 41 +-- .../configuration/applier/servicegroup.hh | 42 +-- .../engine/configuration/applier/state.hh | 26 +- .../configuration/applier/timeperiod.hh | 3 +- .../centreon/engine/configuration/command.hh | 2 +- .../engine/configuration/connector.hh | 2 +- .../centreon/engine/configuration/contact.hh | 2 +- .../engine/configuration/contactgroup.hh | 2 +- .../com/centreon/engine/configuration/host.hh | 4 +- .../engine/configuration/hostdependency.hh | 2 +- .../engine/configuration/hostescalation.hh | 2 +- .../engine/configuration/hostgroup.hh | 2 +- .../centreon/engine/configuration/object.hh | 12 +- .../centreon/engine/configuration/parser.hh | 16 +- .../centreon/engine/configuration/service.hh | 5 +- .../engine/configuration/servicedependency.hh | 2 +- .../engine/configuration/serviceescalation.hh | 2 +- .../engine/configuration/servicegroup.hh | 2 +- .../centreon/engine/configuration/severity.hh | 2 +- .../centreon/engine/configuration/state.hh | 31 +- .../com/centreon/engine/configuration/tag.hh | 2 +- .../engine/configuration/timeperiod.hh | 2 +- .../engine/configuration/whitelist.hh | 1 - engine/inc/com/centreon/engine/contact.hh | 7 +- .../inc/com/centreon/engine/contactgroup.hh | 43 ++- engine/inc/com/centreon/engine/escalation.hh | 2 +- engine/inc/com/centreon/engine/globals.hh | 44 ++- engine/inc/com/centreon/engine/host.hh | 2 +- .../inc/com/centreon/engine/hostdependency.hh | 2 +- .../inc/com/centreon/engine/hostescalation.hh | 2 +- engine/inc/com/centreon/engine/hostgroup.hh | 41 ++- .../inc/com/centreon/engine/macros/defines.hh | 4 - engine/inc/com/centreon/engine/notifier.hh | 4 +- .../retention/applier/anomalydetection.hh | 39 +-- .../com/centreon/engine/retention/program.hh | 1 - engine/inc/com/centreon/engine/service.hh | 2 +- .../com/centreon/engine/servicedependency.hh | 2 +- .../com/centreon/engine/serviceescalation.hh | 2 +- .../inc/com/centreon/engine/servicegroup.hh | 44 +-- engine/inc/com/centreon/engine/timeperiod.hh | 42 +-- engine/inc/com/centreon/engine/xpddefault.hh | 2 - engine/src/anomalydetection.cc | 2 +- engine/src/config.cc | 8 +- engine/src/configuration/anomalydetection.cc | 59 +--- .../configuration/applier/anomalydetection.cc | 5 +- engine/src/configuration/applier/command.cc | 3 +- engine/src/configuration/applier/connector.cc | 3 +- engine/src/configuration/applier/contact.cc | 9 +- .../src/configuration/applier/contactgroup.cc | 5 +- engine/src/configuration/applier/host.cc | 5 +- .../configuration/applier/hostdependency.cc | 5 +- .../configuration/applier/hostescalation.cc | 5 +- engine/src/configuration/applier/hostgroup.cc | 5 +- engine/src/configuration/applier/scheduler.cc | 16 +- engine/src/configuration/applier/service.cc | 6 +- .../applier/servicedependency.cc | 5 +- .../applier/serviceescalation.cc | 5 +- .../src/configuration/applier/servicegroup.cc | 5 +- engine/src/configuration/applier/state.cc | 206 +++++------ .../src/configuration/applier/timeperiod.cc | 5 +- engine/src/configuration/command.cc | 2 +- engine/src/configuration/connector.cc | 2 +- engine/src/configuration/contact.cc | 2 +- engine/src/configuration/contactgroup.cc | 2 +- engine/src/configuration/extended_conf.cc | 1 - engine/src/configuration/host.cc | 40 +-- engine/src/configuration/hostdependency.cc | 10 +- engine/src/configuration/hostescalation.cc | 2 +- engine/src/configuration/hostgroup.cc | 2 +- engine/src/configuration/parser.cc | 11 +- engine/src/configuration/service.cc | 59 +--- engine/src/configuration/servicedependency.cc | 8 +- engine/src/configuration/serviceescalation.cc | 3 +- engine/src/configuration/servicegroup.cc | 2 +- engine/src/configuration/severity.cc | 2 +- engine/src/configuration/state.cc | 330 +----------------- engine/src/configuration/tag.cc | 2 +- engine/src/configuration/timeperiod.cc | 2 +- engine/src/configuration/whitelist.cc | 2 - engine/src/contact.cc | 5 +- engine/src/contactgroup.cc | 27 +- engine/src/diagnostic.cc | 3 +- engine/src/escalation.cc | 4 +- engine/src/events/loop.cc | 5 +- engine/src/globals.cc | 2 - engine/src/host.cc | 5 +- engine/src/hostdependency.cc | 5 +- engine/src/hostescalation.cc | 5 +- engine/src/hostgroup.cc | 28 +- engine/src/main.cc | 29 +- engine/src/notifier.cc | 29 +- engine/src/retention/program.cc | 11 - engine/src/service.cc | 5 +- engine/src/servicedependency.cc | 5 +- engine/src/serviceescalation.cc | 5 +- engine/src/servicegroup.cc | 29 +- engine/src/timeperiod.cc | 4 +- engine/tests/checks/anomalydetection.cc | 9 +- engine/tests/checks/service_check.cc | 7 +- engine/tests/checks/service_retention.cc | 9 +- .../tests/configuration/applier-severity.cc | 3 - .../configuration/applier/applier-command.cc | 9 +- .../applier/applier-connector.cc | 1 - .../configuration/applier/applier-contact.cc | 68 ++-- .../applier/applier-contactgroup.cc | 18 +- .../configuration/applier/applier-global.cc | 17 +- .../configuration/applier/applier-host.cc | 5 +- .../applier/applier-hostdependency.cc | 25 +- .../applier/applier-hostescalation.cc | 6 +- .../applier/applier-hostgroup.cc | 23 +- .../configuration/applier/applier-log.cc | 78 +++-- .../configuration/applier/applier-service.cc | 32 +- .../applier/applier-serviceescalation.cc | 5 +- .../applier/applier-servicegroup.cc | 35 +- .../configuration/applier/applier-state.cc | 38 +- engine/tests/configuration/contact.cc | 3 +- engine/tests/configuration/severity.cc | 15 +- engine/tests/configuration/tag.cc | 16 +- engine/tests/configuration/timeperiod-test.cc | 11 +- engine/tests/configuration/timeperiods.cfg | 99 ++++-- engine/tests/custom_vars/extcmd.cc | 3 +- engine/tests/downtimes/downtime_finder.cc | 15 +- engine/tests/enginerpc/enginerpc.cc | 15 +- .../external_commands/anomalydetection.cc | 10 +- engine/tests/external_commands/service.cc | 16 +- engine/tests/loop/loop.cc | 7 +- engine/tests/macros/macro.cc | 140 ++++---- engine/tests/macros/macro_hostname.cc | 60 ++-- engine/tests/macros/macro_service.cc | 36 +- .../host_downtime_notification.cc | 5 +- .../host_flapping_notification.cc | 8 +- .../notifications/host_normal_notification.cc | 44 ++- .../service_downtime_notification_test.cc | 7 +- .../service_flapping_notification.cc | 7 +- .../service_normal_notification.cc | 16 +- .../service_timeperiod_notification.cc | 66 ++-- .../opentelemetry/open_telemetry_test.cc | 7 +- .../tests/opentelemetry/otl_converter_test.cc | 7 +- 155 files changed, 1271 insertions(+), 1644 deletions(-) mode change 100755 => 100644 engine/tests/macros/macro.cc diff --git a/CMakeLists.txt b/CMakeLists.txt index 27dc8e2264f..0291bc4f58f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -27,6 +27,9 @@ cmake_minimum_required(VERSION 3.16) set(CMAKE_CXX_STANDARD 17) +string(TIMESTAMP CENTREON_CURRENT_YEAR "%Y") +add_definitions(-DCENTREON_CURRENT_YEAR="${CENTREON_CURRENT_YEAR}") + if(DEFINED ENV{VCPKG_ROOT}) set(VCPKG_ROOT "$ENV{VCPKG_ROOT}") message(STATUS "TOOLCHAIN set to ${VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake") diff --git a/broker/core/inc/com/centreon/broker/config/applier/state.hh b/broker/core/inc/com/centreon/broker/config/applier/state.hh index 6e11f52b6b9..13be6203c44 100644 --- a/broker/core/inc/com/centreon/broker/config/applier/state.hh +++ b/broker/core/inc/com/centreon/broker/config/applier/state.hh @@ -1,5 +1,5 @@ /** - * Copyright 2011-2012, 2021-2022 Centreon + * Copyright 2011-2012, 2021-2024 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/broker/core/src/main.cc b/broker/core/src/main.cc index 6dd584e2c0d..a279dcf2c26 100644 --- a/broker/core/src/main.cc +++ b/broker/core/src/main.cc @@ -247,8 +247,8 @@ int main(int argc, char* argv[]) { core_logger->info(" '-D' Generate a diagnostic file."); core_logger->info(" '-h' Print this help."); core_logger->info(" '-v' Print Centreon Broker version."); - core_logger->info("Centreon Broker {}", CENTREON_BROKER_VERSION); - core_logger->info("Copyright 2009-2021 Centreon"); + core_logger->info("Centreon Broker " CENTREON_BROKER_VERSION); + core_logger->info("Copyright 2009-" CENTREON_CURRENT_YEAR " Centreon"); core_logger->info( "License ASL 2.0 "); retval = 0; diff --git a/engine/inc/com/centreon/engine/anomalydetection.hh b/engine/inc/com/centreon/engine/anomalydetection.hh index d11f3038023..29785ed6bb5 100644 --- a/engine/inc/com/centreon/engine/anomalydetection.hh +++ b/engine/inc/com/centreon/engine/anomalydetection.hh @@ -1,22 +1,21 @@ -/* -** Copyright 2020 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2020-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCE_ANOMALYDETECTION_HH #define CCE_ANOMALYDETECTION_HH @@ -148,7 +147,7 @@ class anomalydetection : public service { void set_status_change(bool status_change); const std::string& get_metric_name() const; const std::string& get_thresholds_file() const; - void resolve(int& w, int& e); + void resolve(uint32_t& w, uint32_t& e); static const pointer_set& get_anomaly(uint64_t dependent_service_id); }; diff --git a/engine/inc/com/centreon/engine/config.hh b/engine/inc/com/centreon/engine/config.hh index 9b65d752f1e..83cb8240bca 100644 --- a/engine/inc/com/centreon/engine/config.hh +++ b/engine/inc/com/centreon/engine/config.hh @@ -1,23 +1,22 @@ -/* -** Copyright 2002-2006 Ethan Galstad -** Copyright 2011-2019 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2002-2006 Ethan Galstad + * Copyright 2011-2019 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #ifndef CCE_CONFIG_HH #define CCE_CONFIG_HH @@ -30,7 +29,7 @@ extern "C" { #endif // C++ // Detects circular dependencies and paths. -int pre_flight_circular_check(int* w, int* e); +int pre_flight_circular_check(uint32_t* w, uint32_t* e); #ifdef __cplusplus } diff --git a/engine/inc/com/centreon/engine/configuration/anomalydetection.hh b/engine/inc/com/centreon/engine/configuration/anomalydetection.hh index 3c297fc5b36..fb331007c8e 100644 --- a/engine/inc/com/centreon/engine/configuration/anomalydetection.hh +++ b/engine/inc/com/centreon/engine/configuration/anomalydetection.hh @@ -51,7 +51,7 @@ class anomalydetection : public object { bool operator==(anomalydetection const& other) const noexcept; bool operator!=(anomalydetection const& other) const noexcept; bool operator<(anomalydetection const& other) const noexcept; - void check_validity() const override; + void check_validity(error_cnt& err) const override; key_type key() const; void merge(object const& obj) override; bool parse(char const* key, char const* value) override; @@ -144,8 +144,6 @@ class anomalydetection : public object { bool _set_display_name(std::string const& value); bool _set_event_handler(std::string const& value); bool _set_event_handler_enabled(bool value); - bool _set_failure_prediction_enabled(bool value); - bool _set_failure_prediction_options(std::string const& value); bool _set_first_notification_delay(unsigned int value); bool _set_flap_detection_enabled(bool value); bool _set_flap_detection_options(std::string const& value); @@ -165,7 +163,6 @@ class anomalydetection : public object { bool _set_notification_interval(unsigned int value); bool _set_notification_period(std::string const& value); bool _set_obsess_over_service(bool value); - bool _set_parallelize_check(bool value); bool _set_process_perf_data(bool value); bool _set_retain_nonstatus_information(bool value); bool _set_retain_status_information(bool value); diff --git a/engine/inc/com/centreon/engine/configuration/applier/anomalydetection.hh b/engine/inc/com/centreon/engine/configuration/applier/anomalydetection.hh index 88fc8497f6f..7e8df53d199 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/anomalydetection.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/anomalydetection.hh @@ -1,24 +1,24 @@ /** * Copyright 2020-2024 Centreon * - * This file is part of Centreon Engine. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Centreon Engine is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License version 2 - * as published by the Free Software Foundation. + * http://www.apache.org/licenses/LICENSE-2.0 * - * Centreon Engine is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com * - * You should have received a copy of the GNU General Public License - * along with Centreon Engine. If not, see - * . */ - #ifndef CCE_CONFIGURATION_APPLIER_ANOMALYDETECTION_HH #define CCE_CONFIGURATION_APPLIER_ANOMALYDETECTION_HH +#include "com/centreon/engine/configuration/applier/state.hh" namespace com::centreon::engine { @@ -43,7 +43,8 @@ class anomalydetection { void modify_object(configuration::anomalydetection const& obj); void remove_object(configuration::anomalydetection const& obj); void expand_objects(configuration::state& s); - void resolve_object(configuration::anomalydetection const& obj); + void resolve_object(configuration::anomalydetection const& obj, + error_cnt& err); }; } // namespace applier } // namespace configuration diff --git a/engine/inc/com/centreon/engine/configuration/applier/command.hh b/engine/inc/com/centreon/engine/configuration/applier/command.hh index 9049e571dad..e55cfdde7bf 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/command.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/command.hh @@ -1,24 +1,24 @@ /** * Copyright 2011-2013,2017,2023-2024 Centreon * - * This file is part of Centreon Engine. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Centreon Engine is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License version 2 - * as published by the Free Software Foundation. + * http://www.apache.org/licenses/LICENSE-2.0 * - * Centreon Engine is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com * - * You should have received a copy of the GNU General Public License - * along with Centreon Engine. If not, see - * . */ - #ifndef CCE_CONFIGURATION_APPLIER_COMMAND_HH #define CCE_CONFIGURATION_APPLIER_COMMAND_HH +#include "com/centreon/engine/configuration/applier/state.hh" namespace com::centreon::engine { @@ -46,7 +46,7 @@ class command { void expand_objects(configuration::state& s); void modify_object(configuration::command const& obj); void remove_object(configuration::command const& obj); - void resolve_object(configuration::command const& obj); + void resolve_object(configuration::command const& obj, error_cnt& err); }; } // namespace applier } // namespace configuration diff --git a/engine/inc/com/centreon/engine/configuration/applier/connector.hh b/engine/inc/com/centreon/engine/configuration/applier/connector.hh index e7e1ea93490..ad82485acaf 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/connector.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/connector.hh @@ -1,24 +1,24 @@ /** - * Copyright 2011-2013,2017,2023 Centreon + * Copyright 2011-2013,2017,2023-2024 Centreon * - * This file is part of Centreon Engine. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Centreon Engine is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License version 2 - * as published by the Free Software Foundation. + * http://www.apache.org/licenses/LICENSE-2.0 * - * Centreon Engine is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com * - * You should have received a copy of the GNU General Public License - * along with Centreon Engine. If not, see - * . */ - #ifndef CCE_CONFIGURATION_APPLIER_CONNECTOR_HH #define CCE_CONFIGURATION_APPLIER_CONNECTOR_HH +#include "com/centreon/engine/configuration/applier/state.hh" namespace com::centreon::engine { @@ -44,7 +44,7 @@ class connector { void modify_object(const configuration::connector& obj); void remove_object(configuration::connector const& obj); void expand_objects(configuration::state& s); - void resolve_object(configuration::connector const& obj); + void resolve_object(configuration::connector const& obj, error_cnt& err); }; } // namespace applier } // namespace configuration diff --git a/engine/inc/com/centreon/engine/configuration/applier/contact.hh b/engine/inc/com/centreon/engine/configuration/applier/contact.hh index 76a501889f1..3ece9e9ac74 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/contact.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/contact.hh @@ -1,24 +1,24 @@ /** - * Copyright 2011-2013,2017,2023 Centreon + * Copyright 2011-2013,2017,2023-2024 Centreon * - * This file is part of Centreon Engine. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Centreon Engine is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License version 2 - * as published by the Free Software Foundation. + * http://www.apache.org/licenses/LICENSE-2.0 * - * Centreon Engine is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com * - * You should have received a copy of the GNU General Public License - * along with Centreon Engine. If not, see - * . */ - #ifndef CCE_CONFIGURATION_APPLIER_CONTACT_HH #define CCE_CONFIGURATION_APPLIER_CONTACT_HH +#include "com/centreon/engine/configuration/applier/state.hh" namespace com::centreon::engine { @@ -46,7 +46,7 @@ class contact { void modify_object(const configuration::contact& obj); void remove_object(const configuration::contact& obj); void expand_objects(configuration::state& s); - void resolve_object(const configuration::contact& obj); + void resolve_object(const configuration::contact& obj, error_cnt& err); }; } // namespace applier } // namespace configuration diff --git a/engine/inc/com/centreon/engine/configuration/applier/contactgroup.hh b/engine/inc/com/centreon/engine/configuration/applier/contactgroup.hh index 642220d8933..26f3cadcc73 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/contactgroup.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/contactgroup.hh @@ -1,25 +1,25 @@ /** - * Copyright 2011-2013,2017,2023 Centreon + * Copyright 2011-2013,2017,2023-2024 Centreon * - * This file is part of Centreon Engine. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Centreon Engine is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License version 2 - * as published by the Free Software Foundation. + * http://www.apache.org/licenses/LICENSE-2.0 * - * Centreon Engine is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com * - * You should have received a copy of the GNU General Public License - * along with Centreon Engine. If not, see - * . */ - #ifndef CCE_CONFIGURATION_APPLIER_CONTACTGROUP_HH #define CCE_CONFIGURATION_APPLIER_CONTACTGROUP_HH +#include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/configuration/contactgroup.hh" namespace com::centreon::engine { @@ -54,7 +54,7 @@ class contactgroup { void modify_object(configuration::contactgroup const& obj); void remove_object(configuration::contactgroup const& obj); void expand_objects(configuration::state& s); - void resolve_object(configuration::contactgroup const& obj); + void resolve_object(configuration::contactgroup const& obj, error_cnt& err); }; } // namespace applier } // namespace configuration diff --git a/engine/inc/com/centreon/engine/configuration/applier/host.hh b/engine/inc/com/centreon/engine/configuration/applier/host.hh index de0537d71b7..51f0f5d1667 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/host.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/host.hh @@ -1,25 +1,24 @@ -/* -** Copyright 2011-2013,2017 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2013,2017-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCE_CONFIGURATION_APPLIER_HOST_HH #define CCE_CONFIGURATION_APPLIER_HOST_HH - +#include "com/centreon/engine/configuration/applier/state.hh" namespace com::centreon::engine { @@ -39,11 +38,11 @@ class host { void expand_objects(configuration::state& s); void modify_object(configuration::host const& obj); void remove_object(configuration::host const& obj); - void resolve_object(configuration::host const& obj); + void resolve_object(configuration::host const& obj, error_cnt& err); }; } // namespace applier } // namespace configuration -} +} // namespace com::centreon::engine #endif // !CCE_CONFIGURATION_APPLIER_HOST_HH diff --git a/engine/inc/com/centreon/engine/configuration/applier/hostdependency.hh b/engine/inc/com/centreon/engine/configuration/applier/hostdependency.hh index 49993874a05..5c4f0278a96 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/hostdependency.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/hostdependency.hh @@ -19,6 +19,8 @@ #ifndef CCE_CONFIGURATION_APPLIER_HOSTDEPENDENCY_HH #define CCE_CONFIGURATION_APPLIER_HOSTDEPENDENCY_HH +#include "com/centreon/engine/configuration/applier/state.hh" + namespace com::centreon::engine { namespace configuration { @@ -42,7 +44,7 @@ class hostdependency { void modify_object(configuration::hostdependency const& obj); void remove_object(configuration::hostdependency const& obj); void expand_objects(configuration::state& s); - void resolve_object(configuration::hostdependency const& obj); + void resolve_object(configuration::hostdependency const& obj, error_cnt& err); }; } // namespace applier } // namespace configuration diff --git a/engine/inc/com/centreon/engine/configuration/applier/hostescalation.hh b/engine/inc/com/centreon/engine/configuration/applier/hostescalation.hh index 868f01f7050..36bc1f51f0f 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/hostescalation.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/hostescalation.hh @@ -17,6 +17,7 @@ */ #ifndef CCE_CONFIGURATION_APPLIER_HOSTESCALATION_HH #define CCE_CONFIGURATION_APPLIER_HOSTESCALATION_HH +#include "com/centreon/engine/configuration/applier/state.hh" namespace com::centreon::engine { @@ -43,7 +44,7 @@ class hostescalation { void modify_object(configuration::hostescalation const& obj); void remove_object(configuration::hostescalation const& obj); void expand_objects(configuration::state& s); - void resolve_object(configuration::hostescalation const& obj); + void resolve_object(configuration::hostescalation const& obj, error_cnt& err); }; } // namespace applier } // namespace configuration diff --git a/engine/inc/com/centreon/engine/configuration/applier/hostgroup.hh b/engine/inc/com/centreon/engine/configuration/applier/hostgroup.hh index 3f6101eec20..fed53baec2f 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/hostgroup.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/hostgroup.hh @@ -1,25 +1,25 @@ -/* -** Copyright 2011-2013,2017 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2013,2017-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCE_CONFIGURATION_APPLIER_HOSTGROUP_HH #define CCE_CONFIGURATION_APPLIER_HOSTGROUP_HH +#include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/configuration/hostgroup.hh" namespace com::centreon::engine { @@ -39,7 +39,7 @@ class hostgroup { void expand_objects(configuration::state& s); void modify_object(configuration::hostgroup const& obj); void remove_object(configuration::hostgroup const& obj); - void resolve_object(configuration::hostgroup const& obj); + void resolve_object(configuration::hostgroup const& obj, error_cnt& err); private: typedef std::map @@ -53,6 +53,6 @@ class hostgroup { } // namespace applier } // namespace configuration -} +} // namespace com::centreon::engine #endif // !CCE_CONFIGURATION_APPLIER_HOSTGROUP_HH diff --git a/engine/inc/com/centreon/engine/configuration/applier/service.hh b/engine/inc/com/centreon/engine/configuration/applier/service.hh index e8a4acbb8cf..6461ef6055c 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/service.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/service.hh @@ -1,24 +1,24 @@ -/* -** Copyright 2011-2013,2017 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2013,2017-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCE_CONFIGURATION_APPLIER_SERVICE_HH #define CCE_CONFIGURATION_APPLIER_SERVICE_HH +#include "com/centreon/engine/configuration/applier/state.hh" namespace com::centreon::engine { @@ -38,7 +38,7 @@ class service { void expand_objects(configuration::state& s); void modify_object(configuration::service const& obj); void remove_object(configuration::service const& obj); - void resolve_object(configuration::service const& obj); + void resolve_object(configuration::service const& obj, error_cnt& err); private: void _expand_service_memberships(configuration::service& obj, @@ -49,6 +49,6 @@ class service { } // namespace applier } // namespace configuration -} +} // namespace com::centreon::engine #endif // !CCE_CONFIGURATION_APPLIER_SERVICE_HH diff --git a/engine/inc/com/centreon/engine/configuration/applier/servicedependency.hh b/engine/inc/com/centreon/engine/configuration/applier/servicedependency.hh index cc25eefe498..06b83ac0448 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/servicedependency.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/servicedependency.hh @@ -19,6 +19,8 @@ #ifndef CCE_CONFIGURATION_APPLIER_SERVICEDEPENDENCY_HH #define CCE_CONFIGURATION_APPLIER_SERVICEDEPENDENCY_HH +#include "com/centreon/engine/configuration/applier/state.hh" + namespace com::centreon::engine { namespace configuration { @@ -47,7 +49,8 @@ class servicedependency { void modify_object(configuration::servicedependency const& obj); void expand_objects(configuration::state& s); void remove_object(configuration::servicedependency const& obj); - void resolve_object(configuration::servicedependency const& obj); + void resolve_object(configuration::servicedependency const& obj, + error_cnt& err); }; } // namespace applier } // namespace configuration diff --git a/engine/inc/com/centreon/engine/configuration/applier/serviceescalation.hh b/engine/inc/com/centreon/engine/configuration/applier/serviceescalation.hh index 8b6b067a414..dfa3ec3d0be 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/serviceescalation.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/serviceescalation.hh @@ -1,24 +1,24 @@ -/* -** Copyright 2011-2013,2017,2023 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2013,2017,2023-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCE_CONFIGURATION_APPLIER_SERVICEESCALATION_HH #define CCE_CONFIGURATION_APPLIER_SERVICEESCALATION_HH +#include "com/centreon/engine/configuration/applier/state.hh" namespace com::centreon::engine { @@ -48,7 +48,8 @@ class serviceescalation { void modify_object(const configuration::serviceescalation& obj); void remove_object(const configuration::serviceescalation& obj); void expand_objects(configuration::state& s); - void resolve_object(const configuration::serviceescalation& obj); + void resolve_object(const configuration::serviceescalation& obj, + error_cnt& err); }; } // namespace applier } // namespace configuration diff --git a/engine/inc/com/centreon/engine/configuration/applier/servicegroup.hh b/engine/inc/com/centreon/engine/configuration/applier/servicegroup.hh index b542505abbb..a4eefe860f0 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/servicegroup.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/servicegroup.hh @@ -1,25 +1,25 @@ -/* -** Copyright 2011-2013,2017 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2013,2017-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCE_CONFIGURATION_APPLIER_SERVICEGROUP_HH #define CCE_CONFIGURATION_APPLIER_SERVICEGROUP_HH +#include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/configuration/servicegroup.hh" namespace com::centreon::engine { @@ -39,7 +39,7 @@ class servicegroup { void expand_objects(configuration::state& s); void modify_object(configuration::servicegroup const& obj); void remove_object(configuration::servicegroup const& obj); - void resolve_object(configuration::servicegroup const& obj); + void resolve_object(configuration::servicegroup const& obj, error_cnt& err); private: typedef std::map - void _apply(difference> const& diff); - void _apply(configuration::state& new_cfg, retention::state& state); + void _apply(difference> const& diff, + error_cnt& err); + void _apply(configuration::state& new_cfg, + retention::state& state, + error_cnt& err); template - void _expand(configuration::state& new_state); + void _expand(configuration::state& new_state, error_cnt& err); void _processing(configuration::state& new_cfg, - retention::state* state = NULL); + error_cnt& err, + retention::state* state = nullptr); template - void _resolve(std::set& cfg); + void _resolve(std::set& cfg, error_cnt& err); std::mutex _apply_lock; state* _config; diff --git a/engine/inc/com/centreon/engine/configuration/applier/timeperiod.hh b/engine/inc/com/centreon/engine/configuration/applier/timeperiod.hh index 206616c6077..3a47437b3e0 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/timeperiod.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/timeperiod.hh @@ -18,6 +18,7 @@ #ifndef CCE_CONFIGURATION_APPLIER_TIMEPERIOD_HH #define CCE_CONFIGURATION_APPLIER_TIMEPERIOD_HH +#include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/timeperiod.hh" // Forward declaration. @@ -49,7 +50,7 @@ class timeperiod { void expand_objects(configuration::state& s); void modify_object(configuration::timeperiod const& obj); void remove_object(configuration::timeperiod const& obj); - void resolve_object(configuration::timeperiod const& obj); + void resolve_object(configuration::timeperiod const& obj, error_cnt& err); }; } // namespace applier } // namespace configuration diff --git a/engine/inc/com/centreon/engine/configuration/command.hh b/engine/inc/com/centreon/engine/configuration/command.hh index ebca31ad7f3..2ad5e998983 100644 --- a/engine/inc/com/centreon/engine/configuration/command.hh +++ b/engine/inc/com/centreon/engine/configuration/command.hh @@ -35,7 +35,7 @@ class command : public object { bool operator==(command const& right) const throw(); bool operator!=(command const& right) const throw(); bool operator<(command const& right) const throw(); - void check_validity() const override; + void check_validity(error_cnt& err) const override; key_type const& key() const throw(); void merge(object const& obj) override; bool parse(char const* key, char const* value) override; diff --git a/engine/inc/com/centreon/engine/configuration/connector.hh b/engine/inc/com/centreon/engine/configuration/connector.hh index b9c784465e5..adc1d5601a1 100644 --- a/engine/inc/com/centreon/engine/configuration/connector.hh +++ b/engine/inc/com/centreon/engine/configuration/connector.hh @@ -35,7 +35,7 @@ class connector : public object { bool operator==(connector const& right) const throw(); bool operator!=(connector const& right) const throw(); bool operator<(connector const& right) const throw(); - void check_validity() const override; + void check_validity(error_cnt& err) const override; key_type const& key() const throw(); void merge(object const& obj) override; bool parse(char const* key, char const* value) override; diff --git a/engine/inc/com/centreon/engine/configuration/contact.hh b/engine/inc/com/centreon/engine/configuration/contact.hh index 987dcdb2b77..324f20c80a5 100644 --- a/engine/inc/com/centreon/engine/configuration/contact.hh +++ b/engine/inc/com/centreon/engine/configuration/contact.hh @@ -44,7 +44,7 @@ class contact : public object { bool operator==(contact const& other) const noexcept; bool operator!=(contact const& other) const noexcept; bool operator<(contact const& other) const noexcept; - void check_validity() const override; + void check_validity(error_cnt& err) const override; key_type const& key() const noexcept; void merge(object const& obj) override; bool parse(const char* key, const char* value) override; diff --git a/engine/inc/com/centreon/engine/configuration/contactgroup.hh b/engine/inc/com/centreon/engine/configuration/contactgroup.hh index 0eaae3987df..356731a8c34 100644 --- a/engine/inc/com/centreon/engine/configuration/contactgroup.hh +++ b/engine/inc/com/centreon/engine/configuration/contactgroup.hh @@ -36,7 +36,7 @@ class contactgroup : public object { bool operator==(contactgroup const& right) const noexcept; bool operator!=(contactgroup const& right) const noexcept; bool operator<(contactgroup const& right) const noexcept; - void check_validity() const override; + void check_validity(error_cnt& err) const override; key_type const& key() const noexcept; void merge(object const& obj) override; bool parse(char const* key, char const* value) override; diff --git a/engine/inc/com/centreon/engine/configuration/host.hh b/engine/inc/com/centreon/engine/configuration/host.hh index f91cfb8e844..c6498e666b2 100644 --- a/engine/inc/com/centreon/engine/configuration/host.hh +++ b/engine/inc/com/centreon/engine/configuration/host.hh @@ -50,7 +50,7 @@ class host : public object { bool operator==(host const& other) const noexcept; bool operator!=(host const& other) const noexcept; bool operator<(host const& other) const noexcept; - void check_validity() const override; + void check_validity(error_cnt& err) const override; key_type key() const noexcept; void merge(object const& obj) override; bool parse(char const* key, char const* value) override; @@ -134,8 +134,6 @@ class host : public object { bool _set_display_name(std::string const& value); bool _set_event_handler(std::string const& value); bool _set_event_handler_enabled(bool value); - bool _set_failure_prediction_enabled(bool value); - bool _set_failure_prediction_options(std::string const& value); bool _set_first_notification_delay(unsigned int value); bool _set_flap_detection_enabled(bool value); bool _set_flap_detection_options(std::string const& value); diff --git a/engine/inc/com/centreon/engine/configuration/hostdependency.hh b/engine/inc/com/centreon/engine/configuration/hostdependency.hh index 1f708e47c94..e7862ee2e59 100644 --- a/engine/inc/com/centreon/engine/configuration/hostdependency.hh +++ b/engine/inc/com/centreon/engine/configuration/hostdependency.hh @@ -52,7 +52,7 @@ class hostdependency : public object { bool operator==(hostdependency const& right) const throw(); bool operator!=(hostdependency const& right) const throw(); bool operator<(hostdependency const& right) const; - void check_validity() const override; + void check_validity(error_cnt& err) const override; key_type const& key() const throw(); void merge(object const& obj) override; bool parse(char const* key, char const* value) override; diff --git a/engine/inc/com/centreon/engine/configuration/hostescalation.hh b/engine/inc/com/centreon/engine/configuration/hostescalation.hh index 87b6038e9bd..ce8a6ca90ef 100644 --- a/engine/inc/com/centreon/engine/configuration/hostescalation.hh +++ b/engine/inc/com/centreon/engine/configuration/hostescalation.hh @@ -45,7 +45,7 @@ class hostescalation : public object { bool operator==(hostescalation const& right) const throw(); bool operator!=(hostescalation const& right) const throw(); bool operator<(hostescalation const& right) const; - void check_validity() const override; + void check_validity(error_cnt& err) const override; key_type const& key() const throw(); void merge(object const& obj) override; bool parse(char const* key, char const* value) override; diff --git a/engine/inc/com/centreon/engine/configuration/hostgroup.hh b/engine/inc/com/centreon/engine/configuration/hostgroup.hh index e3d5bd538f3..680abb59949 100644 --- a/engine/inc/com/centreon/engine/configuration/hostgroup.hh +++ b/engine/inc/com/centreon/engine/configuration/hostgroup.hh @@ -37,7 +37,7 @@ class hostgroup : public object { bool operator==(hostgroup const& right) const throw(); bool operator!=(hostgroup const& right) const throw(); bool operator<(hostgroup const& right) const throw(); - void check_validity() const override; + void check_validity(error_cnt& err) const override; key_type const& key() const throw(); void merge(object const& obj) override; bool parse(char const* key, char const* value) override; diff --git a/engine/inc/com/centreon/engine/configuration/object.hh b/engine/inc/com/centreon/engine/configuration/object.hh index 534f467c7c0..db155f96e87 100644 --- a/engine/inc/com/centreon/engine/configuration/object.hh +++ b/engine/inc/com/centreon/engine/configuration/object.hh @@ -26,6 +26,16 @@ typedef std::set set_string; namespace com::centreon::engine { namespace configuration { + +/** + * @brief Error counter, it contains two attributes, one for warnings and + * another for errors. + */ +struct error_cnt { + uint32_t config_warnings = 0; + uint32_t config_errors = 0; +}; + class object { public: enum object_type { @@ -55,7 +65,7 @@ class object { object& operator=(object const& right); bool operator==(object const& right) const noexcept; bool operator!=(object const& right) const noexcept; - virtual void check_validity() const = 0; + virtual void check_validity(error_cnt& err) const = 0; static std::shared_ptr create(std::string const& type_name); virtual void merge(object const& obj) = 0; const std::string& name() const noexcept; diff --git a/engine/inc/com/centreon/engine/configuration/parser.hh b/engine/inc/com/centreon/engine/configuration/parser.hh index ee6b3e41048..42d9c052db3 100644 --- a/engine/inc/com/centreon/engine/configuration/parser.hh +++ b/engine/inc/com/centreon/engine/configuration/parser.hh @@ -20,23 +20,13 @@ #define CCE_CONFIGURATION_PARSER_HH #include -#include "com/centreon/engine/configuration/command.hh" -#include "com/centreon/engine/configuration/connector.hh" -#include "com/centreon/engine/configuration/contact.hh" #include "com/centreon/engine/configuration/file_info.hh" -#include "com/centreon/engine/configuration/host.hh" -#include "com/centreon/engine/configuration/hostdependency.hh" -#include "com/centreon/engine/configuration/hostescalation.hh" -#include "com/centreon/engine/configuration/object.hh" -#include "com/centreon/engine/configuration/service.hh" -#include "com/centreon/engine/configuration/servicedependency.hh" -#include "com/centreon/engine/configuration/serviceescalation.hh" #include "com/centreon/engine/configuration/state.hh" -#include "com/centreon/engine/configuration/timeperiod.hh" namespace com::centreon::engine { namespace configuration { + class parser { std::shared_ptr _logger; @@ -61,7 +51,7 @@ class parser { parser(unsigned int read_options = read_all); ~parser() noexcept = default; - void parse(const std::string& path, state& config); + void parse(const std::string& path, state& config, error_cnt& err); private: typedef void (parser::*store)(object_ptr obj); @@ -90,7 +80,7 @@ class parser { void _parse_global_configuration(const std::string& path); void _parse_object_definitions(const std::string& path); void _parse_resource_file(std::string const& path); - void _resolve_template(); + void _resolve_template(error_cnt& err); void _store_into_list(object_ptr obj); template void _store_into_map(object_ptr obj); diff --git a/engine/inc/com/centreon/engine/configuration/service.hh b/engine/inc/com/centreon/engine/configuration/service.hh index 90ff383f511..109d6878ef8 100644 --- a/engine/inc/com/centreon/engine/configuration/service.hh +++ b/engine/inc/com/centreon/engine/configuration/service.hh @@ -47,7 +47,7 @@ class service : public object { bool operator==(service const& other) const noexcept; bool operator!=(service const& other) const noexcept; bool operator<(service const& other) const noexcept; - void check_validity() const override; + void check_validity(error_cnt& err) const override; key_type key() const; void merge(object const& obj) override; bool parse(char const* key, char const* value) override; @@ -134,8 +134,6 @@ class service : public object { bool _set_display_name(std::string const& value); bool _set_event_handler(std::string const& value); bool _set_event_handler_enabled(bool value); - bool _set_failure_prediction_enabled(bool value); - bool _set_failure_prediction_options(std::string const& value); bool _set_first_notification_delay(unsigned int value); bool _set_flap_detection_enabled(bool value); bool _set_flap_detection_options(std::string const& value); @@ -155,7 +153,6 @@ class service : public object { bool _set_notification_interval(unsigned int value); bool _set_notification_period(std::string const& value); bool _set_obsess_over_service(bool value); - bool _set_parallelize_check(bool value); bool _set_process_perf_data(bool value); bool _set_retain_nonstatus_information(bool value); bool _set_retain_status_information(bool value); diff --git a/engine/inc/com/centreon/engine/configuration/servicedependency.hh b/engine/inc/com/centreon/engine/configuration/servicedependency.hh index 61ea8f77c10..7cb9c5a1594 100644 --- a/engine/inc/com/centreon/engine/configuration/servicedependency.hh +++ b/engine/inc/com/centreon/engine/configuration/servicedependency.hh @@ -53,7 +53,7 @@ class servicedependency : public object { bool operator==(servicedependency const& right) const throw(); bool operator!=(servicedependency const& right) const throw(); bool operator<(servicedependency const& right) const; - void check_validity() const override; + void check_validity(error_cnt& err) const override; key_type const& key() const throw(); void merge(object const& obj) override; bool parse(char const* key, char const* value) override; diff --git a/engine/inc/com/centreon/engine/configuration/serviceescalation.hh b/engine/inc/com/centreon/engine/configuration/serviceescalation.hh index e093fce58e5..7dcdb838bc5 100644 --- a/engine/inc/com/centreon/engine/configuration/serviceescalation.hh +++ b/engine/inc/com/centreon/engine/configuration/serviceescalation.hh @@ -71,7 +71,7 @@ class serviceescalation : public object { bool operator==(serviceescalation const& right) const noexcept; bool operator!=(serviceescalation const& right) const noexcept; bool operator<(serviceescalation const& right) const; - void check_validity() const override; + void check_validity(error_cnt& err) const override; key_type const& key() const noexcept; void merge(object const& obj) override; bool parse(char const* key, char const* value) override; diff --git a/engine/inc/com/centreon/engine/configuration/servicegroup.hh b/engine/inc/com/centreon/engine/configuration/servicegroup.hh index 879eacf999e..caa2147f79e 100644 --- a/engine/inc/com/centreon/engine/configuration/servicegroup.hh +++ b/engine/inc/com/centreon/engine/configuration/servicegroup.hh @@ -39,7 +39,7 @@ class servicegroup : public object { bool operator==(servicegroup const& right) const throw(); bool operator!=(servicegroup const& right) const throw(); bool operator<(servicegroup const& right) const throw(); - void check_validity() const override; + void check_validity(error_cnt& err) const override; key_type const& key() const throw(); void merge(object const& obj) override; bool parse(char const* key, char const* value) override; diff --git a/engine/inc/com/centreon/engine/configuration/severity.hh b/engine/inc/com/centreon/engine/configuration/severity.hh index 5cd3e04e7e7..78f290c5540 100644 --- a/engine/inc/com/centreon/engine/configuration/severity.hh +++ b/engine/inc/com/centreon/engine/configuration/severity.hh @@ -55,7 +55,7 @@ class severity : public object { bool operator==(const severity& other) const noexcept; bool operator!=(const severity& other) const noexcept; bool operator<(const severity& other) const noexcept; - void check_validity() const override; + void check_validity(error_cnt& err) const override; const key_type& key() const noexcept; void merge(const object& obj) override; bool parse(const char* key, const char* value) override; diff --git a/engine/inc/com/centreon/engine/configuration/state.hh b/engine/inc/com/centreon/engine/configuration/state.hh index c2e412f1ea2..33af15d6389 100644 --- a/engine/inc/com/centreon/engine/configuration/state.hh +++ b/engine/inc/com/centreon/engine/configuration/state.hh @@ -74,6 +74,12 @@ class state { std::shared_ptr _logger; public: + struct sched_info_config { + double host_inter_check_delay; + double service_inter_check_delay; + int32_t service_interleave_factor; + } _scheduling_info; + /** * @enum state::date_format * Date format types @@ -461,6 +467,7 @@ class state { void use_timezone(std::string const& value); bool use_true_regexp_matching() const noexcept; void use_true_regexp_matching(bool value); + sched_info_config& sched_info_config() { return _scheduling_info; } bool use_send_recovery_notifications_anyways() const; void use_send_recovery_notifications_anyways(bool value); bool use_host_down_disable_service_checks() const; @@ -475,43 +482,19 @@ class state { private: static void _init_setter(); - void _set_aggregate_status_updates(std::string const& value); - void _set_auth_file(std::string const& value); - void _set_bare_update_check(std::string const& value); void _set_broker_module(std::string const& value); void _set_cfg_dir(std::string const& value); void _set_cfg_file(std::string const& value); - void _set_check_for_updates(std::string const& value); - void _set_child_processes_fork_twice(std::string const& value); void _set_command_check_interval(std::string const& value); - void _set_comment_file(std::string const& value); - void _set_daemon_dumps_core(std::string const& value); void _set_date_format(std::string const& value); - void _set_downtime_file(std::string const& value); - void _set_enable_embedded_perl(std::string const& value); - void _set_enable_failure_prediction(std::string const& value); void _set_event_broker_options(std::string const& value); - void _set_free_child_process_memory(std::string const& value); void _set_host_inter_check_delay_method(std::string const& value); void _set_host_perfdata_file_mode(std::string const& value); - void _set_lock_file(std::string const& value); - void _set_log_archive_path(std::string const& value); - void _set_log_initial_states(std::string const& value); - void _set_log_rotation_method(std::string const& value); - void _set_nagios_group(std::string const& value); - void _set_nagios_user(std::string const& value); void _set_object_cache_file(std::string const& value); - void _set_p1_file(std::string const& value); - void _set_precached_object_file(std::string const& value); void _set_resource_file(std::string const& value); - void _set_retained_process_service_attribute_mask(std::string const& value); - void _set_retained_service_attribute_mask(std::string const& value); void _set_service_inter_check_delay_method(std::string const& value); void _set_service_interleave_factor_method(std::string const& value); void _set_service_perfdata_file_mode(std::string const& value); - void _set_temp_file(std::string const& value); - void _set_temp_path(std::string const& value); - void _set_use_embedded_perl_implicitly(std::string const& value); bool _accept_passive_host_checks; bool _accept_passive_service_checks; diff --git a/engine/inc/com/centreon/engine/configuration/tag.hh b/engine/inc/com/centreon/engine/configuration/tag.hh index c1697c2b3df..d40d9c9a14f 100644 --- a/engine/inc/com/centreon/engine/configuration/tag.hh +++ b/engine/inc/com/centreon/engine/configuration/tag.hh @@ -55,7 +55,7 @@ class tag : public object { bool operator==(const tag& other) const noexcept; bool operator!=(const tag& other) const noexcept; bool operator<(const tag& other) const noexcept; - void check_validity() const override; + void check_validity(error_cnt& err) const override; const key_type& key() const noexcept; void merge(const object& obj) override; bool parse(const char* key, const char* value) override; diff --git a/engine/inc/com/centreon/engine/configuration/timeperiod.hh b/engine/inc/com/centreon/engine/configuration/timeperiod.hh index 7b09612bdf4..b179a71d113 100644 --- a/engine/inc/com/centreon/engine/configuration/timeperiod.hh +++ b/engine/inc/com/centreon/engine/configuration/timeperiod.hh @@ -41,7 +41,7 @@ class timeperiod : public object { bool operator==(timeperiod const& right) const; bool operator!=(timeperiod const& right) const; bool operator<(timeperiod const& right) const; - void check_validity() const override; + void check_validity(error_cnt& err) const override; key_type const& key() const throw(); void merge(object const& obj) override; bool parse(char const* key, char const* value) override; diff --git a/engine/inc/com/centreon/engine/configuration/whitelist.hh b/engine/inc/com/centreon/engine/configuration/whitelist.hh index 7936621be18..26991502388 100644 --- a/engine/inc/com/centreon/engine/configuration/whitelist.hh +++ b/engine/inc/com/centreon/engine/configuration/whitelist.hh @@ -19,7 +19,6 @@ #ifndef CCE_CONFIGURATION_WHITELIST_HH #define CCE_CONFIGURATION_WHITELIST_HH -#include "com/centreon/engine/globals.hh" #include "common/log_v2/log_v2.hh" namespace com::centreon::engine::configuration { diff --git a/engine/inc/com/centreon/engine/contact.hh b/engine/inc/com/centreon/engine/contact.hh index 8476a312443..b9f3b26d9c7 100644 --- a/engine/inc/com/centreon/engine/contact.hh +++ b/engine/inc/com/centreon/engine/contact.hh @@ -20,9 +20,6 @@ #ifndef CCE_CONTACT_HH #define CCE_CONTACT_HH -#include -#include "com/centreon/engine/contactgroup.hh" -#include "com/centreon/engine/customvariable.hh" #include "com/centreon/engine/notifier.hh" /* Max number of custom addresses a contact can have. */ @@ -127,7 +124,7 @@ class contact { bool should_be_notified(notifier::notification_category cat, notifier::reason_type type, notifier const& notif) const; - void resolve(int& w, int& e); + void resolve(uint32_t& w, uint32_t& e); map_customvar const& get_custom_variables() const; map_customvar& get_custom_variables(); timeperiod* get_host_notification_period_ptr() const; @@ -180,7 +177,7 @@ class contact { timeperiod* _service_notification_period_ptr; }; -} +} // namespace com::centreon::engine std::shared_ptr add_contact( std::string const& name, diff --git a/engine/inc/com/centreon/engine/contactgroup.hh b/engine/inc/com/centreon/engine/contactgroup.hh index 1a297aabe97..66345a29e60 100644 --- a/engine/inc/com/centreon/engine/contactgroup.hh +++ b/engine/inc/com/centreon/engine/contactgroup.hh @@ -1,22 +1,21 @@ -/* -** Copyright 2011-2019 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCE_OBJECTS_CONTACTGROUP_HH #define CCE_OBJECTS_CONTACTGROUP_HH @@ -33,7 +32,7 @@ class contactgroup; namespace configuration { class contactgroup; } -} +} // namespace com::centreon::engine using contactgroup_map = absl::flat_hash_map. -*/ - +/** + * Copyright 1999-2009 Ethan Galstad + * Copyright 2009-2010 Nagios Core Development Team and Community Contributors + * Copyright 2011-2024 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #ifndef CCE_GLOBALS_HH #define CCE_GLOBALS_HH @@ -33,9 +32,6 @@ #include "com/centreon/engine/utils.hh" #include "common/log_v2/log_v2.hh" -extern int config_errors; -extern int config_warnings; - /* Start/Restart statistics */ extern com::centreon::engine::restart_stats restart_apply_stats; diff --git a/engine/inc/com/centreon/engine/host.hh b/engine/inc/com/centreon/engine/host.hh index 61c533c27ea..20366362956 100644 --- a/engine/inc/com/centreon/engine/host.hh +++ b/engine/inc/com/centreon/engine/host.hh @@ -245,7 +245,7 @@ class host : public notifier { timeperiod* get_notification_timeperiod() const override; bool get_notify_on_current_state() const override; bool is_in_downtime() const override; - void resolve(int& w, int& e); + void resolve(uint32_t& w, uint32_t& e); void set_check_command_ptr( const std::shared_ptr& cmd) override; diff --git a/engine/inc/com/centreon/engine/hostdependency.hh b/engine/inc/com/centreon/engine/hostdependency.hh index ec72dca3651..7ee9b336304 100644 --- a/engine/inc/com/centreon/engine/hostdependency.hh +++ b/engine/inc/com/centreon/engine/hostdependency.hh @@ -57,7 +57,7 @@ class hostdependency : public dependency { bool check_for_circular_hostdependency_path(hostdependency* dep, types dependency_type); - void resolve(int& w, int& e); + void resolve(uint32_t& w, uint32_t& e); bool get_fail_on(int state) const override; bool operator==(hostdependency const& obj) = delete; diff --git a/engine/inc/com/centreon/engine/hostescalation.hh b/engine/inc/com/centreon/engine/hostescalation.hh index efdb316c222..f5e24720c18 100644 --- a/engine/inc/com/centreon/engine/hostescalation.hh +++ b/engine/inc/com/centreon/engine/hostescalation.hh @@ -48,7 +48,7 @@ class hostescalation : public escalation { std::string const& get_hostname() const; bool is_viable(int state, uint32_t notification_number) const override; - void resolve(int& w, int& e) override; + void resolve(uint32_t& w, uint32_t& e) override; bool matches(const configuration::hostescalation& obj) const; diff --git a/engine/inc/com/centreon/engine/hostgroup.hh b/engine/inc/com/centreon/engine/hostgroup.hh index 52fa4a00d7a..7d12ef50a06 100644 --- a/engine/inc/com/centreon/engine/hostgroup.hh +++ b/engine/inc/com/centreon/engine/hostgroup.hh @@ -1,22 +1,21 @@ -/* -** Copyright 2011-2019 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCE_OBJECTS_HOSTGROUP_HH #define CCE_OBJECTS_HOSTGROUP_HH @@ -55,7 +54,7 @@ class hostgroup { void set_action_url(std::string const& action_url); bool operator==(hostgroup const& obj) = delete; bool operator!=(hostgroup const& obj1) = delete; - void resolve(int& w, int& e); + void resolve(uint32_t& w, uint32_t& e); host_map_unsafe members; @@ -69,7 +68,7 @@ class hostgroup { std::string _notes_url; std::string _action_url; }; -} +} // namespace com::centreon::engine std::ostream& operator<<(std::ostream& os, com::centreon::engine::hostgroup const& obj); diff --git a/engine/inc/com/centreon/engine/macros/defines.hh b/engine/inc/com/centreon/engine/macros/defines.hh index cb09fa59892..0d92a4634a7 100644 --- a/engine/inc/com/centreon/engine/macros/defines.hh +++ b/engine/inc/com/centreon/engine/macros/defines.hh @@ -22,11 +22,7 @@ #define CCE_MACROS_DEFINES_HH_ #include "com/centreon/engine/contact.hh" -#include "com/centreon/engine/contactgroup.hh" -#include "com/centreon/engine/customvariable.hh" -#include "com/centreon/engine/host.hh" #include "com/centreon/engine/hostgroup.hh" -#include "com/centreon/engine/service.hh" #include "com/centreon/engine/servicegroup.hh" // Length Limitations diff --git a/engine/inc/com/centreon/engine/notifier.hh b/engine/inc/com/centreon/engine/notifier.hh index 329eb98b137..8705f069bbb 100644 --- a/engine/inc/com/centreon/engine/notifier.hh +++ b/engine/inc/com/centreon/engine/notifier.hh @@ -258,7 +258,7 @@ class notifier : public checkable { const absl::flat_hash_map& contacts() const noexcept; contactgroup_map_unsafe& get_contactgroups() noexcept; contactgroup_map_unsafe const& get_contactgroups() const noexcept; - void resolve(int& w, int& e); + void resolve(uint32_t& w, uint32_t& e); std::array const& get_state_history() const; std::array& get_state_history(); std::array, 6> const& @@ -340,7 +340,7 @@ class notifier : public checkable { int _pending_flex_downtime; }; -} +} // namespace com::centreon::engine bool is_contact_for_notifier(com::centreon::engine::notifier* notif, com::centreon::engine::contact* cntct); diff --git a/engine/inc/com/centreon/engine/retention/applier/anomalydetection.hh b/engine/inc/com/centreon/engine/retention/applier/anomalydetection.hh index 5a1b7e57f3e..2a1e7be6cc4 100644 --- a/engine/inc/com/centreon/engine/retention/applier/anomalydetection.hh +++ b/engine/inc/com/centreon/engine/retention/applier/anomalydetection.hh @@ -1,22 +1,21 @@ -/* -** Copyright 2022 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2022-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCE_RETENTION_APPLIER_ANOMALYDETECTION_HH #define CCE_RETENTION_APPLIER_ANOMALYDETECTION_HH @@ -49,6 +48,6 @@ class anomalydetection { } // namespace applier } // namespace retention -} +} // namespace com::centreon::engine #endif // !CCE_RETENTION_APPLIER_ANOMALYDETECTION_HH diff --git a/engine/inc/com/centreon/engine/retention/program.hh b/engine/inc/com/centreon/engine/retention/program.hh index 565345aa2d4..d65832bf65b 100644 --- a/engine/inc/com/centreon/engine/retention/program.hh +++ b/engine/inc/com/centreon/engine/retention/program.hh @@ -71,7 +71,6 @@ class program : public object { bool _set_check_host_freshness(bool value); bool _set_check_service_freshness(bool value); bool _set_enable_event_handlers(bool value); - bool _set_enable_failure_prediction(bool value); bool _set_enable_flap_detection(bool value); bool _set_enable_notifications(bool value); bool _set_global_host_event_handler(std::string const& value); diff --git a/engine/inc/com/centreon/engine/service.hh b/engine/inc/com/centreon/engine/service.hh index b602224dc46..c2c1e853c7f 100644 --- a/engine/inc/com/centreon/engine/service.hh +++ b/engine/inc/com/centreon/engine/service.hh @@ -205,7 +205,7 @@ class service : public notifier { static void check_for_orphaned(); static void check_result_freshness(); bool is_in_downtime() const override; - void resolve(int& w, int& e); + void resolve(uint32_t& w, uint32_t& e); std::list const& get_parent_groups() const; std::list& get_parent_groups(); diff --git a/engine/inc/com/centreon/engine/servicedependency.hh b/engine/inc/com/centreon/engine/servicedependency.hh index 94647358442..de2b2b733a3 100644 --- a/engine/inc/com/centreon/engine/servicedependency.hh +++ b/engine/inc/com/centreon/engine/servicedependency.hh @@ -76,7 +76,7 @@ class servicedependency : public dependency { bool check_for_circular_servicedependency_path(servicedependency* dep, types dependency_type); - void resolve(int& w, int& e); + void resolve(uint32_t& w, uint32_t& e); bool get_fail_on(int state) const override; bool operator==(servicedependency const& obj) = delete; diff --git a/engine/inc/com/centreon/engine/serviceescalation.hh b/engine/inc/com/centreon/engine/serviceescalation.hh index abe959912cd..f634f32b83c 100644 --- a/engine/inc/com/centreon/engine/serviceescalation.hh +++ b/engine/inc/com/centreon/engine/serviceescalation.hh @@ -52,7 +52,7 @@ class serviceescalation : public escalation { std::string const& get_hostname() const; std::string const& get_description() const; bool is_viable(int state, uint32_t notification_number) const override; - void resolve(int& w, int& e) override; + void resolve(uint32_t& w, uint32_t& e) override; bool matches(const configuration::serviceescalation& obj) const; static serviceescalation_mmap serviceescalations; diff --git a/engine/inc/com/centreon/engine/servicegroup.hh b/engine/inc/com/centreon/engine/servicegroup.hh index 653c4324dc8..25308bb1141 100644 --- a/engine/inc/com/centreon/engine/servicegroup.hh +++ b/engine/inc/com/centreon/engine/servicegroup.hh @@ -1,22 +1,22 @@ -/* -** Copyright 2011-2013 Merethis -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2013 Merethis + * Copyright 2014-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCE_OBJECTS_SERVICEGROUP_HH #define CCE_OBJECTS_SERVICEGROUP_HH @@ -26,7 +26,7 @@ namespace com::centreon::engine { class host; class servicegroup; -} +} // namespace com::centreon::engine using servicegroup_map = absl::flat_hash_map. -*/ - +/** + * Copyright 2011-2013 Merethis + * Copyright 2014-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ #ifndef CCE_OBJECTS_TIMEPERIOD_HH #define CCE_OBJECTS_TIMEPERIOD_HH @@ -52,7 +52,7 @@ class timeperiod { time_t* invalid_time, bool notif_timeperiod); - void resolve(int& w, int& e); + void resolve(uint32_t& w, uint32_t& e); bool operator==(timeperiod const& obj) throw(); bool operator!=(timeperiod const& obj) throw(); @@ -68,7 +68,7 @@ class timeperiod { timeperiodexclusion _exclusions; }; -} +} // namespace com::centreon::engine bool check_time_against_period(time_t test_time, com::centreon::engine::timeperiod* tperiod); diff --git a/engine/inc/com/centreon/engine/xpddefault.hh b/engine/inc/com/centreon/engine/xpddefault.hh index dc78ca827e7..6fce4315790 100644 --- a/engine/inc/com/centreon/engine/xpddefault.hh +++ b/engine/inc/com/centreon/engine/xpddefault.hh @@ -21,9 +21,7 @@ #ifndef CCE_XPDDEFAULT_HH #define CCE_XPDDEFAULT_HH -#include "com/centreon/engine/host.hh" #include "com/centreon/engine/macros/defines.hh" -#include "com/centreon/engine/service.hh" #ifdef __cplusplus extern "C" { diff --git a/engine/src/anomalydetection.cc b/engine/src/anomalydetection.cc index 2aca85a1275..df1a6956e69 100644 --- a/engine/src/anomalydetection.cc +++ b/engine/src/anomalydetection.cc @@ -1397,7 +1397,7 @@ const std::string& anomalydetection::get_thresholds_file() const { return _thresholds_file; } -void anomalydetection::resolve(int& w, int& e) { +void anomalydetection::resolve(uint32_t& w, uint32_t& e) { set_check_period(_dependent_service->check_period()); service::resolve(w, e); } diff --git a/engine/src/config.cc b/engine/src/config.cc index 87cd3d99014..cdbb2421cb2 100644 --- a/engine/src/config.cc +++ b/engine/src/config.cc @@ -99,10 +99,10 @@ static int dfs_host_path(host* root) { } /* check for circular paths and dependencies */ -int pre_flight_circular_check(int* w, int* e) { - int found(false); - int warnings(0); - int errors(0); +int pre_flight_circular_check(uint32_t* w, uint32_t* e) { + int found = false; + uint32_t warnings = 0; + uint32_t errors = 0; /* bail out if we aren't supposed to verify circular paths */ if (!verify_circular_paths) diff --git a/engine/src/configuration/anomalydetection.cc b/engine/src/configuration/anomalydetection.cc index 8e5c84f74ea..30ba75b5a32 100644 --- a/engine/src/configuration/anomalydetection.cc +++ b/engine/src/configuration/anomalydetection.cc @@ -23,9 +23,6 @@ #include #include "com/centreon/exceptions/msg_fmt.hh" -extern int config_warnings; -extern int config_errors; - using namespace com::centreon; using namespace com::centreon::engine::configuration; using com::centreon::exceptions::msg_fmt; @@ -56,8 +53,6 @@ std::unordered_map const SETTER(std::string const&, _set_notification_period)}, {"contact_groups", SETTER(std::string const&, _set_contactgroups)}, {"contacts", SETTER(std::string const&, _set_contacts)}, - {"failure_prediction_options", - SETTER(std::string const&, _set_failure_prediction_options)}, {"notes", SETTER(std::string const&, _set_notes)}, {"notes_url", SETTER(std::string const&, _set_notes_url)}, {"action_url", SETTER(std::string const&, _set_action_url)}, @@ -74,7 +69,6 @@ std::unordered_map const {"status_change", SETTER(bool, _set_status_change)}, {"active_checks_enabled", SETTER(bool, _set_checks_active)}, {"passive_checks_enabled", SETTER(bool, _set_checks_passive)}, - {"parallelize_check", SETTER(bool, _set_parallelize_check)}, {"is_volatile", SETTER(bool, _set_is_volatile)}, {"obsess_over_service", SETTER(bool, _set_obsess_over_service)}, {"event_handler_enabled", SETTER(bool, _set_event_handler_enabled)}, @@ -94,8 +88,6 @@ std::unordered_map const SETTER(unsigned int, _set_first_notification_delay)}, {"stalking_options", SETTER(std::string const&, _set_stalking_options)}, {"process_perf_data", SETTER(bool, _set_process_perf_data)}, - {"failure_prediction_enabled", - SETTER(bool, _set_failure_prediction_enabled)}, {"retain_status_information", SETTER(bool, _set_retain_status_information)}, {"retain_nonstatus_information", @@ -756,7 +748,7 @@ bool anomalydetection::operator<(anomalydetection const& other) const noexcept { * * @exception msg_fmt if this anomalydetection is an invalid object. */ -void anomalydetection::check_validity() const { +void anomalydetection::check_validity(error_cnt& err) const { if (_service_description.empty()) throw msg_fmt( "Service has no description (property 'service_description')"); @@ -1606,39 +1598,6 @@ bool anomalydetection::_set_event_handler_enabled(bool value) { return true; } -/** - * Set failure_prediction_enabled value. - * - * @param[in] value The new failure_prediction_enabled value. - * - * @return True on success, otherwise false. - */ -bool anomalydetection::_set_failure_prediction_enabled(bool value) { - (void)value; - _logger->warn( - "Warning: anomalydetection failure_prediction_enabled is deprecated. " - "This option will not be supported in 20.04."); - ++config_warnings; - return true; -} - -/** - * Set failure_prediction_options value. - * - * @param[in] value The new failure_prediction_options value. - * - * @return True on success, otherwise false. - */ -bool anomalydetection::_set_failure_prediction_options( - std::string const& value) { - (void)value; - _logger->warn( - "Warning: anomalydetection failure_prediction_options is deprecated. " - "This option will not be supported in 20.04."); - ++config_warnings; - return true; -} - /** * Set first_notification_delay value. * @@ -1922,22 +1881,6 @@ bool anomalydetection::_set_obsess_over_service(bool value) { return true; } -/** - * Set parallelize_check value. - * - * @param[in] value The new parallelize_check value. - * - * @return True on success, otherwise false. - */ -bool anomalydetection::_set_parallelize_check(bool value) { - (void)value; - _logger->warn( - "Warning: anomalydetection parallelize_check is deprecated This option " - "will not be supported in 20.04."); - ++config_warnings; - return true; -} - /** * Set process_perf_data value. * diff --git a/engine/src/configuration/applier/anomalydetection.cc b/engine/src/configuration/applier/anomalydetection.cc index 35f1de0b428..78d062bc6f0 100644 --- a/engine/src/configuration/applier/anomalydetection.cc +++ b/engine/src/configuration/applier/anomalydetection.cc @@ -459,7 +459,8 @@ void applier::anomalydetection::remove_object( * @param[in] obj Service object. */ void applier::anomalydetection::resolve_object( - configuration::anomalydetection const& obj) { + configuration::anomalydetection const& obj, + error_cnt& err) { // Logging. engine_logger(logging::dbg_config, logging::more) << "Resolving anomalydetection '" << obj.service_description() @@ -489,7 +490,7 @@ void applier::anomalydetection::resolve_object( } // Resolve anomalydetection. - it->second->resolve(config_warnings, config_errors); + it->second->resolve(err.config_warnings, err.config_errors); } /** diff --git a/engine/src/configuration/applier/command.cc b/engine/src/configuration/applier/command.cc index c8bd72bdf67..d2b0c82c9f2 100644 --- a/engine/src/configuration/applier/command.cc +++ b/engine/src/configuration/applier/command.cc @@ -209,7 +209,8 @@ void applier::command::remove_object(configuration::command const& obj) { * * @param[in] obj Command object. */ -void applier::command::resolve_object(configuration::command const& obj) { +void applier::command::resolve_object(configuration::command const& obj, + error_cnt& err) { if (!obj.connector().empty()) { connector_map::iterator found{ commands::connector::connectors.find(obj.connector())}; diff --git a/engine/src/configuration/applier/connector.cc b/engine/src/configuration/applier/connector.cc index 4c51c1f5e1f..67039caf1ac 100644 --- a/engine/src/configuration/applier/connector.cc +++ b/engine/src/configuration/applier/connector.cc @@ -189,6 +189,7 @@ void applier::connector::remove_object(configuration::connector const& obj) { * * @param[in] obj Unused. */ -void applier::connector::resolve_object(configuration::connector const& obj) { +void applier::connector::resolve_object(configuration::connector const& obj, + error_cnt& err) { (void)obj; } diff --git a/engine/src/configuration/applier/contact.cc b/engine/src/configuration/applier/contact.cc index 59df873f2bc..b96e9a03880 100644 --- a/engine/src/configuration/applier/contact.cc +++ b/engine/src/configuration/applier/contact.cc @@ -371,7 +371,8 @@ void applier::contact::expand_objects(configuration::state& s) { * * @param[in,out] obj Object to resolve. */ -void applier::contact::resolve_object(const configuration::contact& obj) { +void applier::contact::resolve_object(const configuration::contact& obj, + error_cnt& err) { // Logging. engine_logger(logging::dbg_config, logging::more) << "Resolving contact '" << obj.contact_name() << "'."; @@ -394,7 +395,7 @@ void applier::contact::resolve_object(const configuration::contact& obj) { if (itt != commands::command::commands.end()) ct_it->second->get_host_notification_commands().push_back(itt->second); else { - ++config_errors; + ++err.config_errors; throw(engine_error() << "Could not add host notification command '" << *it << "' to contact '" << obj.contact_name() << "': the command does not exist"); @@ -412,7 +413,7 @@ void applier::contact::resolve_object(const configuration::contact& obj) { if (itt != commands::command::commands.end()) ct_it->second->get_service_notification_commands().push_back(itt->second); else { - ++config_errors; + ++err.config_errors; throw(engine_error() << "Could not add service notification command '" << *it << "' to contact '" << obj.contact_name() << "': the command does not exist"); @@ -423,5 +424,5 @@ void applier::contact::resolve_object(const configuration::contact& obj) { ct_it->second->get_parent_groups().clear(); // Resolve contact. - ct_it->second->resolve(config_warnings, config_errors); + ct_it->second->resolve(err.config_warnings, err.config_errors); } diff --git a/engine/src/configuration/applier/contactgroup.cc b/engine/src/configuration/applier/contactgroup.cc index ebb743a3281..38c8522ccbd 100644 --- a/engine/src/configuration/applier/contactgroup.cc +++ b/engine/src/configuration/applier/contactgroup.cc @@ -199,7 +199,8 @@ void applier::contactgroup::remove_object( * @param[in] obj Contact group object. */ void applier::contactgroup::resolve_object( - configuration::contactgroup const& obj) { + configuration::contactgroup const& obj, + error_cnt& err) { // Logging. engine_logger(logging::dbg_config, logging::more) << "Resolving contact group '" << obj.contactgroup_name() << "'"; @@ -213,7 +214,7 @@ void applier::contactgroup::resolve_object( << "contact group '" << obj.contactgroup_name() << "'"; // Resolve contact group. - it->second->resolve(config_warnings, config_errors); + it->second->resolve(err.config_warnings, err.config_errors); } /** diff --git a/engine/src/configuration/applier/host.cc b/engine/src/configuration/applier/host.cc index 6577915df86..bf0df59a090 100644 --- a/engine/src/configuration/applier/host.cc +++ b/engine/src/configuration/applier/host.cc @@ -460,7 +460,8 @@ void applier::host::remove_object(configuration::host const& obj) { * * @param[in] obj Host object. */ -void applier::host::resolve_object(configuration::host const& obj) { +void applier::host::resolve_object(const configuration::host& obj, + error_cnt& err) { // Logging. engine_logger(logging::dbg_config, logging::more) << "Resolving host '" << obj.host_name() << "'."; @@ -494,7 +495,7 @@ void applier::host::resolve_object(configuration::host const& obj) { it->second->set_total_service_check_interval(0); // Resolve host. - it->second->resolve(config_warnings, config_errors); + it->second->resolve(err.config_warnings, err.config_errors); } /** diff --git a/engine/src/configuration/applier/hostdependency.cc b/engine/src/configuration/applier/hostdependency.cc index 50a071559d1..64cd39262d5 100644 --- a/engine/src/configuration/applier/hostdependency.cc +++ b/engine/src/configuration/applier/hostdependency.cc @@ -224,7 +224,8 @@ void applier::hostdependency::remove_object( * @param[in] obj Hostdependency object. */ void applier::hostdependency::resolve_object( - configuration::hostdependency const& obj) { + configuration::hostdependency const& obj, + error_cnt& err) { // Logging. engine_logger(logging::dbg_config, logging::more) << "Resolving a host dependency."; @@ -238,7 +239,7 @@ void applier::hostdependency::resolve_object( throw engine_error() << "Cannot resolve non-existing host escalation"; // Resolve host dependency. - it->second->resolve(config_warnings, config_errors); + it->second->resolve(err.config_warnings, err.config_errors); } /** diff --git a/engine/src/configuration/applier/hostescalation.cc b/engine/src/configuration/applier/hostescalation.cc index 4337dde13cb..39a09b2e2ba 100644 --- a/engine/src/configuration/applier/hostescalation.cc +++ b/engine/src/configuration/applier/hostescalation.cc @@ -224,7 +224,8 @@ void applier::hostescalation::remove_object( * @param[in] obj Hostescalation object. */ void applier::hostescalation::resolve_object( - configuration::hostescalation const& obj) { + configuration::hostescalation const& obj, + error_cnt& err) { // Logging. engine_logger(logging::dbg_config, logging::more) << "Resolving a host escalation."; @@ -246,7 +247,7 @@ void applier::hostescalation::resolve_object( if (it->second->internal_key() == key && it->second->matches(obj)) { found = true; // Resolve host escalation. - it->second->resolve(config_warnings, config_errors); + it->second->resolve(err.config_warnings, err.config_errors); break; } } diff --git a/engine/src/configuration/applier/hostgroup.cc b/engine/src/configuration/applier/hostgroup.cc index b3b1b8c2303..e304c6b350e 100644 --- a/engine/src/configuration/applier/hostgroup.cc +++ b/engine/src/configuration/applier/hostgroup.cc @@ -190,7 +190,8 @@ void applier::hostgroup::remove_object(configuration::hostgroup const& obj) { * * @param[in] obj Object to resolved. */ -void applier::hostgroup::resolve_object(configuration::hostgroup const& obj) { +void applier::hostgroup::resolve_object(configuration::hostgroup const& obj, + error_cnt& err) { // Logging. engine_logger(logging::dbg_config, logging::more) << "Resolving host group '" << obj.hostgroup_name() << "'"; @@ -203,7 +204,7 @@ void applier::hostgroup::resolve_object(configuration::hostgroup const& obj) { << "host group '" << obj.hostgroup_name() << "'"; // Resolve host group. - it->second->resolve(config_warnings, config_errors); + it->second->resolve(err.config_warnings, err.config_errors); } /** diff --git a/engine/src/configuration/applier/scheduler.cc b/engine/src/configuration/applier/scheduler.cc index c28f7812ce4..2b05898ba13 100644 --- a/engine/src/configuration/applier/scheduler.cc +++ b/engine/src/configuration/applier/scheduler.cc @@ -161,25 +161,19 @@ void applier::scheduler::apply( // Check if we need to add or modify objects into the scheduler. if (!hst_to_schedule.empty() || !svc_to_schedule.empty() || !ad_to_schedule.empty()) { - // Reset scheduling info. - // Keep data that has been set manually by the user - // (service interleave and intercheck delays). - int old_service_leave_factor = scheduling_info.service_interleave_factor; - double old_service_inter_check_delay = - scheduling_info.service_inter_check_delay; - double old_host_inter_check_delay_method = - scheduling_info.host_inter_check_delay; memset(&scheduling_info, 0, sizeof(scheduling_info)); if (config.service_interleave_factor_method() == configuration::state::ilf_user) - scheduling_info.service_interleave_factor = old_service_leave_factor; + scheduling_info.service_interleave_factor = + config.sched_info_config().service_interleave_factor; if (config.service_inter_check_delay_method() == configuration::state::icd_user) - scheduling_info.service_inter_check_delay = old_service_inter_check_delay; + scheduling_info.service_inter_check_delay = + config.sched_info_config().service_inter_check_delay; if (config.host_inter_check_delay_method() == configuration::state::icd_user) scheduling_info.host_inter_check_delay = - old_host_inter_check_delay_method; + config.sched_info_config().host_inter_check_delay; // Calculate scheduling parameters. _calculate_host_scheduling_params(); diff --git a/engine/src/configuration/applier/service.cc b/engine/src/configuration/applier/service.cc index 76d915b9ad6..7cdeb69ea28 100644 --- a/engine/src/configuration/applier/service.cc +++ b/engine/src/configuration/applier/service.cc @@ -22,6 +22,7 @@ #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/config.hh" #include "com/centreon/engine/configuration/applier/scheduler.hh" +#include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/downtimes/downtime_manager.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" @@ -547,7 +548,8 @@ void applier::service::remove_object(configuration::service const& obj) { * * @param[in] obj Service object. */ -void applier::service::resolve_object(configuration::service const& obj) { +void applier::service::resolve_object(configuration::service const& obj, + error_cnt& err) { // Logging. engine_logger(logging::dbg_config, logging::more) << "Resolving service '" << obj.service_description() << "' of host '" @@ -575,7 +577,7 @@ void applier::service::resolve_object(configuration::service const& obj) { } // Resolve service. - it->second->resolve(config_warnings, config_errors); + it->second->resolve(err.config_warnings, err.config_errors); } /** diff --git a/engine/src/configuration/applier/servicedependency.cc b/engine/src/configuration/applier/servicedependency.cc index c256b3e8303..777334486f8 100644 --- a/engine/src/configuration/applier/servicedependency.cc +++ b/engine/src/configuration/applier/servicedependency.cc @@ -264,7 +264,8 @@ void applier::servicedependency::remove_object( * @param[in] obj Servicedependency object. */ void applier::servicedependency::resolve_object( - configuration::servicedependency const& obj) { + const configuration::servicedependency& obj, + error_cnt& err) { // Logging. engine_logger(logging::dbg_config, logging::more) << "Resolving a service dependency."; @@ -277,7 +278,7 @@ void applier::servicedependency::resolve_object( throw engine_error() << "Cannot resolve non-existing service dependency"; // Resolve service dependency. - it->second->resolve(config_warnings, config_errors); + it->second->resolve(err.config_warnings, err.config_errors); } /** diff --git a/engine/src/configuration/applier/serviceescalation.cc b/engine/src/configuration/applier/serviceescalation.cc index 0141abb6f49..fb1eee822c6 100644 --- a/engine/src/configuration/applier/serviceescalation.cc +++ b/engine/src/configuration/applier/serviceescalation.cc @@ -239,7 +239,8 @@ void applier::serviceescalation::remove_object( * @param[in] obj Serviceescalation object. */ void applier::serviceescalation::resolve_object( - configuration::serviceescalation const& obj) { + configuration::serviceescalation const& obj, + error_cnt& err) { // Logging. engine_logger(logging::dbg_config, logging::more) << "Resolving a service escalation."; @@ -260,7 +261,7 @@ void applier::serviceescalation::resolve_object( if (it->second->internal_key() == key && it->second->matches(obj)) { found = true; // Resolve service escalation. - it->second->resolve(config_warnings, config_errors); + it->second->resolve(err.config_warnings, err.config_errors); break; } } diff --git a/engine/src/configuration/applier/servicegroup.cc b/engine/src/configuration/applier/servicegroup.cc index 2f18c2ae047..8f8e42bf855 100644 --- a/engine/src/configuration/applier/servicegroup.cc +++ b/engine/src/configuration/applier/servicegroup.cc @@ -214,7 +214,8 @@ void applier::servicegroup::remove_object( * @param[in,out] obj Servicegroup object. */ void applier::servicegroup::resolve_object( - configuration::servicegroup const& obj) { + configuration::servicegroup const& obj, + error_cnt& err) { // Logging. engine_logger(logging::dbg_config, logging::more) << "Removing service group '" << obj.servicegroup_name() << "'"; @@ -228,7 +229,7 @@ void applier::servicegroup::resolve_object( << "service group '" << obj.servicegroup_name() << "'"; // Resolve service group. - it->second->resolve(config_warnings, config_errors); + it->second->resolve(err.config_warnings, err.config_errors); } /** diff --git a/engine/src/configuration/applier/state.cc b/engine/src/configuration/applier/state.cc index 6c338127ab3..0fe5e5c5e00 100644 --- a/engine/src/configuration/applier/state.cc +++ b/engine/src/configuration/applier/state.cc @@ -45,14 +45,10 @@ #include "com/centreon/engine/configuration/applier/timeperiod.hh" #include "com/centreon/engine/configuration/command.hh" #include "com/centreon/engine/configuration/whitelist.hh" -#include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/logging.hh" #include "com/centreon/engine/logging/broker_sink.hh" #include "com/centreon/engine/logging/logger.hh" -#include "com/centreon/engine/objects.hh" #include "com/centreon/engine/retention/applier/state.hh" -#include "com/centreon/engine/retention/state.hh" #include "com/centreon/engine/version.hh" #include "com/centreon/engine/xpddefault.hh" #include "com/centreon/engine/xsddefault.hh" @@ -71,47 +67,16 @@ static bool has_already_been_loaded(false); * Apply new configuration. * * @param[in] new_cfg The new configuration. - * @param[in] waiting_thread True to wait thread after calulate differencies. - */ -void applier::state::apply(configuration::state& new_cfg) { - configuration::state save(*config); - try { - _processing_state = state_ready; - _processing(new_cfg); - } catch (std::exception const& e) { - // If is the first time to load configuration, we don't - // have a valid configuration to restore. - if (!has_already_been_loaded) - throw; - - // If is not the first time, we can restore the old one. - engine_logger(log_config_error, basic) - << "Error: Could not apply new configuration: " << e.what(); - config_logger->error("Error: Could not apply new configuration: {}", - e.what()); - - // Check if we need to restore old configuration. - if (_processing_state == state_error) { - engine_logger(dbg_config, more) - << "configuration: try to restore old configuration"; - config_logger->debug("configuration: try to restore old configuration"); - _processing(save); - } - } -} - -/** - * Apply new configuration. - * - * @param[in] new_cfg The new configuration. + * @param[out] err The configuration error counter. * @param[in] state The retention to use. */ void applier::state::apply(configuration::state& new_cfg, - retention::state& state) { + error_cnt& err, + retention::state* state) { configuration::state save(*config); try { _processing_state = state_ready; - _processing(new_cfg, &state); + _processing(new_cfg, err, state); } catch (std::exception const& e) { // If is the first time to load configuration, we don't // have a valid configuration to restore. @@ -128,7 +93,7 @@ void applier::state::apply(configuration::state& new_cfg, engine_logger(dbg_config, more) << "configuration: try to restore old configuration"; config_logger->debug("configuration: try to restore old configuration"); - _processing(save, &state); + _processing(save, err, state); } } } @@ -247,7 +212,8 @@ void applier::state::unlock() { * * @param[in] new_cfg The new configuration state. */ -void applier::state::_apply(configuration::state const& new_cfg) { +void applier::state::_apply(configuration::state const& new_cfg, + error_cnt& err) { // Check variables should not be change after the first execution. if (has_already_been_loaded) { if (config->broker_module() != new_cfg.broker_module()) { @@ -255,20 +221,20 @@ void applier::state::_apply(configuration::state const& new_cfg) { << "Warning: Broker modules cannot be changed nor reloaded"; config_logger->warn( "Warning: Broker modules cannot be changed nor reloaded"); - ++config_warnings; + ++err.config_warnings; } if (config->broker_module_directory() != new_cfg.broker_module_directory()) { engine_logger(log_config_warning, basic) << "Warning: Broker module directory cannot be changed"; config_logger->warn("Warning: Broker module directory cannot be changed"); - ++config_warnings; + ++err.config_warnings; } if (config->command_file() != new_cfg.command_file()) { engine_logger(log_config_warning, basic) << "Warning: Command file cannot be changed"; config_logger->warn("Warning: Command file cannot be changed"); - ++config_warnings; + ++err.config_warnings; } if (config->external_command_buffer_slots() != new_cfg.external_command_buffer_slots()) { @@ -276,13 +242,13 @@ void applier::state::_apply(configuration::state const& new_cfg) { << "Warning: External command buffer slots cannot be changed"; config_logger->warn( "Warning: External command buffer slots cannot be changed"); - ++config_warnings; + ++err.config_warnings; } if (config->use_timezone() != new_cfg.use_timezone()) { engine_logger(log_config_warning, basic) << "Warning: Timezone can not be changed"; config_logger->warn("Warning: Timezone can not be changed"); - ++config_warnings; + ++err.config_warnings; } } @@ -503,7 +469,7 @@ void applier::state::_apply(configuration::state const& new_cfg) { "Error: Global host event handler command '{}' is not defined " "anywhere!", temp_command_name); - ++config_errors; + ++err.config_errors; global_host_event_handler_ptr = nullptr; } else global_host_event_handler_ptr = found->second.get(); @@ -522,7 +488,7 @@ void applier::state::_apply(configuration::state const& new_cfg) { "Error: Global service event handler command '{}' is not defined " "anywhere!", temp_command_name); - ++config_errors; + ++err.config_errors; global_service_event_handler_ptr = nullptr; } else global_service_event_handler_ptr = found->second.get(); @@ -547,7 +513,7 @@ void applier::state::_apply(configuration::state const& new_cfg) { "Error: Obsessive compulsive service processor command '{}' is not " "defined anywhere!", temp_command_name); - ++config_errors; + ++err.config_errors; ocsp_command_ptr = nullptr; } else ocsp_command_ptr = found->second.get(); @@ -565,7 +531,7 @@ void applier::state::_apply(configuration::state const& new_cfg) { "Error: Obsessive compulsive host processor command '{}' is not " "defined anywhere!", temp_command_name); - ++config_errors; + ++err.config_errors; ochp_command_ptr = nullptr; } else ochp_command_ptr = found->second.get(); @@ -585,7 +551,8 @@ void applier::state::_apply(configuration::state const& new_cfg) { */ template void applier::state::_apply( - difference > const& diff) { + difference > const& diff, + error_cnt& err) { // Type alias. typedef std::set cfg_set; @@ -606,7 +573,7 @@ void applier::state::_apply( try { aplyr.remove_object(*it_delete); } catch (std::exception const& e) { - ++config_errors; + ++err.config_errors; engine_logger(log_info_message, basic) << e.what(); events_logger->info(e.what()); } @@ -623,7 +590,7 @@ void applier::state::_apply( try { aplyr.add_object(*it_create); } catch (std::exception const& e) { - ++config_errors; + ++err.config_errors; engine_logger(log_info_message, basic) << e.what(); events_logger->info(e.what()); } @@ -640,7 +607,7 @@ void applier::state::_apply( try { aplyr.modify_object(*it_modify); } catch (std::exception const& e) { - ++config_errors; + ++err.config_errors; engine_logger(log_info_message, basic) << e.what(); events_logger->info(e.what()); } @@ -1216,7 +1183,8 @@ void applier::state::apply_log_config(configuration::state& new_cfg) { * @param[in] state The retention state to use. */ void applier::state::_apply(configuration::state& new_cfg, - retention::state& state) { + retention::state& state, + error_cnt& err) { retention::applier::state app_state; if (!verify_config) app_state.apply(new_cfg, state); @@ -1224,7 +1192,7 @@ void applier::state::_apply(configuration::state& new_cfg, try { app_state.apply(new_cfg, state); } catch (std::exception const& e) { - ++config_errors; + ++err.config_errors; std::cout << e.what(); } } @@ -1237,13 +1205,13 @@ void applier::state::_apply(configuration::state& new_cfg, * @param[in,out] cfg Configuration objects. */ template -void applier::state::_expand(configuration::state& new_state) { +void applier::state::_expand(configuration::state& new_state, error_cnt& err) { ApplierType aplyr; try { aplyr.expand_objects(new_state); } catch (std::exception const& e) { if (verify_config) { - ++config_errors; + ++err.config_errors; std::cout << e.what(); } else throw; @@ -1254,9 +1222,11 @@ void applier::state::_expand(configuration::state& new_state) { * Process new configuration and apply it. * * @param[in] new_cfg The new configuration. + * @param[out] err The configuration error counter. * @param[in] state The retention to use. */ void applier::state::_processing(configuration::state& new_cfg, + error_cnt& err, retention::state* state) { // Timing. struct timeval tv[5]; @@ -1271,48 +1241,49 @@ void applier::state::_processing(configuration::state& new_cfg, gettimeofday(tv, nullptr); // Expand timeperiods. - _expand(new_cfg); + _expand(new_cfg, err); // Expand connectors. - _expand(new_cfg); + _expand(new_cfg, err); // Expand commands. - _expand(new_cfg); + _expand(new_cfg, err); // Expand contacts. - _expand(new_cfg); + _expand(new_cfg, err); // Expand contactgroups. - _expand(new_cfg); + _expand(new_cfg, err); // Expand hosts. - _expand(new_cfg); + _expand(new_cfg, err); // Expand hostgroups. - _expand(new_cfg); + _expand(new_cfg, err); // Expand services. - _expand(new_cfg); + _expand(new_cfg, err); // Expand anomalydetections. - _expand(new_cfg); + _expand(new_cfg, + err); // Expand servicegroups. - _expand(new_cfg); + _expand(new_cfg, err); // Expand hostdependencies. - _expand(new_cfg); + _expand(new_cfg, err); // Expand servicedependencies. - _expand( - new_cfg); + _expand(new_cfg, + err); // Expand hostescalations. - _expand(new_cfg); + _expand(new_cfg, err); // Expand serviceescalations. - _expand( - new_cfg); + _expand(new_cfg, + err); // // Build difference for all objects. @@ -1431,87 +1402,89 @@ void applier::state::_processing(configuration::state& new_cfg, // // Apply timeperiods. - _apply(diff_timeperiods); + _apply(diff_timeperiods, + err); _resolve( - config->timeperiods()); + config->timeperiods(), err); // Apply connectors. - _apply(diff_connectors); - _resolve( - config->connectors()); + _apply(diff_connectors, err); + _resolve(config->connectors(), + err); // Apply commands. - _apply(diff_commands); - _resolve(config->commands()); + _apply(diff_commands, err); + _resolve(config->commands(), err); // Apply contacts and contactgroups. - _apply(diff_contacts); + _apply(diff_contacts, err); _apply( - diff_contactgroups); + diff_contactgroups, err); _resolve( - config->contactgroups()); - _resolve(config->contacts()); + config->contactgroups(), err); + _resolve(config->contacts(), err); // Apply severities. - _apply(diff_severities); + _apply(diff_severities, err); // Apply tags. - _apply(diff_tags); + _apply(diff_tags, err); // Apply hosts and hostgroups. - _apply(diff_hosts); - _apply(diff_hostgroups); + _apply(diff_hosts, err); + _apply(diff_hostgroups, err); // Apply services. - _apply(diff_services); + _apply(diff_services, err); // Apply anomalydetections. _apply( - diff_anomalydetections); + diff_anomalydetections, err); // Apply servicegroups. _apply( - diff_servicegroups); + diff_servicegroups, err); // Resolve hosts, services, host groups. - _resolve(config->hosts()); - _resolve( - config->hostgroups()); + _resolve(config->hosts(), err); + _resolve(config->hostgroups(), + err); // Resolve services. - _resolve(config->mut_services()); + _resolve(config->mut_services(), + err); // Resolve anomalydetections. _resolve( - config->anomalydetections()); + config->anomalydetections(), err); // Resolve service groups. _resolve( - config->servicegroups()); + config->servicegroups(), err); // Apply host dependencies. _apply( - diff_hostdependencies); + diff_hostdependencies, err); _resolve( - config->hostdependencies()); + config->hostdependencies(), err); // Apply service dependencies. _apply( - diff_servicedependencies); + diff_servicedependencies, err); _resolve( - config->servicedependencies()); + config->servicedependencies(), err); // Apply host escalations. _apply( - diff_hostescalations); + diff_hostescalations, err); _resolve( - config->hostescalations()); + config->hostescalations(), err); // Apply service escalations. _apply( - diff_serviceescalations); + diff_serviceescalations, err); _resolve( - config->serviceescalations()); + config->serviceescalations(), err); #ifdef DEBUG_CONFIG std::cout << "WARNING!! You are using a version of " @@ -1528,7 +1501,7 @@ void applier::state::_processing(configuration::state& new_cfg, // Load retention. if (state) - _apply(new_cfg, *state); + _apply(new_cfg, *state, err); // Apply scheduler. if (!verify_config) @@ -1537,13 +1510,13 @@ void applier::state::_processing(configuration::state& new_cfg, // Apply new global on the current state. if (!verify_config) { - _apply(new_cfg); + _apply(new_cfg, err); whitelist::reload(); } else { try { - _apply(new_cfg); + _apply(new_cfg, err); } catch (std::exception const& e) { - ++config_errors; + ++err.config_errors; engine_logger(log_info_message, basic) << e.what(); events_logger->info(e.what()); } @@ -1553,7 +1526,7 @@ void applier::state::_processing(configuration::state& new_cfg, gettimeofday(tv + 3, nullptr); // Check for circular paths between hosts. - pre_flight_circular_check(&config_warnings, &config_errors); + pre_flight_circular_check(&err.config_warnings, &err.config_errors); // Call start broker event the first time to run applier state. if (!has_already_been_loaded) { @@ -1633,16 +1606,17 @@ void applier::state::_processing(configuration::state& new_cfg, * @param[in] cfg Configuration objects. */ template -void applier::state::_resolve(std::set& cfg) { +void applier::state::_resolve(std::set& cfg, + error_cnt& err) { ApplierType aplyr; - for (typename std::set::const_iterator it(cfg.begin()), - end(cfg.end()); + for (typename std::set::const_iterator it = cfg.begin(), + end = cfg.end(); it != end; ++it) { try { - aplyr.resolve_object(*it); + aplyr.resolve_object(*it, err); } catch (std::exception const& e) { if (verify_config) { - ++config_errors; + ++err.config_errors; std::cout << e.what() << std::endl; } else throw; diff --git a/engine/src/configuration/applier/timeperiod.cc b/engine/src/configuration/applier/timeperiod.cc index 3140a879660..df738fc3bee 100644 --- a/engine/src/configuration/applier/timeperiod.cc +++ b/engine/src/configuration/applier/timeperiod.cc @@ -167,7 +167,8 @@ void applier::timeperiod::remove_object(configuration::timeperiod const& obj) { * * @param[in] obj Unused. */ -void applier::timeperiod::resolve_object(configuration::timeperiod const& obj) { +void applier::timeperiod::resolve_object(configuration::timeperiod const& obj, + error_cnt& err) { // Logging. engine_logger(logging::dbg_config, logging::more) << "Resolving time period '" << obj.timeperiod_name() << "'."; @@ -180,7 +181,7 @@ void applier::timeperiod::resolve_object(configuration::timeperiod const& obj) { << "time period '" << obj.timeperiod_name() << "'"; // Resolve time period. - it->second->resolve(config_warnings, config_errors); + it->second->resolve(err.config_warnings, err.config_errors); } /** diff --git a/engine/src/configuration/command.cc b/engine/src/configuration/command.cc index 28bf2b34856..9be403106ba 100644 --- a/engine/src/configuration/command.cc +++ b/engine/src/configuration/command.cc @@ -113,7 +113,7 @@ bool command::operator<(command const& right) const throw() { * * If the object is not valid, an exception is thrown. */ -void command::check_validity() const { +void command::check_validity(error_cnt& err [[maybe_unused]]) const { if (_command_name.empty()) throw msg_fmt("Command has no name (property 'command_name')"); if (_command_line.empty()) diff --git a/engine/src/configuration/connector.cc b/engine/src/configuration/connector.cc index 5f67da8927a..3a26096f0da 100644 --- a/engine/src/configuration/connector.cc +++ b/engine/src/configuration/connector.cc @@ -112,7 +112,7 @@ bool connector::operator<(connector const& right) const throw() { * * If the object is not valid, an exception is thrown. */ -void connector::check_validity() const { +void connector::check_validity(error_cnt& err [[maybe_unused]]) const { if (_connector_name.empty()) throw msg_fmt("Connector has no name (property 'connector_name')"); if (_connector_line.empty()) diff --git a/engine/src/configuration/contact.cc b/engine/src/configuration/contact.cc index 65900b90d60..931d2f02fb4 100644 --- a/engine/src/configuration/contact.cc +++ b/engine/src/configuration/contact.cc @@ -230,7 +230,7 @@ bool contact::operator<(contact const& other) const noexcept { * * If the object is not valid, an exception is thrown. */ -void contact::check_validity() const { +void contact::check_validity(error_cnt& err [[maybe_unused]]) const { if (_contact_name.empty()) throw msg_fmt("Contact has no name (property 'contact_name')"); } diff --git a/engine/src/configuration/contactgroup.cc b/engine/src/configuration/contactgroup.cc index 9e0e4a484c6..178f1ff65ee 100644 --- a/engine/src/configuration/contactgroup.cc +++ b/engine/src/configuration/contactgroup.cc @@ -121,7 +121,7 @@ bool contactgroup::operator<(contactgroup const& right) const throw() { * * If the object is not valid, an exception is thrown. */ -void contactgroup::check_validity() const { +void contactgroup::check_validity(error_cnt& err [[maybe_unused]]) const { if (_contactgroup_name.empty()) throw msg_fmt("Contact group has no name (property 'contactgroup_name')"); } diff --git a/engine/src/configuration/extended_conf.cc b/engine/src/configuration/extended_conf.cc index 84d85c07ca0..a350cf51764 100644 --- a/engine/src/configuration/extended_conf.cc +++ b/engine/src/configuration/extended_conf.cc @@ -18,7 +18,6 @@ #include "com/centreon/engine/configuration/extended_conf.hh" #include "com/centreon/engine/configuration/state.hh" -#include "com/centreon/engine/globals.hh" #include "com/centreon/exceptions/msg_fmt.hh" #include "common/log_v2/log_v2.hh" diff --git a/engine/src/configuration/host.cc b/engine/src/configuration/host.cc index 7d255c874ff..5f3b47c4588 100644 --- a/engine/src/configuration/host.cc +++ b/engine/src/configuration/host.cc @@ -25,9 +25,6 @@ #include "bbdo/neb.pb.h" #include "com/centreon/exceptions/msg_fmt.hh" -extern int config_warnings; -extern int config_errors; - using namespace com::centreon; using namespace com::centreon::engine::configuration; using com::centreon::exceptions::msg_fmt; @@ -52,8 +49,6 @@ std::unordered_map const host::_setters{ {"check_command", SETTER(std::string const&, _set_check_command)}, {"check_period", SETTER(std::string const&, _set_check_period)}, {"event_handler", SETTER(std::string const&, _set_event_handler)}, - {"failure_prediction_options", - SETTER(std::string const&, _set_failure_prediction_options)}, {"notes", SETTER(std::string const&, _set_notes)}, {"notes_url", SETTER(std::string const&, _set_notes_url)}, {"action_url", SETTER(std::string const&, _set_action_url)}, @@ -89,8 +84,6 @@ std::unordered_map const host::_setters{ SETTER(unsigned int, _set_first_notification_delay)}, {"stalking_options", SETTER(std::string const&, _set_stalking_options)}, {"process_perf_data", SETTER(bool, _set_process_perf_data)}, - {"failure_prediction_enabled", - SETTER(bool, _set_failure_prediction_enabled)}, {"2d_coords", SETTER(std::string const&, _set_coords_2d)}, {"3d_coords", SETTER(std::string const&, _set_coords_3d)}, {"obsess_over_host", SETTER(bool, _set_obsess_over_host)}, @@ -430,7 +423,7 @@ bool host::operator<(host const& other) const noexcept { * * If the object is not valid, an exception is thrown. */ -void host::check_validity() const { +void host::check_validity(error_cnt& err [[maybe_unused]]) const { if (_host_name.empty()) throw msg_fmt("Host has no name (property 'host_name')"); if (_address.empty()) @@ -1258,37 +1251,6 @@ bool host::_set_event_handler_enabled(bool value) { return true; } -/** - * Set failure_prediction_enabled value. - * - * @param[in] value The new failure_prediction_enabled value. - * - * @return True on success, otherwise false. - */ -bool host::_set_failure_prediction_enabled(bool value [[maybe_unused]]) { - _logger->warn( - "Warning: host failure_prediction_enabled is deprecated This option will " - "not be supported in 20.04."); - ++config_warnings; - return true; -} - -/** - * Set failure_prediction_options value. - * - * @param[in] value The new failure_prediction_options value. - * - * @return True on success, otherwise false. - */ -bool host::_set_failure_prediction_options(const std::string& value - [[maybe_unused]]) { - _logger->warn( - "Warning: service failure_prediction_options is deprecated This option " - "will not be supported in 20.04."); - ++config_warnings; - return (true); -} - /** * Set first_notification_delay value. * diff --git a/engine/src/configuration/hostdependency.cc b/engine/src/configuration/hostdependency.cc index 5ccf7ddb8aa..5993c8f0166 100644 --- a/engine/src/configuration/hostdependency.cc +++ b/engine/src/configuration/hostdependency.cc @@ -18,13 +18,9 @@ * */ -#include "com/centreon/engine/configuration/hostdependency.hh" -#include "com/centreon/engine/globals.hh" +#include "com/centreon/engine/configuration/state.hh" #include "com/centreon/exceptions/msg_fmt.hh" -extern int config_warnings; -extern int config_errors; - using namespace com::centreon; using namespace com::centreon::engine::configuration; using com::centreon::exceptions::msg_fmt; @@ -181,7 +177,7 @@ bool hostdependency::operator<(hostdependency const& right) const { * * If the object is not valid, an exception is thrown. */ -void hostdependency::check_validity() const { +void hostdependency::check_validity(configuration::error_cnt& err) const { if (_hosts->empty() && _hostgroups->empty()) throw msg_fmt( "Host dependency is not attached to any host or host group (properties " @@ -193,7 +189,7 @@ void hostdependency::check_validity() const { "'dependent_hostgroup_name', respectively)"); if (!_execution_failure_options && !_notification_failure_options) { - ++config_warnings; + ++err.config_warnings; std::string host_name(!_hosts->empty() ? *_hosts->begin() : *_hostgroups->begin()); std::string dependend_host_name(!_dependent_hosts->empty() diff --git a/engine/src/configuration/hostescalation.cc b/engine/src/configuration/hostescalation.cc index 8c9853c99b6..24df969ace6 100644 --- a/engine/src/configuration/hostescalation.cc +++ b/engine/src/configuration/hostescalation.cc @@ -162,7 +162,7 @@ bool hostescalation::operator<(hostescalation const& right) const { * * If the object is not valid, an exception is thrown. */ -void hostescalation::check_validity() const { +void hostescalation::check_validity(error_cnt& err [[maybe_unused]]) const { if (_hosts->empty() && _hostgroups->empty()) throw msg_fmt( "Host escalation is not attached to any host or host group (properties " diff --git a/engine/src/configuration/hostgroup.cc b/engine/src/configuration/hostgroup.cc index b8ea44beccd..7182bb2cdc2 100644 --- a/engine/src/configuration/hostgroup.cc +++ b/engine/src/configuration/hostgroup.cc @@ -167,7 +167,7 @@ bool hostgroup::operator<(hostgroup const& right) const throw() { * * If the object is not valid, an exception is thrown. */ -void hostgroup::check_validity() const { +void hostgroup::check_validity(error_cnt& err [[maybe_unused]]) const { if (_hostgroup_name.empty()) throw msg_fmt("Host group has no name (property 'hostgroup_name')"); } diff --git a/engine/src/configuration/parser.cc b/engine/src/configuration/parser.cc index d893b3665e1..f5e737873e1 100644 --- a/engine/src/configuration/parser.cc +++ b/engine/src/configuration/parser.cc @@ -17,7 +17,6 @@ * */ #include "com/centreon/engine/configuration/parser.hh" -#include "com/centreon/engine/globals.hh" #include "com/centreon/exceptions/msg_fmt.hh" #include "com/centreon/io/directory_entry.hh" #include "common/log_v2/log_v2.hh" @@ -89,7 +88,7 @@ parser::parser(unsigned int read_options) * @param[in] path The configuration file path. * @param[in] config The state configuration to fill. */ -void parser::parse(std::string const& path, state& config) { +void parser::parse(std::string const& path, state& config, error_cnt& err) { _config = &config; // parse the global configuration file. @@ -103,7 +102,7 @@ void parser::parse(std::string const& path, state& config) { _apply(config.cfg_dir(), &parser::_parse_directory_configuration); // Apply template. - _resolve_template(); + _resolve_template(err); // Fill state. _insert(_map_objects[object::command], config.commands()); @@ -455,7 +454,7 @@ void parser::_parse_resource_file(std::string const& path) { /** * Resolve template for register objects. */ -void parser::_resolve_template() { +void parser::_resolve_template(error_cnt& err) { for (map_object& templates : _templates) { for (map_object::iterator it = templates.begin(), end = templates.end(); it != end; ++it) @@ -469,7 +468,7 @@ void parser::_resolve_template() { it != end; ++it) { (*it)->resolve_template(templates); try { - (*it)->check_validity(); + (*it)->check_validity(err); } catch (std::exception const& e) { throw msg_fmt("Configuration parsing failed {}: {}", _get_file_info(it->get()), e.what()); @@ -484,7 +483,7 @@ void parser::_resolve_template() { it != end; ++it) { it->second->resolve_template(templates); try { - it->second->check_validity(); + it->second->check_validity(err); } catch (std::exception const& e) { throw msg_fmt("Configuration parsing failed {}: {}", _get_file_info(it->second.get()), e.what()); diff --git a/engine/src/configuration/service.cc b/engine/src/configuration/service.cc index 916eddbae91..73efe5d04e7 100644 --- a/engine/src/configuration/service.cc +++ b/engine/src/configuration/service.cc @@ -21,13 +21,9 @@ #include #include #include -#include "com/centreon/engine/globals.hh" #include "com/centreon/engine/host.hh" #include "com/centreon/exceptions/msg_fmt.hh" -extern int config_warnings; -extern int config_errors; - using namespace com::centreon; using namespace com::centreon::engine::configuration; using com::centreon::exceptions::msg_fmt; @@ -55,8 +51,6 @@ std::unordered_map const service::_setters{ SETTER(std::string const&, _set_notification_period)}, {"contact_groups", SETTER(std::string const&, _set_contactgroups)}, {"contacts", SETTER(std::string const&, _set_contacts)}, - {"failure_prediction_options", - SETTER(std::string const&, _set_failure_prediction_options)}, {"notes", SETTER(std::string const&, _set_notes)}, {"notes_url", SETTER(std::string const&, _set_notes_url)}, {"action_url", SETTER(std::string const&, _set_action_url)}, @@ -72,7 +66,6 @@ std::unordered_map const service::_setters{ SETTER(unsigned int, _set_recovery_notification_delay)}, {"active_checks_enabled", SETTER(bool, _set_checks_active)}, {"passive_checks_enabled", SETTER(bool, _set_checks_passive)}, - {"parallelize_check", SETTER(bool, _set_parallelize_check)}, {"is_volatile", SETTER(bool, _set_is_volatile)}, {"obsess_over_service", SETTER(bool, _set_obsess_over_service)}, {"event_handler_enabled", SETTER(bool, _set_event_handler_enabled)}, @@ -91,8 +84,6 @@ std::unordered_map const service::_setters{ SETTER(unsigned int, _set_first_notification_delay)}, {"stalking_options", SETTER(std::string const&, _set_stalking_options)}, {"process_perf_data", SETTER(bool, _set_process_perf_data)}, - {"failure_prediction_enabled", - SETTER(bool, _set_failure_prediction_enabled)}, {"retain_status_information", SETTER(bool, _set_retain_status_information)}, {"retain_nonstatus_information", SETTER(bool, _set_retain_nonstatus_information)}, @@ -676,7 +667,7 @@ bool service::operator<(service const& other) const noexcept { * * @return True if is a valid object, otherwise false. */ -void service::check_validity() const { +void service::check_validity(error_cnt& err [[maybe_unused]]) const { if (_service_description.empty()) throw msg_fmt( "Service has no description (property 'service_description')"); @@ -1481,38 +1472,6 @@ bool service::_set_event_handler_enabled(bool value) { return true; } -/** - * Set failure_prediction_enabled value. - * - * @param[in] value The new failure_prediction_enabled value. - * - * @return True on success, otherwise false. - */ -bool service::_set_failure_prediction_enabled(bool value) { - (void)value; - _logger->warn( - "Warning: service failure_prediction_enabled is deprecated. This option " - "will not be supported in 20.04."); - ++config_warnings; - return true; -} - -/** - * Set failure_prediction_options value. - * - * @param[in] value The new failure_prediction_options value. - * - * @return True on success, otherwise false. - */ -bool service::_set_failure_prediction_options(std::string const& value) { - (void)value; - _logger->warn( - "Warning: service failure_prediction_options is deprecated. This option " - "will not be supported in 20.04."); - ++config_warnings; - return true; -} - /** * Set first_notification_delay value. * @@ -1796,22 +1755,6 @@ bool service::_set_obsess_over_service(bool value) { return true; } -/** - * Set parallelize_check value. - * - * @param[in] value The new parallelize_check value. - * - * @return True on success, otherwise false. - */ -bool service::_set_parallelize_check(bool value) { - (void)value; - _logger->warn( - "Warning: service parallelize_check is deprecated This option will not " - "be supported in 20.04."); - ++config_warnings; - return true; -} - /** * Set process_perf_data value. * diff --git a/engine/src/configuration/servicedependency.cc b/engine/src/configuration/servicedependency.cc index 98f00491d1a..1f70031d1a7 100644 --- a/engine/src/configuration/servicedependency.cc +++ b/engine/src/configuration/servicedependency.cc @@ -19,12 +19,8 @@ */ #include "com/centreon/engine/configuration/servicedependency.hh" -#include "com/centreon/engine/globals.hh" #include "com/centreon/exceptions/msg_fmt.hh" -extern int config_warnings; -extern int config_errors; - using namespace com::centreon; using namespace com::centreon::engine::configuration; using com::centreon::exceptions::msg_fmt; @@ -230,7 +226,7 @@ bool servicedependency::operator<(servicedependency const& right) const { * * If the object is not valid, an exception is thrown. */ -void servicedependency::check_validity() const { +void servicedependency::check_validity(error_cnt& err) const { // Check base service(s). if (_servicegroups->empty()) { if (_service_description->empty()) @@ -260,7 +256,7 @@ void servicedependency::check_validity() const { // With no execution or failure options this dependency is useless. if (!_execution_failure_options && !_notification_failure_options) { - ++config_warnings; + ++err.config_warnings; std::ostringstream msg; msg << "Warning: Ignoring lame service dependency of "; if (!_dependent_servicegroups->empty()) diff --git a/engine/src/configuration/serviceescalation.cc b/engine/src/configuration/serviceescalation.cc index 4cf59dcb8f5..f41fc9a3571 100644 --- a/engine/src/configuration/serviceescalation.cc +++ b/engine/src/configuration/serviceescalation.cc @@ -18,7 +18,6 @@ */ #include "com/centreon/engine/configuration/serviceescalation.hh" -#include "com/centreon/engine/globals.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon; @@ -238,7 +237,7 @@ bool serviceescalation::operator<(serviceescalation const& right) const { * * If the object is not valid, an exception is thrown. */ -void serviceescalation::check_validity() const { +void serviceescalation::check_validity(error_cnt& err [[maybe_unused]]) const { if (_servicegroups->empty()) { if (_service_description->empty()) throw msg_fmt( diff --git a/engine/src/configuration/servicegroup.cc b/engine/src/configuration/servicegroup.cc index c15dceb50bf..39ff98ffe09 100644 --- a/engine/src/configuration/servicegroup.cc +++ b/engine/src/configuration/servicegroup.cc @@ -141,7 +141,7 @@ bool servicegroup::operator<(servicegroup const& right) const throw() { * * If the object is not valid, an exception is thrown. */ -void servicegroup::check_validity() const { +void servicegroup::check_validity(error_cnt& err [[maybe_unused]]) const { if (_servicegroup_name.empty()) throw msg_fmt("Service group has no name (property 'servicegroup_name')"); } diff --git a/engine/src/configuration/severity.cc b/engine/src/configuration/severity.cc index 3ec4ace32e5..6df971be114 100644 --- a/engine/src/configuration/severity.cc +++ b/engine/src/configuration/severity.cc @@ -129,7 +129,7 @@ bool severity::operator<(const severity& other) const noexcept { * * If the object is not valid, an exception is thrown. */ -void severity::check_validity() const { +void severity::check_validity(error_cnt& err [[maybe_unused]]) const { if (_severity_name.empty()) throw msg_fmt("Severity has no name (property 'severity_name')"); if (_key.first == 0) diff --git a/engine/src/configuration/state.cc b/engine/src/configuration/state.cc index 47eb38de128..2ee1415a225 100644 --- a/engine/src/configuration/state.cc +++ b/engine/src/configuration/state.cc @@ -19,10 +19,9 @@ #include "com/centreon/engine/configuration/state.hh" #include "com/centreon/common/rapidjson_helper.hh" #include "com/centreon/engine/broker.hh" -#include "com/centreon/engine/globals.hh" #include "com/centreon/exceptions/msg_fmt.hh" #include "com/centreon/io/file_entry.hh" -#include "compatibility/locations.h" +#include "common/log_v2/log_v2.hh" using namespace com::centreon; using namespace com::centreon::engine; @@ -137,16 +136,12 @@ void state::_init_setter() { SETTER(int, additional_freshness_latency, "additional_freshness_latency"); SETTER(const std::string&, admin_email, "admin_email"); SETTER(const std::string&, admin_pager, "admin_pager"); - SETTER(const std::string&, _set_aggregate_status_updates, - "aggregate_status_updates"); SETTER(bool, allow_empty_hostgroup_assignment, "allow_empty_hostgroup_assignment"); - SETTER(const std::string&, _set_auth_file, "auth_file"); SETTER(bool, auto_reschedule_checks, "auto_reschedule_checks"); SETTER(unsigned int, auto_rescheduling_interval, "auto_rescheduling_interval"); SETTER(unsigned int, auto_rescheduling_window, "auto_rescheduling_window"); - SETTER(const std::string&, _set_bare_update_check, "bare_update_check"); SETTER(const std::string&, broker_module_directory, "broker_module_directory"); SETTER(const std::string&, _set_broker_module, "broker_module"); @@ -158,27 +153,18 @@ void state::_init_setter() { SETTER(bool, check_external_commands, "check_external_commands"); SETTER(bool, check_orphaned_hosts, "check_for_orphaned_hosts"); SETTER(bool, check_orphaned_services, "check_for_orphaned_services"); - SETTER(const std::string&, _set_check_for_updates, "check_for_updates"); SETTER(bool, check_host_freshness, "check_host_freshness"); SETTER(unsigned int, check_reaper_interval, "check_result_reaper_frequency"); SETTER(bool, check_service_freshness, "check_service_freshness"); - SETTER(const std::string&, _set_child_processes_fork_twice, - "child_processes_fork_twice"); SETTER(const std::string&, _set_command_check_interval, "command_check_interval"); SETTER(const std::string&, command_file, "command_file"); - SETTER(const std::string&, _set_comment_file, "comment_file"); - SETTER(const std::string&, _set_daemon_dumps_core, "daemon_dumps_core"); SETTER(const std::string&, _set_date_format, "date_format"); SETTER(const std::string&, debug_file, "debug_file"); SETTER(int64_t, debug_level, "debug_level"); SETTER(unsigned int, debug_verbosity, "debug_verbosity"); - SETTER(const std::string&, _set_downtime_file, "downtime_file"); - SETTER(const std::string&, _set_enable_embedded_perl, "enable_embedded_perl"); SETTER(bool, enable_environment_macros, "enable_environment_macros"); SETTER(bool, enable_event_handlers, "enable_event_handlers"); - SETTER(const std::string&, _set_enable_failure_prediction, - "enable_failure_prediction"); SETTER(bool, enable_flap_detection, "enable_flap_detection"); SETTER(bool, enable_macros_filter, "enable_macros_filter"); SETTER(bool, enable_notifications, "enable_notifications"); @@ -191,8 +177,6 @@ void state::_init_setter() { SETTER(bool, execute_host_checks, "execute_host_checks"); SETTER(bool, execute_service_checks, "execute_service_checks"); SETTER(int, external_command_buffer_slots, "external_command_buffer_slots"); - SETTER(const std::string&, _set_free_child_process_memory, - "free_child_process_memory"); SETTER(const std::string&, global_host_event_handler, "global_host_event_handler"); SETTER(const std::string&, global_service_event_handler, @@ -218,18 +202,14 @@ void state::_init_setter() { "illegal_macro_output_chars"); SETTER(const std::string&, illegal_object_chars, "illegal_object_name_chars"); SETTER(unsigned int, interval_length, "interval_length"); - SETTER(const std::string&, _set_lock_file, "lock_file"); - SETTER(const std::string&, _set_log_archive_path, "log_archive_path"); SETTER(bool, log_event_handlers, "log_event_handlers"); SETTER(bool, log_external_commands, "log_external_commands"); SETTER(const std::string&, log_file, "log_file"); SETTER(bool, log_host_retries, "log_host_retries"); - SETTER(const std::string&, _set_log_initial_states, "log_initial_states"); SETTER(bool, log_notifications, "log_notifications"); SETTER(bool, log_passive_checks, "log_passive_checks"); SETTER(bool, log_pid, "log_pid"); SETTER(bool, log_file_line, "log_file_line"); - SETTER(const std::string&, _set_log_rotation_method, "log_rotation_method"); SETTER(bool, log_service_retries, "log_service_retries"); SETTER(float, low_host_flap_threshold, "low_host_flap_threshold"); SETTER(float, low_service_flap_threshold, "low_service_flap_threshold"); @@ -240,24 +220,18 @@ void state::_init_setter() { SETTER(unsigned long, max_log_file_size, "max_log_file_size"); SETTER(uint32_t, log_flush_period, "log_flush_period"); SETTER(unsigned int, max_service_check_spread, "max_service_check_spread"); - SETTER(const std::string&, _set_nagios_group, "nagios_group"); - SETTER(const std::string&, _set_nagios_user, "nagios_user"); SETTER(unsigned int, notification_timeout, "notification_timeout"); - SETTER(const std::string&, _set_object_cache_file, "object_cache_file"); SETTER(bool, obsess_over_hosts, "obsess_over_hosts"); SETTER(bool, obsess_over_services, "obsess_over_services"); SETTER(const std::string&, ochp_command, "ochp_command"); SETTER(unsigned int, ochp_timeout, "ochp_timeout"); SETTER(const std::string&, ocsp_command, "ocsp_command"); SETTER(unsigned int, ocsp_timeout, "ocsp_timeout"); - SETTER(const std::string&, _set_p1_file, "p1_file"); SETTER(int, perfdata_timeout, "perfdata_timeout"); SETTER(const std::string&, poller_name, "poller_name"); SETTER(uint32_t, poller_id, "poller_id"); SETTER(uint16_t, rpc_port, "rpc_port"); SETTER(const std::string&, rpc_listen_address, "rpc_listen_address"); - SETTER(const std::string&, _set_precached_object_file, - "precached_object_file"); SETTER(bool, process_performance_data, "process_performance_data"); SETTER(const std::string&, _set_resource_file, "resource_file"); SETTER(unsigned long, retained_contact_host_attribute_mask, @@ -268,10 +242,6 @@ void state::_init_setter() { "retained_host_attribute_mask"); SETTER(unsigned long, retained_process_host_attribute_mask, "retained_process_host_attribute_mask"); - SETTER(const std::string&, _set_retained_process_service_attribute_mask, - "retained_process_service_attribute_mask"); - SETTER(const std::string&, _set_retained_service_attribute_mask, - "retained_service_attribute_mask"); SETTER(bool, retain_state_information, "retain_state_information"); SETTER(unsigned int, retention_scheduling_horizon, "retention_scheduling_horizon"); @@ -300,13 +270,7 @@ void state::_init_setter() { SETTER(const std::string&, state_retention_file, "state_retention_file"); SETTER(const std::string&, status_file, "status_file"); SETTER(unsigned int, status_update_interval, "status_update_interval"); - SETTER(const std::string&, _set_temp_file, "temp_file"); - SETTER(const std::string&, _set_temp_path, "temp_path"); SETTER(unsigned int, time_change_threshold, "time_change_threshold"); - SETTER(bool, use_aggressive_host_checking, "use_aggressive_host_checking"); - SETTER(bool, use_aggressive_host_checking, "use_agressive_host_checking"); - SETTER(const std::string&, _set_use_embedded_perl_implicitly, - "use_embedded_perl_implicitly"); SETTER(bool, use_large_installation_tweaks, "use_large_installation_tweaks"); SETTER(uint32_t, instance_heartbeat_interval, "instance_heartbeat_interval"); SETTER(bool, use_regexp_matches, "use_regexp_matching"); @@ -335,8 +299,6 @@ void state::_init_setter() { SETTER(const std::string&, log_level_otl, "log_level_otl"); SETTER(const std::string&, use_timezone, "use_timezone"); SETTER(bool, use_true_regexp_matching, "use_true_regexp_matching"); - SETTER(const std::string&, _set_comment_file, "xcddefault_comment_file"); - SETTER(const std::string&, _set_downtime_file, "xdddefault_downtime_file"); SETTER(bool, use_send_recovery_notifications_anyways, "send_recovery_notifications_anyways"); SETTER(bool, use_host_down_disable_service_checks, @@ -3786,20 +3748,6 @@ void state::user(unsigned int key, const std::string& value) { _users[fmt::format("{}", key)] = value; } -/** - * Set use_aggressive_host_checking value. This function is still there just - * to warn the user. It should be removed soon. - * - * @param[in] value The new use_aggressive_host_checking value. - */ -void state::use_aggressive_host_checking(bool value __attribute__((unused))) { - _logger->warn( - "Warning: use_aggressive_host_checking is deprecated. This option is " - "no " - "more supported since version 21.04."); - ++config_warnings; -} - /** * Get use_large_installation_tweaks value. * @@ -4313,37 +4261,6 @@ void state::use_true_regexp_matching(bool value) { _use_true_regexp_matching = value; } -/** - * Unused variable aggregate_status_updates. - * - * @param[in] value Unused. - */ -void state::_set_aggregate_status_updates(const std::string& value - [[maybe_unused]]) { - _logger->warn("Warning: aggregate_status_updates variable ignored"); - ++config_warnings; -} - -/** - * Unused variable auth_file. - * - * @param[in] value Unused. - */ -void state::_set_auth_file(const std::string& value [[maybe_unused]]) { - _logger->warn("Warning: auth_file variable ignored"); - ++config_warnings; -} - -/** - * Unused variable bare_update_check. - * - * @param[in] value Unused. - */ -void state::_set_bare_update_check(const std::string& value [[maybe_unused]]) { - _logger->warn("Warning: bare_update_check variable ignored"); - ++config_warnings; -} - /** * Add broker module. * @@ -4383,27 +4300,6 @@ void state::_set_cfg_file(const std::string& value) { } } -/** - * Unused variable check_for_updates. - * - * @param[in] value Unused. - */ -void state::_set_check_for_updates(const std::string& value [[maybe_unused]]) { - _logger->warn("Warning: check_for_updates variable ignored"); - ++config_warnings; -} - -/** - * Unused variable child_processes_fork_twice. - * - * @param[in] value Unused. - */ -void state::_set_child_processes_fork_twice(const std::string& value - [[maybe_unused]]) { - _logger->warn("Warning: child_processes_fork_twice variable ignored"); - ++config_warnings; -} - /** * Set command check interval. * @@ -4422,26 +4318,6 @@ void state::_set_command_check_interval(const std::string& value) { *this, val.c_str()); } -/** - * Unused variable comment_file. - * - * @param[in] value Unused. - */ -void state::_set_comment_file(const std::string& value [[maybe_unused]]) { - _logger->warn("Warning: comment_file variable ignored"); - ++config_warnings; -} - -/** - * Unused variable daemon_dumps_core. - * - * @param[in] value Unused. - */ -void state::_set_daemon_dumps_core(const std::string& value [[maybe_unused]]) { - _logger->warn("Warning: daemon_dumps_core variable ignored"); - ++config_warnings; -} - /** * Set date format. * @@ -4458,38 +4334,6 @@ void state::_set_date_format(const std::string& value) { _date_format = us; } -/** - * Unused variable downtime_file. - * - * @param[in] value Unused. - */ -void state::_set_downtime_file(const std::string& value [[maybe_unused]]) { - _logger->warn("Warning: downtime_file variable ignored"); - ++config_warnings; -} - -/** - * Unused variable enable_embedded_perl. - * - * @param[in] value Unused. - */ -void state::_set_enable_embedded_perl(const std::string& value - [[maybe_unused]]) { - _logger->warn("Warning: enable_embedded_perl variable ignored"); - ++config_warnings; -} - -/** - * Unused variable enable_failure_prediction. - * - * @param[in] value Unused. - */ -void state::_set_enable_failure_prediction(const std::string& value - [[maybe_unused]]) { - _logger->warn("Warning: enable_failure_prediction variable ignored"); - ++config_warnings; -} - /** * Set event_broker_options. * @@ -4504,17 +4348,6 @@ void state::_set_event_broker_options(const std::string& value) { } } -/** - * Unused variable free_child_process_memory. - * - * @param[in] value Unused. - */ -void state::_set_free_child_process_memory(const std::string& value - [[maybe_unused]]) { - _logger->warn("Warning: free_child_process_memory variable ignored"); - ++config_warnings; -} - /** * Set host_inter_check_delay_method. * @@ -4529,8 +4362,8 @@ void state::_set_host_inter_check_delay_method(const std::string& value) { _host_inter_check_delay_method = icd_smart; else { _host_inter_check_delay_method = icd_user; - if (!absl::SimpleAtod(value, &scheduling_info.host_inter_check_delay) || - scheduling_info.host_inter_check_delay <= 0.0) + if (!absl::SimpleAtod(value, &_scheduling_info.host_inter_check_delay) || + _scheduling_info.host_inter_check_delay <= 0.0) throw msg_fmt( "Invalid value for host_inter_check_delay_method, must be one of 'n' " "(none), 'd' (dumb), 's' (smart) or a stricly positive value ({} " @@ -4553,99 +4386,6 @@ void state::_set_host_perfdata_file_mode(const std::string& value) { _host_perfdata_file_mode = mode_file_append; } -/** - * Unused variable lock_file. - * - * @param[in] value Unused. - */ -void state::_set_lock_file(const std::string& value [[maybe_unused]]) { - _logger->warn("Warning: lock_file variable ignored"); - ++config_warnings; -} - -/** - * Unused variable log_archive_path. - * - * @param[in] value Unused. - */ -void state::_set_log_archive_path(const std::string& value [[maybe_unused]]) { - _logger->warn("Warning: log_archive_path variable ignored"); - ++config_warnings; -} - -/** - * Unused variable log_initial_states. - * - * @param[in] value Unused. - */ -void state::_set_log_initial_states(const std::string& value [[maybe_unused]]) { - _logger->warn("Warning: log_initial_states variable ignored"); - ++config_warnings; -} - -/** - * Unused variable log_rotation_method. - * - * @param[in] value Unused. - */ -void state::_set_log_rotation_method(const std::string& value - [[maybe_unused]]) { - _logger->warn("Warning: log_rotation_method variable ignored"); - ++config_warnings; -} - -/** - * Unused variable nagios_group. - * - * @param[in] value Unused. - */ -void state::_set_nagios_group(const std::string& value [[maybe_unused]]) { - _logger->warn("Warning: nagios_group variable ignored"); - ++config_warnings; -} - -/** - * Unused variable nagios_user. - * - * @param[in] value Unused. - */ -void state::_set_nagios_user(const std::string& value [[maybe_unused]]) { - _logger->warn("Warning: nagios_user variable ignored"); - ++config_warnings; -} - -/** - * Set object_cache_file value. - * - * @param[in] value Unused. - */ -void state::_set_object_cache_file(const std::string& value [[maybe_unused]]) { - _logger->warn("Warning: object_cache_file variable ignored"); - ++config_warnings; -} - -/** - * Unused variable p1_file. - * - * @param[in] value Unused. - */ -void state::_set_p1_file(const std::string& value [[maybe_unused]]) { - _logger->warn("Warning: p1_file variable ignored"); - - ++config_warnings; -} - -/** - * Set precached_object_file value. - * - * @param[in] value Unused. - */ -void state::_set_precached_object_file(const std::string& value - [[maybe_unused]]) { - _logger->warn("Warning: precached_object_file variable ignored"); - ++config_warnings; -} - /** * Set resource_file. * @@ -4661,29 +4401,6 @@ void state::_set_resource_file(const std::string& value) { } } -/** - * Unused variable retained_process_service_attribute_mask. - * - * @param[in] value Unused. - */ -void state::_set_retained_process_service_attribute_mask( - const std::string& value [[maybe_unused]]) { - _logger->warn( - "Warning: retained_process_service_attribute_mask variable ignored"); - ++config_warnings; -} - -/** - * Unused variable retained_service_attribute_mask. - * - * @param[in] value Unused. - */ -void state::_set_retained_service_attribute_mask(const std::string& value - [[maybe_unused]]) { - _logger->warn("Warning: retained_service_attribute_mask variable ignored"); - ++config_warnings; -} - /** * Set service_inter_check_delay_method * @@ -4698,8 +4415,8 @@ void state::_set_service_inter_check_delay_method(const std::string& value) { _service_inter_check_delay_method = icd_smart; else { _service_inter_check_delay_method = icd_user; - if (!absl::SimpleAtod(value, &scheduling_info.service_inter_check_delay) || - scheduling_info.service_inter_check_delay <= 0.0) + if (!absl::SimpleAtod(value, &_scheduling_info.service_inter_check_delay) || + _scheduling_info.service_inter_check_delay <= 0.0) throw msg_fmt( "Invalid value for service_inter_check_delay_method, must be one of " "'n' (none), 'd' (dumb), 's' (smart) or a strictly positive value " @@ -4718,9 +4435,9 @@ void state::_set_service_interleave_factor_method(const std::string& value) { _service_interleave_factor_method = ilf_smart; else { _service_interleave_factor_method = ilf_user; - if (!absl::SimpleAtoi(value, &scheduling_info.service_interleave_factor) || - scheduling_info.service_interleave_factor < 1) - scheduling_info.service_interleave_factor = 1; + if (!absl::SimpleAtoi(value, &_scheduling_info.service_interleave_factor) || + _scheduling_info.service_interleave_factor < 1) + _scheduling_info.service_interleave_factor = 1; } } @@ -4738,37 +4455,6 @@ void state::_set_service_perfdata_file_mode(const std::string& value) { _service_perfdata_file_mode = mode_file_append; } -/** - * Unused variable temp_file. - * - * @param[in] value Unused. - */ -void state::_set_temp_file(const std::string& value [[maybe_unused]]) { - _logger->warn("Warning: temp_file variable ignored"); - ++config_warnings; -} - -/** - * Unused variable temp_path. - * - * @param[in] value Unused. - */ -void state::_set_temp_path(const std::string& value [[maybe_unused]]) { - _logger->warn("Warning: temp_path variable ignored"); - ++config_warnings; -} - -/** - * Unused variable use_embedded_perl_implicitly. - * - * @param[in] value Unused. - */ -void state::_set_use_embedded_perl_implicitly(const std::string& value - [[maybe_unused]]) { - _logger->warn("Warning: use_embedded_perl_implicitly variable ignored"); - ++config_warnings; -} - void state::macros_filter(const std::string& value) { size_t previous(0), first, last; size_t current(value.find(',')); diff --git a/engine/src/configuration/tag.cc b/engine/src/configuration/tag.cc index c25b2a53194..f17fd214a78 100644 --- a/engine/src/configuration/tag.cc +++ b/engine/src/configuration/tag.cc @@ -110,7 +110,7 @@ bool tag::operator<(const tag& other) const noexcept { * * If the object is not valid, an exception is thrown. */ -void tag::check_validity() const { +void tag::check_validity(error_cnt& err [[maybe_unused]]) const { if (_tag_name.empty()) throw msg_fmt("Tag has no name (property 'tag_name')"); if (_key.first == 0) diff --git a/engine/src/configuration/timeperiod.cc b/engine/src/configuration/timeperiod.cc index 9b6afdb1f65..c4eb591f57f 100644 --- a/engine/src/configuration/timeperiod.cc +++ b/engine/src/configuration/timeperiod.cc @@ -126,7 +126,7 @@ bool timeperiod::operator<(timeperiod const& right) const { * * If the object is not valid, an exception is thrown. */ -void timeperiod::check_validity() const { +void timeperiod::check_validity(error_cnt& err [[maybe_unused]]) const { if (_timeperiod_name.empty()) throw msg_fmt("Time period has no name (property 'timeperiod_name')"); } diff --git a/engine/src/configuration/whitelist.cc b/engine/src/configuration/whitelist.cc index f9849a0bbe8..ae2780b75a7 100644 --- a/engine/src/configuration/whitelist.cc +++ b/engine/src/configuration/whitelist.cc @@ -17,7 +17,6 @@ * */ -#include "common/log_v2/log_v2.hh" #define C4_NO_DEBUG_BREAK 1 #include "com/centreon/engine/configuration/whitelist.hh" @@ -31,7 +30,6 @@ #include #include "absl/base/call_once.h" -#include "com/centreon/engine/globals.hh" #include "com/centreon/exceptions/msg_fmt.hh" #include "common/log_v2/log_v2.hh" diff --git a/engine/src/contact.cc b/engine/src/contact.cc index 0a2ac083a0a..3873f6854e5 100644 --- a/engine/src/contact.cc +++ b/engine/src/contact.cc @@ -1043,8 +1043,9 @@ bool contact::_to_notify_custom(notifier::reason_type type return true; } -void contact::resolve(int& w, int& e) { - int warnings{0}, errors{0}; +void contact::resolve(uint32_t& w, uint32_t& e) { + uint32_t warnings = 0; + uint32_t errors = 0; /* check service notification commands */ if (get_service_notification_commands().empty()) { diff --git a/engine/src/contactgroup.cc b/engine/src/contactgroup.cc index 6cd17d3388c..63e819c0f8c 100644 --- a/engine/src/contactgroup.cc +++ b/engine/src/contactgroup.cc @@ -1,22 +1,21 @@ /** * Copyright 2011-2019,2024 Centreon * - * This file is part of Centreon Engine. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Centreon Engine is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License version 2 - * as published by the Free Software Foundation. + * http://www.apache.org/licenses/LICENSE-2.0 * - * Centreon Engine is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com * - * You should have received a copy of the GNU General Public License - * along with Centreon Engine. If not, see - * . */ - #include "com/centreon/engine/configuration/contactgroup.hh" #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/configuration/applier/state.hh" @@ -111,8 +110,8 @@ std::ostream& operator<<(std::ostream& os, contactgroup_map_unsafe const& obj) { return os; } -void contactgroup::resolve(int& w __attribute__((unused)), int& e) { - int errors{0}; +void contactgroup::resolve(uint32_t& w __attribute__((unused)), uint32_t& e) { + uint32_t errors = 0; for (contact_map_unsafe::iterator it{_members.begin()}, end{_members.end()}; it != end; ++it) { diff --git a/engine/src/diagnostic.cc b/engine/src/diagnostic.cc index e8a00107a18..0c2d3f443ef 100644 --- a/engine/src/diagnostic.cc +++ b/engine/src/diagnostic.cc @@ -156,8 +156,9 @@ void diagnostic::generate(std::string const& cfg_file, << std::endl; configuration::state conf; try { + configuration::error_cnt err; configuration::parser parsr; - parsr.parse(cfg_file, conf); + parsr.parse(cfg_file, conf, err); } catch (std::exception const& e) { std::cerr << "Diagnostic: configuration file '" << cfg_file << "' parsing failed: " << e.what() << std::endl; diff --git a/engine/src/escalation.cc b/engine/src/escalation.cc index eeedd11aefb..088ce33eb23 100644 --- a/engine/src/escalation.cc +++ b/engine/src/escalation.cc @@ -113,8 +113,8 @@ bool escalation::is_viable(int state __attribute__((unused)), return true; } -void escalation::resolve(int& w __attribute__((unused)), int& e) { - int errors{0}; +void escalation::resolve(uint32_t& w [[maybe_unused]], uint32_t& e) { + uint32_t errors = 0; // Find the timeperiod. if (!get_escalation_period().empty()) { timeperiod_map::const_iterator it{ diff --git a/engine/src/events/loop.cc b/engine/src/events/loop.cc index 59cd5fe765a..7a3c981f435 100644 --- a/engine/src/events/loop.cc +++ b/engine/src/events/loop.cc @@ -92,6 +92,7 @@ void loop::run() { loop::loop() : _need_reload(0), _reload_running(false) {} static void apply_conf(std::atomic* reloading) { + configuration::error_cnt err; engine_logger(log_info_message, more) << "Starting to reload configuration."; process_logger->info("Starting to reload configuration."); try { @@ -99,10 +100,10 @@ static void apply_conf(std::atomic* reloading) { { configuration::parser p; std::string path(::config->cfg_main()); - p.parse(path, config); + p.parse(path, config, err); } configuration::extended_conf::update_state(config); - configuration::applier::state::instance().apply(config); + configuration::applier::state::instance().apply(config, err); engine_logger(log_info_message, basic) << "Configuration reloaded, main loop continuing."; process_logger->info("Configuration reloaded, main loop continuing."); diff --git a/engine/src/globals.cc b/engine/src/globals.cc index e00e0736d06..99346e158e1 100644 --- a/engine/src/globals.cc +++ b/engine/src/globals.cc @@ -73,8 +73,6 @@ com::centreon::engine::commands::command* global_service_event_handler_ptr( com::centreon::engine::commands::command* ochp_command_ptr(NULL); com::centreon::engine::commands::command* ocsp_command_ptr(NULL); int additional_freshness_latency(15); -int config_errors(0); -int config_warnings(0); int sig_id(0); bool sighup{false}; int sigrestart(false); diff --git a/engine/src/host.cc b/engine/src/host.cc index 802b4c85ceb..023fe969f6f 100644 --- a/engine/src/host.cc +++ b/engine/src/host.cc @@ -3951,8 +3951,9 @@ bool host::is_in_downtime() const { * @param e Errors given by the method. An exception is thrown is at less an * error is rised. */ -void host::resolve(int& w, int& e) { - int warnings{0}, errors{0}; +void host::resolve(uint32_t& w, uint32_t& e) { + uint32_t warnings = 0; + uint32_t errors = 0; try { notifier::resolve(warnings, errors); diff --git a/engine/src/hostdependency.cc b/engine/src/hostdependency.cc index d96c8cb99ab..497ac2695ab 100644 --- a/engine/src/hostdependency.cc +++ b/engine/src/hostdependency.cc @@ -228,9 +228,8 @@ bool hostdependency::check_for_circular_hostdependency_path( return false; } -void hostdependency::resolve(int& w, int& e) { - (void)w; - int errors{0}; +void hostdependency::resolve(uint32_t& w [[maybe_unused]], uint32_t& e) { + int errors = 0; // Find the dependent host. host_map::const_iterator it = host::hosts.find(_dependent_hostname); diff --git a/engine/src/hostescalation.cc b/engine/src/hostescalation.cc index 5d0e4bba3ce..d3bd6bf6064 100644 --- a/engine/src/hostescalation.cc +++ b/engine/src/hostescalation.cc @@ -91,9 +91,8 @@ bool hostescalation::is_viable(int state, uint32_t notification_number) const { return retval; } -void hostescalation::resolve(int& w, int& e) { - (void)w; - int errors{0}; +void hostescalation::resolve(uint32_t& w [[maybe_unused]], uint32_t& e) { + uint32_t errors = 0; // Find the host. host_map::const_iterator found(host::hosts.find(this->get_hostname())); diff --git a/engine/src/hostgroup.cc b/engine/src/hostgroup.cc index 54a911fb717..e533bc9c30f 100644 --- a/engine/src/hostgroup.cc +++ b/engine/src/hostgroup.cc @@ -1,22 +1,21 @@ /** * Copyright 2011-2024 Centreon * - * This file is part of Centreon Engine. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Centreon Engine is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License version 2 - * as published by the Free Software Foundation. + * http://www.apache.org/licenses/LICENSE-2.0 * - * Centreon Engine is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com * - * You should have received a copy of the GNU General Public License - * along with Centreon Engine. If not, see - * . */ - #include "com/centreon/engine/hostgroup.hh" #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/configuration/applier/state.hh" @@ -155,9 +154,8 @@ std::ostream& operator<<(std::ostream& os, return (os); } -void hostgroup::resolve(int& w, int& e) { - (void)w; - int errors{0}; +void hostgroup::resolve(uint32_t& w [[maybe_unused]], uint32_t& e) { + uint32_t errors = 0; // Check all group members. for (host_map_unsafe::iterator it{members.begin()}, end{members.end()}; diff --git a/engine/src/main.cc b/engine/src/main.cc index 53dbe0d08e1..7ea59d82e0a 100644 --- a/engine/src/main.cc +++ b/engine/src/main.cc @@ -207,13 +207,14 @@ int main(int argc, char* argv[]) { // Just display the license. if (display_license) { std::cout - << "Centreon Engine " << CENTREON_ENGINE_VERSION_STRING - << "\n" + << "Centreon Engine " CENTREON_ENGINE_VERSION_STRING + "\n" "\n" "Copyright 1999-2009 Ethan Galstad\n" "Copyright 2009-2010 Nagios Core Development Team and Community " "Contributors\n" - "Copyright 2011-2021 Centreon\n" + "Copyright 2011-" CENTREON_CURRENT_YEAR + " Centreon\n" "\n" "This program is free software: you can redistribute it and/or\n" "modify it under the terms of the GNU General Public License " @@ -275,13 +276,14 @@ int main(int argc, char* argv[]) { try { // Read in the configuration files (main config file, // resource and object config files). + configuration::error_cnt err; configuration::state config; { configuration::parser p; - p.parse(config_file, config); + p.parse(config_file, config, err); } - configuration::applier::state::instance().apply(config); + configuration::applier::state::instance().apply(config, err); std::cout << "\n Checked " << commands::command::commands.size() << " commands.\n Checked " @@ -301,9 +303,10 @@ int main(int argc, char* argv[]) { << servicegroup::servicegroups.size() << " service groups.\n Checked " << service::services.size() << " services.\n Checked " << timeperiod::timeperiods.size() - << " time periods.\n\n Total Warnings: " << config_warnings - << "\n Total Errors: " << config_errors << std::endl; - retval = config_errors ? EXIT_FAILURE : EXIT_SUCCESS; + << " time periods.\n\n Total Warnings: " + << err.config_warnings + << "\n Total Errors: " << err.config_errors << std::endl; + retval = err.config_errors ? EXIT_FAILURE : EXIT_SUCCESS; } catch (const std::exception& e) { std::cout << "Error while processing a config file: " << e.what() << std::endl; @@ -330,9 +333,10 @@ int main(int argc, char* argv[]) { try { // Parse configuration. configuration::state config; + configuration::error_cnt err; { configuration::parser p; - p.parse(config_file, config); + p.parse(config_file, config, err); } // Parse retention. @@ -348,7 +352,7 @@ int main(int argc, char* argv[]) { } // Apply configuration. - configuration::applier::state::instance().apply(config, state); + configuration::applier::state::instance().apply(config, err, &state); display_scheduling_info(); retval = EXIT_SUCCESS; @@ -365,10 +369,11 @@ int main(int argc, char* argv[]) { else { try { // Parse configuration. + configuration::error_cnt err; configuration::state config; { configuration::parser p; - p.parse(config_file, config); + p.parse(config_file, config, err); } configuration::extended_conf::load_all(extended_conf_file.begin(), @@ -432,7 +437,7 @@ int main(int argc, char* argv[]) { &backend_broker_log, logging::log_all, logging::basic); // Apply configuration. - configuration::applier::state::instance().apply(config, state); + configuration::applier::state::instance().apply(config, err, &state); // Handle signals (interrupts). setup_sighandler(); diff --git a/engine/src/notifier.cc b/engine/src/notifier.cc index 9f99a71a7fa..418229df236 100644 --- a/engine/src/notifier.cc +++ b/engine/src/notifier.cc @@ -1,22 +1,21 @@ /** - * Copyright 2011-2019 Centreon + * Copyright 2011-2024 Centreon * - * This file is part of Centreon Engine. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Centreon Engine is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License version 2 - * as published by the Free Software Foundation. + * http://www.apache.org/licenses/LICENSE-2.0 * - * Centreon Engine is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com * - * You should have received a copy of the GNU General Public License - * along with Centreon Engine. If not, see - * . */ - #include "com/centreon/engine/notifier.hh" #include "com/centreon/engine/broker.hh" @@ -1371,8 +1370,8 @@ bool is_contact_for_notifier(com::centreon::engine::notifier* notif, * @param e Errors given by the method. An exception is thrown is at less an * error is rised. */ -void notifier::resolve(int& w, int& e) { - int warnings{0}, errors{0}; +void notifier::resolve(uint32_t& w, uint32_t& e) { + uint32_t warnings = 0, errors = 0; /* This list will be filled in {hostescalation,serviceescalation}::resolve */ _escalations.clear(); diff --git a/engine/src/retention/program.cc b/engine/src/retention/program.cc index 6d571448095..06f0cbd186d 100644 --- a/engine/src/retention/program.cc +++ b/engine/src/retention/program.cc @@ -32,7 +32,6 @@ program::setters const program::_setters[] = { {"check_host_freshness", SETTER(bool, _set_check_host_freshness)}, {"check_service_freshness", SETTER(bool, _set_check_service_freshness)}, {"enable_event_handlers", SETTER(bool, _set_enable_event_handlers)}, - {"enable_failure_prediction", SETTER(bool, _set_enable_failure_prediction)}, {"enable_flap_detection", SETTER(bool, _set_enable_flap_detection)}, {"enable_notifications", SETTER(bool, _set_enable_notifications)}, {"global_host_event_handler", @@ -409,16 +408,6 @@ bool program::_set_enable_event_handlers(bool value) { return (true); } -/** - * Deprecated. - * - * @param[in] value Unused. - */ -bool program::_set_enable_failure_prediction(bool value) { - (void)value; - return (true); -} - /** * Set enable_flap_detection. * diff --git a/engine/src/service.cc b/engine/src/service.cc index c4b96d2962c..3ca52aa723d 100644 --- a/engine/src/service.cc +++ b/engine/src/service.cc @@ -3864,8 +3864,9 @@ host* service::get_host_ptr() { return _host_ptr; } -void service::resolve(int& w, int& e) { - int warnings{0}, errors{0}; +void service::resolve(uint32_t& w, uint32_t& e) { + uint32_t warnings = 0; + uint32_t errors = 0; try { notifier::resolve(warnings, errors); diff --git a/engine/src/servicedependency.cc b/engine/src/servicedependency.cc index 80a73c55dc7..07de74d3558 100644 --- a/engine/src/servicedependency.cc +++ b/engine/src/servicedependency.cc @@ -289,9 +289,8 @@ bool servicedependency::check_for_circular_servicedependency_path( return false; } -void servicedependency::resolve(int& w, int& e) { - (void)w; - int errors{0}; +void servicedependency::resolve(uint32_t& w [[maybe_unused]], uint32_t& e) { + uint32_t errors = 0; // Find the dependent service. service_map::const_iterator found{service::services.find( diff --git a/engine/src/serviceescalation.cc b/engine/src/serviceescalation.cc index 41db8011492..27751dfc13f 100644 --- a/engine/src/serviceescalation.cc +++ b/engine/src/serviceescalation.cc @@ -86,9 +86,8 @@ bool serviceescalation::is_viable(int state, return retval; } -void serviceescalation::resolve(int& w, int& e) { - (void)w; - int errors{0}; +void serviceescalation::resolve(uint32_t& w [[maybe_unused]], uint32_t& e) { + uint32_t errors = 0; // Find the service. service_map::const_iterator found{ diff --git a/engine/src/servicegroup.cc b/engine/src/servicegroup.cc index c8b24fcf126..1c1cfbb6415 100644 --- a/engine/src/servicegroup.cc +++ b/engine/src/servicegroup.cc @@ -1,22 +1,22 @@ /** * Copyright 2011-2013 Merethis + * Copyright 2014-2024 Centreon * - * This file is part of Centreon Engine. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Centreon Engine is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License version 2 - * as published by the Free Software Foundation. + * http://www.apache.org/licenses/LICENSE-2.0 * - * Centreon Engine is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com * - * You should have received a copy of the GNU General Public License - * along with Centreon Engine. If not, see - * . */ - #include "com/centreon/engine/servicegroup.hh" #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/configuration/applier/state.hh" @@ -161,9 +161,8 @@ bool engine::is_servicegroup_exist(std::string const& name) throw() { return it != servicegroup::servicegroups.end(); } -void servicegroup::resolve(int& w, int& e) { - (void)w; - int errors{0}; +void servicegroup::resolve(uint32_t& w [[maybe_unused]], uint32_t& e) { + uint32_t errors = 0; // Check all group members. for (service_map_unsafe::iterator it(members.begin()), end(members.end()); diff --git a/engine/src/timeperiod.cc b/engine/src/timeperiod.cc index e156edd99f2..c95bd84957c 100644 --- a/engine/src/timeperiod.cc +++ b/engine/src/timeperiod.cc @@ -1149,8 +1149,8 @@ void get_next_valid_time(time_t pref_time, * @param e[out] Number of errors produced during this resolution. * */ -void timeperiod::resolve(int& w __attribute__((unused)), int& e) { - int errors{0}; +void timeperiod::resolve(uint32_t& w __attribute__((unused)), uint32_t& e) { + uint32_t errors = 0; // Check for illegal characters in timeperiod name. if (contains_illegal_object_chars(_name.c_str())) { diff --git a/engine/tests/checks/anomalydetection.cc b/engine/tests/checks/anomalydetection.cc index d210bd77ea6..cb78afc4717 100644 --- a/engine/tests/checks/anomalydetection.cc +++ b/engine/tests/checks/anomalydetection.cc @@ -54,11 +54,12 @@ class AnomalydetectionCheck : public TestEngine { checks_logger->set_level(spdlog::level::trace); commands_logger->set_level(spdlog::level::trace); + error_cnt err; configuration::applier::contact ct_aply; configuration::contact ctct{new_configuration_contact("admin", true)}; ct_aply.add_object(ctct); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct); + ct_aply.resolve_object(ctct, err); configuration::host hst{new_configuration_host("test_host", "admin")}; configuration::applier::host hst_aply; @@ -69,8 +70,8 @@ class AnomalydetectionCheck : public TestEngine { configuration::applier::service svc_aply; svc_aply.add_object(svc); - hst_aply.resolve_object(hst); - svc_aply.resolve_object(svc); + hst_aply.resolve_object(hst, err); + svc_aply.resolve_object(svc, err); configuration::anomalydetection ad{new_configuration_anomalydetection( "test_host", "test_ad", "admin", 9, 8, @@ -78,7 +79,7 @@ class AnomalydetectionCheck : public TestEngine { configuration::applier::anomalydetection ad_aply; ad_aply.add_object(ad); - ad_aply.resolve_object(ad); + ad_aply.resolve_object(ad, err); host_map const& hm{engine::host::hosts}; _host = hm.begin()->second; diff --git a/engine/tests/checks/service_check.cc b/engine/tests/checks/service_check.cc index a58e4185eb4..3046a65960f 100644 --- a/engine/tests/checks/service_check.cc +++ b/engine/tests/checks/service_check.cc @@ -52,6 +52,7 @@ extern configuration::state* config; class ServiceCheck : public TestEngine { public: void SetUp() override { + configuration::error_cnt err; init_config_state(); config->contacts().clear(); @@ -59,7 +60,7 @@ class ServiceCheck : public TestEngine { configuration::contact ctct{new_configuration_contact("admin", true)}; ct_aply.add_object(ctct); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct); + ct_aply.resolve_object(ctct, err); configuration::host hst{new_configuration_host("test_host", "admin")}; configuration::applier::host hst_aply; @@ -70,8 +71,8 @@ class ServiceCheck : public TestEngine { configuration::applier::service svc_aply; svc_aply.add_object(svc); - hst_aply.resolve_object(hst); - svc_aply.resolve_object(svc); + hst_aply.resolve_object(hst, err); + svc_aply.resolve_object(svc, err); host_map const& hm{engine::host::hosts}; _host = hm.begin()->second; diff --git a/engine/tests/checks/service_retention.cc b/engine/tests/checks/service_retention.cc index 39c95bfbb5f..22e1fd35fef 100644 --- a/engine/tests/checks/service_retention.cc +++ b/engine/tests/checks/service_retention.cc @@ -52,6 +52,9 @@ using namespace com::centreon::engine::configuration::applier; extern configuration::state* config; class ServiceRetention : public TestEngine { + protected: + error_cnt _err; + public: void SetUp() override { init_config_state(); @@ -63,7 +66,7 @@ class ServiceRetention : public TestEngine { configuration::contact ctct{new_configuration_contact("admin", true)}; ct_aply.add_object(ctct); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct); + ct_aply.resolve_object(ctct, _err); configuration::host hst{new_configuration_host("test_host", "admin")}; configuration::applier::host hst_aply; @@ -74,8 +77,8 @@ class ServiceRetention : public TestEngine { configuration::applier::service svc_aply; svc_aply.add_object(svc); - hst_aply.resolve_object(hst); - svc_aply.resolve_object(svc); + hst_aply.resolve_object(hst, _err); + svc_aply.resolve_object(svc, _err); host_map const& hm{engine::host::hosts}; _host = hm.begin()->second; diff --git a/engine/tests/configuration/applier-severity.cc b/engine/tests/configuration/applier-severity.cc index 2fc28b857a1..8c47ac08900 100644 --- a/engine/tests/configuration/applier-severity.cc +++ b/engine/tests/configuration/applier-severity.cc @@ -26,9 +26,6 @@ using namespace com::centreon::engine; using namespace com::centreon::engine::configuration; using namespace com::centreon::engine::configuration::applier; -extern int config_errors; -extern int config_warnings; - class ApplierSeverity : public ::testing::Test { public: void SetUp() override { diff --git a/engine/tests/configuration/applier/applier-command.cc b/engine/tests/configuration/applier/applier-command.cc index 3c530d44896..3035c263a09 100755 --- a/engine/tests/configuration/applier/applier-command.cc +++ b/engine/tests/configuration/applier/applier-command.cc @@ -122,6 +122,7 @@ TEST_F(ApplierCommand, NewCommandWithConnectorFromConfig) { // Then the applier add_object adds the command into the configuration set // but not in the commands map (the connector is not defined). TEST_F(ApplierCommand, NewCommandAndConnectorWithSameName) { + error_cnt err; configuration::applier::command aply; configuration::applier::connector cnn_aply; configuration::command cmd("cmd"); @@ -141,7 +142,7 @@ TEST_F(ApplierCommand, NewCommandAndConnectorWithSameName) { ASSERT_EQ(found->second->get_name(), "cmd"); ASSERT_EQ(found->second->get_command_line(), "echo 1"); - aply.resolve_object(cmd); + aply.resolve_object(cmd, err); connector_map::iterator found_con{ commands::connector::connectors.find("cmd")}; ASSERT_TRUE(found_con != commands::connector::connectors.end()); @@ -227,6 +228,7 @@ TEST_F(ApplierCommand, RemoveCommandWithConnector) { // When the command is removed from the configuration, // Then the command is totally removed. TEST_F(ApplierCommand, ComplexCommand) { + error_cnt err; configuration::applier::command cmd_aply; configuration::applier::host hst_aply; @@ -256,7 +258,7 @@ TEST_F(ApplierCommand, ComplexCommand) { ASSERT_TRUE(config->hosts().size() == 1); hst_aply.expand_objects(*config); - hst_aply.resolve_object(hst); + hst_aply.resolve_object(hst, err); ASSERT_TRUE(hst_found->second->custom_variables.size() == 3); nagios_macros* macros(get_global_macros()); grab_host_macros_r(macros, hst_found->second.get()); @@ -271,6 +273,7 @@ TEST_F(ApplierCommand, ComplexCommand) { // When the command is removed from the configuration, // Then the command is totally removed. TEST_F(ApplierCommand, ComplexCommandWithContact) { + error_cnt err; configuration::applier::command cmd_aply; configuration::applier::host hst_aply; configuration::applier::contact cnt_aply; @@ -310,7 +313,7 @@ TEST_F(ApplierCommand, ComplexCommandWithContact) { ASSERT_TRUE(config->hosts().size() == 1); hst_aply.expand_objects(*config); - hst_aply.resolve_object(hst); + hst_aply.resolve_object(hst, err); ASSERT_TRUE(hst_found->second->custom_variables.size() == 3); nagios_macros* macros(get_global_macros()); grab_host_macros_r(macros, hst_found->second.get()); diff --git a/engine/tests/configuration/applier/applier-connector.cc b/engine/tests/configuration/applier/applier-connector.cc index ff183e871f8..c0bc411371b 100644 --- a/engine/tests/configuration/applier/applier-connector.cc +++ b/engine/tests/configuration/applier/applier-connector.cc @@ -84,7 +84,6 @@ TEST_F(ApplierConnector, ModifyNonExistingConnector) { // When a non existing connector is removed // Then nothing is done. TEST_F(ApplierConnector, RemoveNonExistingConnector) { - configuration::applier::connector aply; configuration::connector cnn("connector"); cnn.parse("connector_line", "echo 1"); diff --git a/engine/tests/configuration/applier/applier-contact.cc b/engine/tests/configuration/applier/applier-contact.cc index 001cfed503c..bff735f72ab 100644 --- a/engine/tests/configuration/applier/applier-contact.cc +++ b/engine/tests/configuration/applier/applier-contact.cc @@ -34,16 +34,9 @@ using namespace com::centreon::engine; using namespace com::centreon::engine::configuration; using namespace com::centreon::engine::configuration::applier; -extern int config_errors; -extern int config_warnings; - class ApplierContact : public ::testing::Test { public: - void SetUp() override { - config_errors = 0; - config_warnings = 0; - init_config_state(); - } + void SetUp() override { init_config_state(); } void TearDown() override { deinit_config_state(); } @@ -200,7 +193,8 @@ TEST_F(ApplierContact, ResolveContactFromConfig) { aply_grp.add_object(grp); aply.add_object(ctct); aply.expand_objects(*config); - ASSERT_THROW(aply.resolve_object(ctct), std::exception); + error_cnt err; + ASSERT_THROW(aply.resolve_object(ctct, err), std::exception); } // Given a contact @@ -217,9 +211,10 @@ TEST_F(ApplierContact, ResolveContactNoNotification) { configuration::contact ctct("test"); aply.add_object(ctct); aply.expand_objects(*config); - ASSERT_THROW(aply.resolve_object(ctct), std::exception); - ASSERT_EQ(config_warnings, 2); - ASSERT_EQ(config_errors, 2); + error_cnt err; + ASSERT_THROW(aply.resolve_object(ctct, err), std::exception); + ASSERT_EQ(err.config_warnings, 2); + ASSERT_EQ(err.config_errors, 2); } // Given a valid contact @@ -237,9 +232,10 @@ TEST_F(ApplierContact, ResolveValidContact) { configuration::contact ctct(valid_contact_config()); aply.add_object(ctct); aply.expand_objects(*config); - ASSERT_NO_THROW(aply.resolve_object(ctct)); - ASSERT_EQ(config_warnings, 0); - ASSERT_EQ(config_errors, 0); + error_cnt err; + ASSERT_NO_THROW(aply.resolve_object(ctct, err)); + ASSERT_EQ(err.config_warnings, 0); + ASSERT_EQ(err.config_errors, 0); } // Given a valid contact @@ -253,9 +249,10 @@ TEST_F(ApplierContact, ResolveNonExistingServiceNotificationTimeperiod) { ctct.parse("service_notification_period", "non_existing_period"); aply.add_object(ctct); aply.expand_objects(*config); - ASSERT_THROW(aply.resolve_object(ctct), std::exception); - ASSERT_EQ(config_warnings, 0); - ASSERT_EQ(config_errors, 1); + error_cnt err; + ASSERT_THROW(aply.resolve_object(ctct, err), std::exception); + ASSERT_EQ(err.config_warnings, 0); + ASSERT_EQ(err.config_errors, 1); } // Given a valid contact @@ -269,9 +266,10 @@ TEST_F(ApplierContact, ResolveNonExistingHostNotificationTimeperiod) { ctct.parse("host_notification_period", "non_existing_period"); aply.add_object(ctct); aply.expand_objects(*config); - ASSERT_THROW(aply.resolve_object(ctct), std::exception); - ASSERT_EQ(config_warnings, 0); - ASSERT_EQ(config_errors, 1); + error_cnt err; + ASSERT_THROW(aply.resolve_object(ctct, err), std::exception); + ASSERT_EQ(err.config_warnings, 0); + ASSERT_EQ(err.config_errors, 1); } // Given a valid contact @@ -285,9 +283,10 @@ TEST_F(ApplierContact, ResolveNonExistingServiceCommand) { ctct.parse("service_notification_commands", "non_existing_command"); aply.add_object(ctct); aply.expand_objects(*config); - ASSERT_THROW(aply.resolve_object(ctct), std::exception); - ASSERT_EQ(config_warnings, 0); - ASSERT_EQ(config_errors, 1); + error_cnt err; + ASSERT_THROW(aply.resolve_object(ctct, err), std::exception); + ASSERT_EQ(err.config_warnings, 0); + ASSERT_EQ(err.config_errors, 1); } // Given a valid contact @@ -301,9 +300,10 @@ TEST_F(ApplierContact, ResolveNonExistingHostCommand) { ctct.parse("host_notification_commands", "non_existing_command"); aply.add_object(ctct); aply.expand_objects(*config); - ASSERT_THROW(aply.resolve_object(ctct), std::exception); - ASSERT_EQ(config_warnings, 0); - ASSERT_EQ(config_errors, 1); + error_cnt err; + ASSERT_THROW(aply.resolve_object(ctct, err), std::exception); + ASSERT_EQ(err.config_warnings, 0); + ASSERT_EQ(err.config_errors, 1); } // Given a valid contact configuration @@ -366,9 +366,10 @@ TEST_F(ApplierContact, ContactWithOnlyHostRecoveryNotification) { ctct.parse("service_notifications_enabled", "1"); aply.add_object(ctct); aply.expand_objects(*config); - aply.resolve_object(ctct); - ASSERT_EQ(config_warnings, 1); - ASSERT_EQ(config_errors, 0); + error_cnt err; + aply.resolve_object(ctct, err); + ASSERT_EQ(err.config_warnings, 1); + ASSERT_EQ(err.config_errors, 0); } // Given a valid contact @@ -385,7 +386,8 @@ TEST_F(ApplierContact, ContactWithOnlyServiceRecoveryNotification) { ctct.parse("service_notifications_enabled", "1"); aply.add_object(ctct); aply.expand_objects(*config); - aply.resolve_object(ctct); - ASSERT_EQ(config_warnings, 1); - ASSERT_EQ(config_errors, 0); + error_cnt err; + aply.resolve_object(ctct, err); + ASSERT_EQ(err.config_warnings, 1); + ASSERT_EQ(err.config_errors, 0); } diff --git a/engine/tests/configuration/applier/applier-contactgroup.cc b/engine/tests/configuration/applier/applier-contactgroup.cc index 98c27920e44..ccbef264891 100644 --- a/engine/tests/configuration/applier/applier-contactgroup.cc +++ b/engine/tests/configuration/applier/applier-contactgroup.cc @@ -30,16 +30,9 @@ using namespace com::centreon::engine; using namespace com::centreon::engine::configuration; using namespace com::centreon::engine::configuration::applier; -extern int config_errors; -extern int config_warnings; - class ApplierContactgroup : public ::testing::Test { public: - void SetUp() override { - config_errors = 0; - config_warnings = 0; - init_config_state(); - } + void SetUp() override { init_config_state(); } void TearDown() override { deinit_config_state(); } }; @@ -146,6 +139,7 @@ TEST_F(ApplierContactgroup, ResolveInexistentContact) { // When the resolve_object() method is called // Then the contact is really added to the contact group. TEST_F(ApplierContactgroup, ResolveContactgroup) { + error_cnt err; configuration::applier::contact aply; configuration::applier::contactgroup aply_grp; configuration::contactgroup grp("test_group"); @@ -155,7 +149,7 @@ TEST_F(ApplierContactgroup, ResolveContactgroup) { grp.parse("members", "test"); aply_grp.add_object(grp); aply_grp.expand_objects(*config); - ASSERT_NO_THROW(aply_grp.resolve_object(grp)); + ASSERT_NO_THROW(aply_grp.resolve_object(grp, err)); } // Given a contactgroup with a contact already configured @@ -164,6 +158,7 @@ TEST_F(ApplierContactgroup, ResolveContactgroup) { // Then the parse method returns true and set the first one contacts // to the second one. TEST_F(ApplierContactgroup, SetContactgroupMembers) { + error_cnt err; configuration::applier::contact aply; configuration::applier::contactgroup aply_grp; configuration::contactgroup grp("test_group"); @@ -172,7 +167,7 @@ TEST_F(ApplierContactgroup, SetContactgroupMembers) { grp.parse("members", "test"); aply_grp.add_object(grp); aply_grp.expand_objects(*config); - aply_grp.resolve_object(grp); + aply_grp.resolve_object(grp, err); ASSERT_TRUE(grp.members().size() == 1); configuration::contactgroup grp1("big_group"); @@ -185,6 +180,7 @@ TEST_F(ApplierContactgroup, SetContactgroupMembers) { } TEST_F(ApplierContactgroup, ContactRemove) { + error_cnt err; configuration::applier::contact aply; configuration::applier::contactgroup aply_grp; configuration::contactgroup grp("test_group"); @@ -198,7 +194,7 @@ TEST_F(ApplierContactgroup, ContactRemove) { grp.parse("members", "test, test2"); aply_grp.add_object(grp); aply_grp.expand_objects(*config); - aply_grp.resolve_object(grp); + aply_grp.resolve_object(grp, err); ASSERT_EQ( engine::contactgroup::contactgroups["test_group"]->get_members().size(), 2u); diff --git a/engine/tests/configuration/applier/applier-global.cc b/engine/tests/configuration/applier/applier-global.cc index ac272cae031..107abebe923 100644 --- a/engine/tests/configuration/applier/applier-global.cc +++ b/engine/tests/configuration/applier/applier-global.cc @@ -21,6 +21,8 @@ #include #include #include +#include "com/centreon/engine/configuration/state.hh" +#include "com/centreon/engine/globals.hh" #include "helper.hh" using namespace com::centreon; @@ -38,6 +40,7 @@ class ApplierGlobal : public ::testing::Test { TEST_F(ApplierGlobal, pollerName) { configuration::parser parser; configuration::state st; + configuration::error_cnt err; ASSERT_EQ(st.poller_name(), "unknown"); @@ -47,7 +50,7 @@ TEST_F(ApplierGlobal, pollerName) { ofs << "poller_name=poller-test" << std::endl; ofs.close(); - parser.parse("/tmp/test-config.cfg", st); + parser.parse("/tmp/test-config.cfg", st, err); std::remove("/tmp/test-config.cfg"); ASSERT_EQ(st.poller_name(), "poller-test"); @@ -56,6 +59,7 @@ TEST_F(ApplierGlobal, pollerName) { TEST_F(ApplierGlobal, pollerId) { configuration::parser parser; configuration::state st; + configuration::error_cnt err; ASSERT_EQ(st.poller_id(), 0u); @@ -65,7 +69,7 @@ TEST_F(ApplierGlobal, pollerId) { ofs << "poller_id=42" << std::endl; ofs.close(); - parser.parse("/tmp/test-config.cfg", st); + parser.parse("/tmp/test-config.cfg", st, err); std::remove("/tmp/test-config.cfg"); ASSERT_EQ(st.poller_id(), 42u); @@ -74,6 +78,7 @@ TEST_F(ApplierGlobal, pollerId) { TEST_F(ApplierGlobal, RpcPort) { configuration::parser parser; configuration::state st; + configuration::error_cnt err; ASSERT_EQ(st.rpc_port(), 0u); @@ -83,7 +88,7 @@ TEST_F(ApplierGlobal, RpcPort) { ofs << "rpc_port=42" << std::endl; ofs.close(); - parser.parse("/tmp/test-config.cfg", st); + parser.parse("/tmp/test-config.cfg", st, err); std::remove("/tmp/test-config.cfg"); ASSERT_EQ(st.rpc_port(), 42u); @@ -92,6 +97,7 @@ TEST_F(ApplierGlobal, RpcPort) { TEST_F(ApplierGlobal, RpcListenAddress) { configuration::parser parser; configuration::state st; + configuration::error_cnt err; ASSERT_EQ(st.rpc_port(), 0u); @@ -101,7 +107,7 @@ TEST_F(ApplierGlobal, RpcListenAddress) { ofs << "rpc_listen_address=10.11.12.13" << std::endl; ofs.close(); - parser.parse("/tmp/test-config.cfg", st); + parser.parse("/tmp/test-config.cfg", st, err); std::remove("/tmp/test-config.cfg"); ASSERT_EQ(st.rpc_listen_address(), "10.11.12.13"); @@ -110,6 +116,7 @@ TEST_F(ApplierGlobal, RpcListenAddress) { TEST_F(ApplierGlobal, NotDefinedRpcListenAddress) { configuration::parser parser; configuration::state st; + configuration::error_cnt err; ASSERT_EQ(st.rpc_port(), 0u); @@ -119,7 +126,7 @@ TEST_F(ApplierGlobal, NotDefinedRpcListenAddress) { ofs << "rpc_port=42" << std::endl; ofs.close(); - parser.parse("/tmp/test-config.cfg", st); + parser.parse("/tmp/test-config.cfg", st, err); std::remove("/tmp/test-config.cfg"); ASSERT_EQ(st.rpc_listen_address(), "localhost"); diff --git a/engine/tests/configuration/applier/applier-host.cc b/engine/tests/configuration/applier/applier-host.cc index 88b6be736a0..7250d45dc3f 100644 --- a/engine/tests/configuration/applier/applier-host.cc +++ b/engine/tests/configuration/applier/applier-host.cc @@ -102,6 +102,7 @@ TEST_F(ApplierHost, HostRemoved) { } TEST_F(ApplierHost, HostParentChildUnreachable) { + error_cnt err; configuration::applier::host hst_aply; configuration::applier::command cmd_aply; configuration::host hst_child; @@ -135,8 +136,8 @@ TEST_F(ApplierHost, HostParentChildUnreachable) { ASSERT_EQ(engine::host::hosts.size(), 2u); hst_aply.expand_objects(*config); - hst_aply.resolve_object(hst_child); - hst_aply.resolve_object(hst_parent); + hst_aply.resolve_object(hst_child, err); + hst_aply.resolve_object(hst_parent, err); host_map::iterator child = engine::host::hosts.find("child_host"); host_map::iterator parent = engine::host::hosts.find("parent_host"); diff --git a/engine/tests/configuration/applier/applier-hostdependency.cc b/engine/tests/configuration/applier/applier-hostdependency.cc index 06707899e0f..6429646d270 100644 --- a/engine/tests/configuration/applier/applier-hostdependency.cc +++ b/engine/tests/configuration/applier/applier-hostdependency.cc @@ -52,70 +52,73 @@ extern configuration::state* config; class HostDependency : public TestEngine { public: void SetUp() override { + error_cnt err; init_config_state(); configuration::applier::contact ct_aply; configuration::contact ctct{new_configuration_contact("admin", true)}; ct_aply.add_object(ctct); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct); + ct_aply.resolve_object(ctct, err); configuration::applier::host hst_aply; configuration::host hst1{new_configuration_host("host1", "admin", 18)}; hst_aply.add_object(hst1); - hst_aply.resolve_object(hst1); + hst_aply.resolve_object(hst1, err); configuration::host hst2{new_configuration_host("host2", "admin", 19)}; hst_aply.add_object(hst2); - hst_aply.resolve_object(hst2); + hst_aply.resolve_object(hst2, err); configuration::host hst3{new_configuration_host("host3", "admin", 20)}; hst_aply.add_object(hst3); - hst_aply.resolve_object(hst3); + hst_aply.resolve_object(hst3, err); } void TearDown() override { deinit_config_state(); } }; TEST_F(HostDependency, CircularDependency2) { + error_cnt err; configuration::applier::hostdependency hd_aply; configuration::hostdependency hd1{ new_configuration_hostdependency("host1", "host2")}; hd_aply.expand_objects(*config); hd_aply.add_object(hd1); - hd_aply.resolve_object(hd1); + hd_aply.resolve_object(hd1, err); configuration::hostdependency hd2{ new_configuration_hostdependency("host2", "host1")}; hd_aply.expand_objects(*config); hd_aply.add_object(hd2); - hd_aply.resolve_object(hd2); + hd_aply.resolve_object(hd2, err); - int w{0}, e{0}; + uint32_t w = 0, e = 0; ASSERT_EQ(pre_flight_circular_check(&w, &e), ERROR); } TEST_F(HostDependency, CircularDependency3) { + error_cnt err; configuration::applier::hostdependency hd_aply; configuration::hostdependency hd1{ new_configuration_hostdependency("host1", "host2")}; hd_aply.expand_objects(*config); hd_aply.add_object(hd1); - hd_aply.resolve_object(hd1); + hd_aply.resolve_object(hd1, err); configuration::hostdependency hd2{ new_configuration_hostdependency("host2", "host3")}; hd_aply.expand_objects(*config); hd_aply.add_object(hd2); - hd_aply.resolve_object(hd2); + hd_aply.resolve_object(hd2, err); configuration::hostdependency hd3{ new_configuration_hostdependency("host3", "host1")}; hd_aply.expand_objects(*config); hd_aply.add_object(hd3); - hd_aply.resolve_object(hd3); + hd_aply.resolve_object(hd3, err); - int w{0}, e{0}; + uint32_t w{0}, e{0}; ASSERT_EQ(pre_flight_circular_check(&w, &e), ERROR); } diff --git a/engine/tests/configuration/applier/applier-hostescalation.cc b/engine/tests/configuration/applier/applier-hostescalation.cc index 42a647a5be1..8cdee2a6141 100644 --- a/engine/tests/configuration/applier/applier-hostescalation.cc +++ b/engine/tests/configuration/applier/applier-hostescalation.cc @@ -20,6 +20,7 @@ #include #include #include +#include #include #include #include @@ -56,6 +57,7 @@ TEST_F(ApplierHostEscalation, AddEscalation) { } TEST_F(ApplierHostEscalation, ResolveObject) { + configuration::error_cnt err; configuration::applier::host hst_aply; configuration::host hst; ASSERT_TRUE(hst.parse("host_name", "test_host")); @@ -68,9 +70,9 @@ TEST_F(ApplierHostEscalation, ResolveObject) { configuration::hostescalation he; ASSERT_TRUE(he.parse("host_name", "test_host")); ASSERT_TRUE(he.parse("first_notification", "4")); - ASSERT_THROW(he_apply.resolve_object(he), std::exception); + ASSERT_THROW(he_apply.resolve_object(he, err), std::exception); he_apply.add_object(he); - ASSERT_NO_THROW(he_apply.resolve_object(he)); + ASSERT_NO_THROW(he_apply.resolve_object(he, err)); } TEST_F(ApplierHostEscalation, RemoveEscalation) { diff --git a/engine/tests/configuration/applier/applier-hostgroup.cc b/engine/tests/configuration/applier/applier-hostgroup.cc index 6c0c0da0299..3747fac883d 100644 --- a/engine/tests/configuration/applier/applier-hostgroup.cc +++ b/engine/tests/configuration/applier/applier-hostgroup.cc @@ -41,6 +41,7 @@ class ApplierHostGroup : public ::testing::Test { // Given host configuration without host_id // Then the applier add_object throws an exception. TEST_F(ApplierHostGroup, NewHostGroup) { + error_cnt err; configuration::applier::hostgroup hg_aply; configuration::applier::host hst_aply; configuration::hostgroup hg; @@ -72,10 +73,10 @@ TEST_F(ApplierHostGroup, NewHostGroup) { ASSERT_NO_THROW(hst_aply.expand_objects(*config)); ASSERT_NO_THROW(hg_aply.expand_objects(*config)); - ASSERT_NO_THROW(hst_aply.resolve_object(hst_a)); - ASSERT_NO_THROW(hst_aply.resolve_object(hst_b)); - ASSERT_NO_THROW(hst_aply.resolve_object(hst_c)); - ASSERT_NO_THROW(hg_aply.resolve_object(hg)); + ASSERT_NO_THROW(hst_aply.resolve_object(hst_a, err)); + ASSERT_NO_THROW(hst_aply.resolve_object(hst_b, err)); + ASSERT_NO_THROW(hst_aply.resolve_object(hst_c, err)); + ASSERT_NO_THROW(hg_aply.resolve_object(hg, err)); ASSERT_EQ(engine::hostgroup::hostgroups.size(), 1u); ASSERT_EQ(engine::hostgroup::hostgroups.begin()->second->members.size(), 3u); @@ -111,9 +112,10 @@ TEST_F(ApplierHostGroup, HostRenamed) { ASSERT_NO_THROW(hst_aply.expand_objects(*config)); ASSERT_NO_THROW(hg_aply.expand_objects(*config)); - ASSERT_NO_THROW(hst_aply.resolve_object(hst_a)); - ASSERT_NO_THROW(hst_aply.resolve_object(hst_c)); - ASSERT_NO_THROW(hg_aply.resolve_object(hg)); + error_cnt err; + ASSERT_NO_THROW(hst_aply.resolve_object(hst_a, err)); + ASSERT_NO_THROW(hst_aply.resolve_object(hst_c, err)); + ASSERT_NO_THROW(hg_aply.resolve_object(hg, err)); ASSERT_NO_THROW(hg_aply.remove_object(hg)); ASSERT_TRUE(hg.parse("hostgroup_name", "temp_hg")); @@ -155,9 +157,10 @@ TEST_F(ApplierHostGroup, HostRemoved) { ASSERT_NO_THROW(hst_aply.expand_objects(*config)); ASSERT_NO_THROW(hg_aply.expand_objects(*config)); - ASSERT_NO_THROW(hst_aply.resolve_object(hst_a)); - ASSERT_NO_THROW(hst_aply.resolve_object(hst_c)); - ASSERT_NO_THROW(hg_aply.resolve_object(hg)); + error_cnt err; + ASSERT_NO_THROW(hst_aply.resolve_object(hst_a, err)); + ASSERT_NO_THROW(hst_aply.resolve_object(hst_c, err)); + ASSERT_NO_THROW(hg_aply.resolve_object(hg, err)); engine::hostgroup* hg_obj{engine::hostgroup::hostgroups["temphg"].get()}; ASSERT_EQ(hg_obj->members.size(), 2u); diff --git a/engine/tests/configuration/applier/applier-log.cc b/engine/tests/configuration/applier/applier-log.cc index 9f6becac860..b3b0c707cd7 100644 --- a/engine/tests/configuration/applier/applier-log.cc +++ b/engine/tests/configuration/applier/applier-log.cc @@ -22,6 +22,7 @@ #include #include +#include "com/centreon/engine/configuration/state.hh" #include "helper.hh" using namespace com::centreon; @@ -39,6 +40,7 @@ class ApplierLog : public ::testing::Test { TEST_F(ApplierLog, logV2Enabled) { configuration::parser parser; configuration::state st; + configuration::error_cnt err; ASSERT_EQ(st.log_v2_enabled(), true); @@ -48,7 +50,7 @@ TEST_F(ApplierLog, logV2Enabled) { ofs << "log_v2_enabled=0" << std::endl; ofs.close(); - parser.parse("/tmp/test-config.cfg", st); + parser.parse("/tmp/test-config.cfg", st, err); std::remove("/tmp/test-config.cfg"); ASSERT_EQ(st.log_v2_enabled(), false); @@ -57,6 +59,7 @@ TEST_F(ApplierLog, logV2Enabled) { TEST_F(ApplierLog, logLegacyEnabled) { configuration::parser parser; configuration::state st; + configuration::error_cnt err; ASSERT_EQ(st.log_legacy_enabled(), true); @@ -66,13 +69,14 @@ TEST_F(ApplierLog, logLegacyEnabled) { ofs << "log_legacy_enabled=0" << std::endl; ofs.close(); - parser.parse("/tmp/test-config.cfg", st); + parser.parse("/tmp/test-config.cfg", st, err); std::remove("/tmp/test-config.cfg"); ASSERT_EQ(st.log_legacy_enabled(), false); } TEST_F(ApplierLog, logV2Logger) { + configuration::error_cnt err; configuration::parser parser; configuration::state st; @@ -84,13 +88,14 @@ TEST_F(ApplierLog, logV2Logger) { ofs << "log_v2_logger=syslog" << std::endl; ofs.close(); - parser.parse("/tmp/test-config.cfg", st); + parser.parse("/tmp/test-config.cfg", st, err); std::remove("/tmp/test-config.cfg"); ASSERT_EQ(st.log_v2_logger(), "syslog"); } TEST_F(ApplierLog, logLevelFunctions) { + configuration::error_cnt err; configuration::parser parser; configuration::state st; @@ -102,7 +107,7 @@ TEST_F(ApplierLog, logLevelFunctions) { ofs << "log_level_functions=trace" << std::endl; ofs.close(); - parser.parse("/tmp/test-config.cfg", st); + parser.parse("/tmp/test-config.cfg", st, err); ASSERT_EQ(st.log_level_functions(), "trace"); @@ -110,13 +115,14 @@ TEST_F(ApplierLog, logLevelFunctions) { ofs << "log_level_functions=tracerrrr" << std::endl; ofs.close(); - ASSERT_THROW(parser.parse("/tmp/test-config.cfg", st), std::exception); + ASSERT_THROW(parser.parse("/tmp/test-config.cfg", st, err), std::exception); std::remove("/tmp/test-config.cfg"); } TEST_F(ApplierLog, logLevelConfig) { configuration::parser parser; configuration::state st; + configuration::error_cnt err; ASSERT_EQ(st.log_level_config(), "info"); @@ -126,7 +132,7 @@ TEST_F(ApplierLog, logLevelConfig) { ofs << "log_level_config=debug" << std::endl; ofs.close(); - parser.parse("/tmp/test-config.cfg", st); + parser.parse("/tmp/test-config.cfg", st, err); ASSERT_EQ(st.log_level_config(), "debug"); @@ -134,7 +140,7 @@ TEST_F(ApplierLog, logLevelConfig) { ofs << "log_level_config=tracerrrr" << std::endl; ofs.close(); - ASSERT_THROW(parser.parse("/tmp/test-config.cfg", st), std::exception); + ASSERT_THROW(parser.parse("/tmp/test-config.cfg", st, err), std::exception); std::remove("/tmp/test-config.cfg"); // testing::internal::CaptureStdout(); @@ -151,6 +157,7 @@ TEST_F(ApplierLog, logLevelConfig) { } TEST_F(ApplierLog, logLevelEvents) { + configuration::error_cnt err; configuration::parser parser; configuration::state st; @@ -162,14 +169,14 @@ TEST_F(ApplierLog, logLevelEvents) { ofs << "log_level_events=warning" << std::endl; ofs.close(); - parser.parse("/tmp/test-config.cfg", st); + parser.parse("/tmp/test-config.cfg", st, err); ASSERT_EQ(st.log_level_events(), "warning"); ofs.open("/tmp/test-config.cfg"); ofs << "log_level_events=tracerrrr" << std::endl; ofs.close(); - ASSERT_THROW(parser.parse("/tmp/test-config.cfg", st), std::exception); + ASSERT_THROW(parser.parse("/tmp/test-config.cfg", st, err), std::exception); std::remove("/tmp/test-config.cfg"); // testing::internal::CaptureStdout(); // parser.parse("/tmp/test-config.cfg", st); @@ -187,6 +194,7 @@ TEST_F(ApplierLog, logLevelEvents) { TEST_F(ApplierLog, logLevelChecks) { configuration::parser parser; configuration::state st; + configuration::error_cnt err; ASSERT_EQ(st.log_level_checks(), "info"); @@ -196,14 +204,14 @@ TEST_F(ApplierLog, logLevelChecks) { ofs << "log_level_checks=error" << std::endl; ofs.close(); - parser.parse("/tmp/test-config.cfg", st); + parser.parse("/tmp/test-config.cfg", st, err); ASSERT_EQ(st.log_level_checks(), "error"); ofs.open("/tmp/test-config.cfg"); ofs << "log_level_checks=tracerrrr" << std::endl; ofs.close(); - ASSERT_THROW(parser.parse("/tmp/test-config.cfg", st), std::exception); + ASSERT_THROW(parser.parse("/tmp/test-config.cfg", st, err), std::exception); std::remove("/tmp/test-config.cfg"); // testing::internal::CaptureStdout(); // parser.parse("/tmp/test-config.cfg", st); @@ -221,6 +229,7 @@ TEST_F(ApplierLog, logLevelChecks) { TEST_F(ApplierLog, logLevelNotifications) { configuration::parser parser; configuration::state st; + configuration::error_cnt err; ASSERT_EQ(st.log_level_notifications(), "error"); @@ -230,14 +239,14 @@ TEST_F(ApplierLog, logLevelNotifications) { ofs << "log_level_notifications=off" << std::endl; ofs.close(); - parser.parse("/tmp/test-config.cfg", st); + parser.parse("/tmp/test-config.cfg", st, err); ASSERT_EQ(st.log_level_notifications(), "off"); ofs.open("/tmp/test-config.cfg"); ofs << "log_level_notifications=tracerrrr" << std::endl; ofs.close(); - ASSERT_THROW(parser.parse("/tmp/test-config.cfg", st), std::exception); + ASSERT_THROW(parser.parse("/tmp/test-config.cfg", st, err), std::exception); std::remove("/tmp/test-config.cfg"); // testing::internal::CaptureStdout(); // parser.parse("/tmp/test-config.cfg", st); @@ -255,6 +264,7 @@ TEST_F(ApplierLog, logLevelNotifications) { TEST_F(ApplierLog, logLevelEventBroker) { configuration::parser parser; configuration::state st; + configuration::error_cnt err; ASSERT_EQ(st.log_level_eventbroker(), "error"); @@ -264,14 +274,14 @@ TEST_F(ApplierLog, logLevelEventBroker) { ofs << "log_level_eventbroker=critical" << std::endl; ofs.close(); - parser.parse("/tmp/test-config.cfg", st); + parser.parse("/tmp/test-config.cfg", st, err); ASSERT_EQ(st.log_level_eventbroker(), "critical"); ofs.open("/tmp/test-config.cfg"); ofs << "log_level_eventbroker=tracerrrr" << std::endl; ofs.close(); - ASSERT_THROW(parser.parse("/tmp/test-config.cfg", st), std::exception); + ASSERT_THROW(parser.parse("/tmp/test-config.cfg", st, err), std::exception); std::remove("/tmp/test-config.cfg"); // testing::internal::CaptureStdout(); // parser.parse("/tmp/test-config.cfg", st); @@ -289,6 +299,7 @@ TEST_F(ApplierLog, logLevelEventBroker) { TEST_F(ApplierLog, logLevelExternalCommand) { configuration::parser parser; configuration::state st; + configuration::error_cnt err; ASSERT_EQ(st.log_level_external_command(), "error"); @@ -298,14 +309,14 @@ TEST_F(ApplierLog, logLevelExternalCommand) { ofs << "log_level_external_command=trace" << std::endl; ofs.close(); - parser.parse("/tmp/test-config.cfg", st); + parser.parse("/tmp/test-config.cfg", st, err); ASSERT_EQ(st.log_level_external_command(), "trace"); ofs.open("/tmp/test-config.cfg"); ofs << "log_level_external_command=tracerrrr" << std::endl; ofs.close(); - ASSERT_THROW(parser.parse("/tmp/test-config.cfg", st), std::exception); + ASSERT_THROW(parser.parse("/tmp/test-config.cfg", st, err), std::exception); std::remove("/tmp/test-config.cfg"); // testing::internal::CaptureStdout(); // parser.parse("/tmp/test-config.cfg", st); @@ -323,6 +334,7 @@ TEST_F(ApplierLog, logLevelExternalCommand) { TEST_F(ApplierLog, logLevelCommands) { configuration::parser parser; configuration::state st; + configuration::error_cnt err; ASSERT_EQ(st.log_level_commands(), "error"); @@ -332,14 +344,14 @@ TEST_F(ApplierLog, logLevelCommands) { ofs << "log_level_commands=debug" << std::endl; ofs.close(); - parser.parse("/tmp/test-config.cfg", st); + parser.parse("/tmp/test-config.cfg", st, err); ASSERT_EQ(st.log_level_commands(), "debug"); ofs.open("/tmp/test-config.cfg"); ofs << "log_level_commands=tracerrrr" << std::endl; ofs.close(); - ASSERT_THROW(parser.parse("/tmp/test-config.cfg", st), std::exception); + ASSERT_THROW(parser.parse("/tmp/test-config.cfg", st, err), std::exception); std::remove("/tmp/test-config.cfg"); // testing::internal::CaptureStdout(); // parser.parse("/tmp/test-config.cfg", st); @@ -357,6 +369,7 @@ TEST_F(ApplierLog, logLevelCommands) { TEST_F(ApplierLog, logLevelDowntimes) { configuration::parser parser; configuration::state st; + configuration::error_cnt err; ASSERT_EQ(st.log_level_downtimes(), "error"); @@ -366,14 +379,14 @@ TEST_F(ApplierLog, logLevelDowntimes) { ofs << "log_level_downtimes=warning" << std::endl; ofs.close(); - parser.parse("/tmp/test-config.cfg", st); + parser.parse("/tmp/test-config.cfg", st, err); ASSERT_EQ(st.log_level_downtimes(), "warning"); ofs.open("/tmp/test-config.cfg"); ofs << "log_level_downtimes=tracerrrr" << std::endl; ofs.close(); - ASSERT_THROW(parser.parse("/tmp/test-config.cfg", st), std::exception); + ASSERT_THROW(parser.parse("/tmp/test-config.cfg", st, err), std::exception); std::remove("/tmp/test-config.cfg"); // testing::internal::CaptureStdout(); // parser.parse("/tmp/test-config.cfg", st); @@ -391,6 +404,7 @@ TEST_F(ApplierLog, logLevelDowntimes) { TEST_F(ApplierLog, logLevelComments) { configuration::parser parser; configuration::state st; + configuration::error_cnt err; ASSERT_EQ(st.log_level_comments(), "error"); @@ -400,14 +414,14 @@ TEST_F(ApplierLog, logLevelComments) { ofs << "log_level_comments=error" << std::endl; ofs.close(); - parser.parse("/tmp/test-config.cfg", st); + parser.parse("/tmp/test-config.cfg", st, err); ASSERT_EQ(st.log_level_comments(), "error"); ofs.open("/tmp/test-config.cfg"); ofs << "log_level_comments=tracerrrr" << std::endl; ofs.close(); - ASSERT_THROW(parser.parse("/tmp/test-config.cfg", st), std::exception); + ASSERT_THROW(parser.parse("/tmp/test-config.cfg", st, err), std::exception); std::remove("/tmp/test-config.cfg"); // testing::internal::CaptureStdout(); // parser.parse("/tmp/test-config.cfg", st); @@ -425,6 +439,7 @@ TEST_F(ApplierLog, logLevelComments) { TEST_F(ApplierLog, logLevelMacros) { configuration::parser parser; configuration::state st; + configuration::error_cnt err; ASSERT_EQ(st.log_level_macros(), "error"); @@ -434,14 +449,14 @@ TEST_F(ApplierLog, logLevelMacros) { ofs << "log_level_macros=critical" << std::endl; ofs.close(); - parser.parse("/tmp/test-config.cfg", st); + parser.parse("/tmp/test-config.cfg", st, err); ASSERT_EQ(st.log_level_macros(), "critical"); ofs.open("/tmp/test-config.cfg"); ofs << "log_level_macros=tracerrrr" << std::endl; ofs.close(); - ASSERT_THROW(parser.parse("/tmp/test-config.cfg", st), std::exception); + ASSERT_THROW(parser.parse("/tmp/test-config.cfg", st, err), std::exception); std::remove("/tmp/test-config.cfg"); // testing::internal::CaptureStdout(); // parser.parse("/tmp/test-config.cfg", st); @@ -459,6 +474,7 @@ TEST_F(ApplierLog, logLevelMacros) { TEST_F(ApplierLog, logLevelProcess) { configuration::parser parser; configuration::state st; + configuration::error_cnt err; ASSERT_EQ(st.log_level_process(), "info"); @@ -468,14 +484,14 @@ TEST_F(ApplierLog, logLevelProcess) { ofs << "log_level_process=off" << std::endl; ofs.close(); - parser.parse("/tmp/test-config.cfg", st); + parser.parse("/tmp/test-config.cfg", st, err); ASSERT_EQ(st.log_level_process(), "off"); ofs.open("/tmp/test-config.cfg"); ofs << "log_level_process=tracerrrr" << std::endl; ofs.close(); - ASSERT_THROW(parser.parse("/tmp/test-config.cfg", st), std::exception); + ASSERT_THROW(parser.parse("/tmp/test-config.cfg", st, err), std::exception); std::remove("/tmp/test-config.cfg"); // testing::internal::CaptureStdout(); // parser.parse("/tmp/test-config.cfg", st); @@ -493,6 +509,7 @@ TEST_F(ApplierLog, logLevelProcess) { TEST_F(ApplierLog, logLevelRuntime) { configuration::parser parser; configuration::state st; + configuration::error_cnt err; ASSERT_EQ(st.log_level_runtime(), "error"); @@ -502,14 +519,14 @@ TEST_F(ApplierLog, logLevelRuntime) { ofs << "log_level_runtime=off" << std::endl; ofs.close(); - parser.parse("/tmp/test-config.cfg", st); + parser.parse("/tmp/test-config.cfg", st, err); ASSERT_EQ(st.log_level_runtime(), "off"); ofs.open("/tmp/test-config.cfg"); ofs << "log_level_runtime=tracerrrr" << std::endl; ofs.close(); - ASSERT_THROW(parser.parse("/tmp/test-config.cfg", st), std::exception); + ASSERT_THROW(parser.parse("/tmp/test-config.cfg", st, err), std::exception); std::remove("/tmp/test-config.cfg"); // testing::internal::CaptureStdout(); // parser.parse("/tmp/test-config.cfg", st); @@ -527,6 +544,7 @@ TEST_F(ApplierLog, logLevelRuntime) { TEST_F(ApplierLog, logFile) { configuration::parser parser; configuration::state st; + configuration::error_cnt err; ASSERT_EQ(st.log_file(), DEFAULT_LOG_FILE); @@ -536,7 +554,7 @@ TEST_F(ApplierLog, logFile) { ofs << "log_file=/tmp/centengine.log" << std::endl; ofs.close(); - parser.parse("/tmp/test-config.cfg", st); + parser.parse("/tmp/test-config.cfg", st, err); std::remove("/tmp/test-config.cfg"); ASSERT_EQ(st.log_file(), "/tmp/centengine.log"); diff --git a/engine/tests/configuration/applier/applier-service.cc b/engine/tests/configuration/applier/applier-service.cc index 1f5b0d20a6f..abba80764f3 100644 --- a/engine/tests/configuration/applier/applier-service.cc +++ b/engine/tests/configuration/applier/applier-service.cc @@ -28,6 +28,7 @@ #include "com/centreon/engine/configuration/applier/service.hh" #include "com/centreon/engine/configuration/applier/tag.hh" #include "com/centreon/engine/configuration/host.hh" +#include "com/centreon/engine/configuration/object.hh" #include "com/centreon/engine/configuration/service.hh" #include "com/centreon/engine/contact.hh" #include "com/centreon/engine/exceptions/error.hh" @@ -259,29 +260,30 @@ TEST_F(ApplierService, ServicesEquality) { } // Given a service configuration applied to a service, -// When the check_validity() method is executed on the configuration, +// When the check_validity(err) method is executed on the configuration, // Then it throws an exception because: // 1. it does not provide a service description // 2. it is not attached to a host // 3. the service does not contain any check command. TEST_F(ApplierService, ServicesCheckValidity) { + error_cnt err; configuration::applier::host hst_aply; configuration::applier::service svc_aply; configuration::service csvc; // No service description - ASSERT_THROW(csvc.check_validity(), com::centreon::exceptions::msg_fmt); + ASSERT_THROW(csvc.check_validity(err), com::centreon::exceptions::msg_fmt); ASSERT_TRUE(csvc.parse("service_description", "check description")); ASSERT_TRUE(csvc.parse("service_id", "53")); // No host attached to - ASSERT_THROW(csvc.check_validity(), com::centreon::exceptions::msg_fmt); + ASSERT_THROW(csvc.check_validity(err), com::centreon::exceptions::msg_fmt); ASSERT_TRUE(csvc.parse("hosts", "test_host")); // No check command attached to - ASSERT_THROW(csvc.check_validity(), com::centreon::exceptions::msg_fmt); + ASSERT_THROW(csvc.check_validity(err), com::centreon::exceptions::msg_fmt); configuration::applier::command cmd_aply; configuration::command cmd("cmd"); @@ -302,8 +304,8 @@ TEST_F(ApplierService, ServicesCheckValidity) { ASSERT_TRUE(csvc.parse("service_description", "foo")); // No check command - ASSERT_NO_THROW(csvc.check_validity()); - svc_aply.resolve_object(csvc); + ASSERT_NO_THROW(csvc.check_validity(err)); + svc_aply.resolve_object(csvc, err); service_map const& sm(engine::service::services); ASSERT_EQ(sm.size(), 1u); @@ -372,6 +374,7 @@ TEST_F(ApplierService, ServicesStalkingOptions) { // Then after the service resolution, we can see the contactgroup stored in the // service with the contact inside it. TEST_F(ApplierService, ContactgroupResolution) { + error_cnt err; configuration::contact ctct{new_configuration_contact("admin", true)}; configuration::applier::contact ct_aply; ct_aply.add_object(ctct); @@ -380,7 +383,7 @@ TEST_F(ApplierService, ContactgroupResolution) { cg.parse("members", "admin"); configuration::applier::contactgroup cg_aply; cg_aply.add_object(cg); - cg_aply.resolve_object(cg); + cg_aply.resolve_object(cg, err); configuration::applier::host hst_aply; configuration::applier::service svc_aply; configuration::service svc; @@ -404,7 +407,7 @@ TEST_F(ApplierService, ContactgroupResolution) { svc.set_host_id(1); svc_aply.add_object(svc); - svc_aply.resolve_object(svc); + svc_aply.resolve_object(svc, err); service_id_map const& sm(engine::service::services_by_id); ASSERT_EQ(sm.size(), 1u); ASSERT_EQ(sm.begin()->first.first, 1u); @@ -755,7 +758,7 @@ TEST_F(ApplierService, ServicesEqualityTags) { } // Given a service configuration applied to a service, -// When the check_validity() method is executed on the configuration, +// When the check_validity(err) method is executed on the configuration, // Then it throws an exception because: // 1. it does not provide a service description // 2. it is not attached to a host @@ -764,9 +767,10 @@ TEST_F(ApplierService, ServicesCheckValidityTags) { configuration::applier::host hst_aply; configuration::applier::service svc_aply; configuration::service csvc; + configuration::error_cnt err; // No service description - ASSERT_THROW(csvc.check_validity(), com::centreon::exceptions::msg_fmt); + ASSERT_THROW(csvc.check_validity(err), com::centreon::exceptions::msg_fmt); ASSERT_TRUE(csvc.parse("service_description", "check description")); ASSERT_TRUE(csvc.parse("service_id", "53")); @@ -774,12 +778,12 @@ TEST_F(ApplierService, ServicesCheckValidityTags) { ASSERT_TRUE(csvc.parse("category_tags", "3")); // No host attached to - ASSERT_THROW(csvc.check_validity(), com::centreon::exceptions::msg_fmt); + ASSERT_THROW(csvc.check_validity(err), com::centreon::exceptions::msg_fmt); ASSERT_TRUE(csvc.parse("hosts", "test_host")); // No check command attached to - ASSERT_THROW(csvc.check_validity(), com::centreon::exceptions::msg_fmt); + ASSERT_THROW(csvc.check_validity(err), com::centreon::exceptions::msg_fmt); configuration::applier::command cmd_aply; configuration::command cmd("cmd"); @@ -816,8 +820,8 @@ TEST_F(ApplierService, ServicesCheckValidityTags) { ASSERT_TRUE(csvc.parse("service_description", "foo")); // No check command - ASSERT_NO_THROW(csvc.check_validity()); - svc_aply.resolve_object(csvc); + ASSERT_NO_THROW(csvc.check_validity(err)); + svc_aply.resolve_object(csvc, err); service_map const& sm(engine::service::services); ASSERT_EQ(sm.size(), 1u); diff --git a/engine/tests/configuration/applier/applier-serviceescalation.cc b/engine/tests/configuration/applier/applier-serviceescalation.cc index 754e30da81a..f0598101452 100644 --- a/engine/tests/configuration/applier/applier-serviceescalation.cc +++ b/engine/tests/configuration/applier/applier-serviceescalation.cc @@ -75,6 +75,7 @@ TEST_F(ApplierServiceEscalation, AddEscalation) { } TEST_F(ApplierServiceEscalation, ResolveObject) { + configuration::error_cnt err; configuration::applier::host hst_aply; configuration::host hst; ASSERT_TRUE(hst.parse("host_name", "test_host")); @@ -104,9 +105,9 @@ TEST_F(ApplierServiceEscalation, ResolveObject) { ASSERT_TRUE(se.parse("host", "test_host")); ASSERT_TRUE(se.parse("service_description", "test_svc")); ASSERT_TRUE(se.parse("first_notification", "4")); - ASSERT_THROW(se_apply.resolve_object(se), std::exception); + ASSERT_THROW(se_apply.resolve_object(se, err), std::exception); se_apply.add_object(se); - ASSERT_NO_THROW(se_apply.resolve_object(se)); + ASSERT_NO_THROW(se_apply.resolve_object(se, err)); } TEST_F(ApplierServiceEscalation, RemoveEscalation) { diff --git a/engine/tests/configuration/applier/applier-servicegroup.cc b/engine/tests/configuration/applier/applier-servicegroup.cc index 273507f8084..50c117ac4f7 100644 --- a/engine/tests/configuration/applier/applier-servicegroup.cc +++ b/engine/tests/configuration/applier/applier-servicegroup.cc @@ -33,16 +33,9 @@ using namespace com::centreon::engine; using namespace com::centreon::engine::configuration; using namespace com::centreon::engine::configuration::applier; -extern int config_errors; -extern int config_warnings; - class ApplierServicegroup : public ::testing::Test { public: - void SetUp() override { - config_errors = 0; - config_warnings = 0; - init_config_state(); - } + void SetUp() override { init_config_state(); } void TearDown() override { deinit_config_state(); } }; @@ -94,13 +87,14 @@ TEST_F(ApplierServicegroup, ModifyServicegroupFromConfig) { // When the resolve_object() method is called // Then no warning, nor error are given TEST_F(ApplierServicegroup, ResolveEmptyservicegroup) { + error_cnt err; configuration::applier::servicegroup aplyr; configuration::servicegroup grp("test"); aplyr.add_object(grp); aplyr.expand_objects(*config); - aplyr.resolve_object(grp); - ASSERT_EQ(config_warnings, 0); - ASSERT_EQ(config_errors, 0); + aplyr.resolve_object(grp, err); + ASSERT_EQ(err.config_warnings, 0); + ASSERT_EQ(err.config_errors, 0); } // Given a servicegroup with a non-existing service @@ -108,20 +102,22 @@ TEST_F(ApplierServicegroup, ResolveEmptyservicegroup) { // Then an exception is thrown // And the method returns 1 error TEST_F(ApplierServicegroup, ResolveInexistentService) { + error_cnt err; configuration::applier::servicegroup aplyr; configuration::servicegroup grp("test"); grp.parse("members", "host1,non_existing_service"); aplyr.add_object(grp); aplyr.expand_objects(*config); - ASSERT_THROW(aplyr.resolve_object(grp), std::exception); - ASSERT_EQ(config_warnings, 0); - ASSERT_EQ(config_errors, 1); + ASSERT_THROW(aplyr.resolve_object(grp, err), std::exception); + ASSERT_EQ(err.config_warnings, 0); + ASSERT_EQ(err.config_errors, 1); } // Given a servicegroup with a service and a host // When the resolve_object() method is called // Then the service is really added to the service group. TEST_F(ApplierServicegroup, ResolveServicegroup) { + error_cnt err; configuration::applier::host aply_hst; configuration::applier::service aply_svc; configuration::applier::command aply_cmd; @@ -149,7 +145,7 @@ TEST_F(ApplierServicegroup, ResolveServicegroup) { grp.parse("members", "test_host,test"); aply_grp.add_object(grp); aply_grp.expand_objects(*config); - ASSERT_NO_THROW(aply_grp.resolve_object(grp)); + ASSERT_NO_THROW(aply_grp.resolve_object(grp, err)); } // Given a servicegroup with a service already configured @@ -158,6 +154,7 @@ TEST_F(ApplierServicegroup, ResolveServicegroup) { // Then the parse method returns true and set the first one service // to the second one. TEST_F(ApplierServicegroup, SetServicegroupMembers) { + error_cnt err; configuration::applier::host aply_hst; configuration::applier::service aply_svc; configuration::applier::command aply_cmd; @@ -185,7 +182,7 @@ TEST_F(ApplierServicegroup, SetServicegroupMembers) { grp.parse("members", "test_host,test"); aply_grp.add_object(grp); aply_grp.expand_objects(*config); - aply_grp.resolve_object(grp); + aply_grp.resolve_object(grp, err); ASSERT_TRUE(grp.members().size() == 1); configuration::servicegroup grp1("big_group"); @@ -202,6 +199,7 @@ TEST_F(ApplierServicegroup, SetServicegroupMembers) { // When we remove the configuration // Then it is really removed TEST_F(ApplierServicegroup, RemoveServicegroupFromConfig) { + error_cnt err; configuration::applier::host aply_hst; configuration::applier::service aply_svc; configuration::applier::command aply_cmd; @@ -229,7 +227,7 @@ TEST_F(ApplierServicegroup, RemoveServicegroupFromConfig) { grp.parse("members", "test_host,test"); aply_grp.add_object(grp); aply_grp.expand_objects(*config); - aply_grp.resolve_object(grp); + aply_grp.resolve_object(grp, err); ASSERT_TRUE(grp.members().size() == 1); configuration::servicegroup grp1("big_group"); @@ -249,6 +247,7 @@ TEST_F(ApplierServicegroup, RemoveServicegroupFromConfig) { // When we remove the configuration // Then it is really removed TEST_F(ApplierServicegroup, RemoveServiceFromGroup) { + error_cnt err; configuration::applier::host aply_hst; configuration::applier::service aply_svc; configuration::applier::command aply_cmd; @@ -288,7 +287,7 @@ TEST_F(ApplierServicegroup, RemoveServiceFromGroup) { grp.parse("members", "test_host,test,test_host,test2"); aply_grp.add_object(grp); aply_grp.expand_objects(*config); - aply_grp.resolve_object(grp); + aply_grp.resolve_object(grp, err); ASSERT_TRUE(grp.members().size() == 2); engine::servicegroup* sg{ diff --git a/engine/tests/configuration/applier/applier-state.cc b/engine/tests/configuration/applier/applier-state.cc index 3248dcf52d3..38177e7f6c6 100644 --- a/engine/tests/configuration/applier/applier-state.cc +++ b/engine/tests/configuration/applier/applier-state.cc @@ -22,16 +22,14 @@ #include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/configuration/extended_conf.hh" #include "com/centreon/engine/configuration/parser.hh" +#include "com/centreon/engine/configuration/state.hh" #include "com/centreon/engine/globals.hh" using namespace com::centreon::engine; class ApplierState : public ::testing::Test { public: - void SetUp() override { - config_errors = 0; - config_warnings = 0; - } + void SetUp() override {} void TearDown() override {} }; @@ -702,8 +700,9 @@ constexpr size_t SERVICEGROUPS = 3u; TEST_F(ApplierState, StateLegacyParsing) { configuration::state config; configuration::parser p; + configuration::error_cnt err; CreateConf(); - p.parse("/tmp/centengine.cfg", config); + p.parse("/tmp/centengine.cfg", config, err); ASSERT_EQ(config.check_service_freshness(), true); ASSERT_EQ(config.enable_flap_detection(), false); ASSERT_EQ(config.instance_heartbeat_interval(), 30); @@ -969,61 +968,69 @@ TEST_F(ApplierState, StateLegacyParsing) { TEST_F(ApplierState, StateLegacyParsingServicegroupValidityFailed) { configuration::state config; configuration::parser p; + configuration::error_cnt err; CreateBadConf(ConfigurationObject::SERVICEGROUP); - ASSERT_THROW(p.parse("/tmp/centengine.cfg", config), std::exception); + ASSERT_THROW(p.parse("/tmp/centengine.cfg", config, err), std::exception); } TEST_F(ApplierState, StateLegacyParsingTagValidityFailed) { configuration::state config; configuration::parser p; + configuration::error_cnt err; CreateBadConf(ConfigurationObject::TAG); - ASSERT_THROW(p.parse("/tmp/centengine.cfg", config), std::exception); + ASSERT_THROW(p.parse("/tmp/centengine.cfg", config, err), std::exception); } TEST_F(ApplierState, StateLegacyParsingServicedependencyValidityFailed) { configuration::state config; configuration::parser p; + configuration::error_cnt err; CreateBadConf(ConfigurationObject::SERVICEDEPENDENCY); - ASSERT_THROW(p.parse("/tmp/centengine.cfg", config), std::exception); + ASSERT_THROW(p.parse("/tmp/centengine.cfg", config, err), std::exception); } TEST_F(ApplierState, StateLegacyParsingAnomalydetectionValidityFailed) { configuration::state config; configuration::parser p; + configuration::error_cnt err; CreateBadConf(ConfigurationObject::ANOMALYDETECTION); - ASSERT_THROW(p.parse("/tmp/centengine.cfg", config), std::exception); + ASSERT_THROW(p.parse("/tmp/centengine.cfg", config, err), std::exception); } TEST_F(ApplierState, StateLegacyParsingContactgroupWithoutName) { configuration::state config; configuration::parser p; + configuration::error_cnt err; CreateBadConf(ConfigurationObject::CONTACTGROUP); - ASSERT_THROW(p.parse("/tmp/centengine.cfg", config), std::exception); + ASSERT_THROW(p.parse("/tmp/centengine.cfg", config, err), std::exception); } TEST_F(ApplierState, StateLegacyParsingHostescalationWithoutHost) { configuration::state config; configuration::parser p; + configuration::error_cnt err; CreateBadConf(ConfigurationObject::HOSTESCALATION); - ASSERT_THROW(p.parse("/tmp/centengine.cfg", config), std::exception); + ASSERT_THROW(p.parse("/tmp/centengine.cfg", config, err), std::exception); } TEST_F(ApplierState, StateLegacyParsingHostdependencyWithoutHost) { configuration::state config; configuration::parser p; + configuration::error_cnt err; CreateBadConf(ConfigurationObject::HOSTDEPENDENCY); - ASSERT_THROW(p.parse("/tmp/centengine.cfg", config), std::exception); + ASSERT_THROW(p.parse("/tmp/centengine.cfg", config, err), std::exception); } TEST_F(ApplierState, extended_override_conf) { configuration::state config; configuration::parser p; + configuration::error_cnt err; CreateConf(); - p.parse("/tmp/centengine.cfg", config); + p.parse("/tmp/centengine.cfg", config, err); const char* file_paths[] = {"/tmp/extended_conf.json"}; CreateFile(file_paths[0], - R"({"instance_heartbeat_interval":120, + R"({"instance_heartbeat_interval":120, "log_level_functions":"debug", "log_level_checks":"trace", "enable_flap_detection": true, @@ -1042,8 +1049,9 @@ TEST_F(ApplierState, extended_override_conf) { TEST_F(ApplierState, extended_override_conf_overflow) { configuration::state config; configuration::parser p; + configuration::error_cnt err; CreateConf(); - p.parse("/tmp/centengine.cfg", config); + p.parse("/tmp/centengine.cfg", config, err); const char* file_paths[] = {"/tmp/extended_conf.json"}; CreateFile(file_paths[0], diff --git a/engine/tests/configuration/contact.cc b/engine/tests/configuration/contact.cc index 8a3bfea06cf..4d53553e0f7 100644 --- a/engine/tests/configuration/contact.cc +++ b/engine/tests/configuration/contact.cc @@ -38,5 +38,6 @@ class ConfigContact : public ::testing::Test { // Then an exception is thrown. TEST_F(ConfigContact, NewContactWithNoName) { configuration::contact ctct(""); - ASSERT_THROW(ctct.check_validity(), std::exception); + configuration::error_cnt err; + ASSERT_THROW(ctct.check_validity(err), std::exception); } diff --git a/engine/tests/configuration/severity.cc b/engine/tests/configuration/severity.cc index ab632869ea5..fce65fbab87 100644 --- a/engine/tests/configuration/severity.cc +++ b/engine/tests/configuration/severity.cc @@ -39,14 +39,16 @@ class ConfigSeverity : public ::testing::Test { // Then an exception is thrown. TEST_F(ConfigSeverity, NewSeverityWithNoKey) { configuration::severity sv({0, 0}); - ASSERT_THROW(sv.check_validity(), std::exception); + configuration::error_cnt err; + ASSERT_THROW(sv.check_validity(err), std::exception); } // When I create a configuration::severity with a null level // Then an exception is thrown. TEST_F(ConfigSeverity, NewSeverityWithNoLevel) { configuration::severity sv({1, 0}); - ASSERT_THROW(sv.check_validity(), std::exception); + configuration::error_cnt err; + ASSERT_THROW(sv.check_validity(err), std::exception); } // When I create a configuration::severity with an empty name @@ -54,7 +56,8 @@ TEST_F(ConfigSeverity, NewSeverityWithNoLevel) { TEST_F(ConfigSeverity, NewSeverityWithNoName) { configuration::severity sv({1, 0}); sv.parse("level", "2"); - ASSERT_THROW(sv.check_validity(), std::exception); + configuration::error_cnt err; + ASSERT_THROW(sv.check_validity(err), std::exception); } // When I create a configuration::severity with a non empty name, @@ -69,7 +72,8 @@ TEST_F(ConfigSeverity, NewSeverityWellFilled) { ASSERT_EQ(sv.level(), 2); ASSERT_EQ(sv.severity_name(), "foobar"); ASSERT_EQ(sv.type(), configuration::severity::service); - ASSERT_NO_THROW(sv.check_validity()); + configuration::error_cnt err; + ASSERT_NO_THROW(sv.check_validity(err)); } // When I create a configuration::severity with an icon id. @@ -81,5 +85,6 @@ TEST_F(ConfigSeverity, NewSeverityIconId) { sv.parse("severity_name", "foobar"); sv.parse("type", "host"); ASSERT_EQ(sv.icon_id(), 18); - ASSERT_NO_THROW(sv.check_validity()); + configuration::error_cnt err; + ASSERT_NO_THROW(sv.check_validity(err)); } diff --git a/engine/tests/configuration/tag.cc b/engine/tests/configuration/tag.cc index 32a1e3fcacc..db4b1c0f5f8 100644 --- a/engine/tests/configuration/tag.cc +++ b/engine/tests/configuration/tag.cc @@ -20,6 +20,7 @@ #include "com/centreon/engine/configuration/tag.hh" #include +#include "com/centreon/engine/configuration/object.hh" #include "helper.hh" using namespace com::centreon; @@ -38,45 +39,50 @@ class ConfigTag : public ::testing::Test { // When I create a configuration::tag with a null id // Then an exception is thrown. TEST_F(ConfigTag, NewTagWithNoKey) { + configuration::error_cnt err; configuration::tag tg({0, 0}); - ASSERT_THROW(tg.check_validity(), std::exception); + ASSERT_THROW(tg.check_validity(err), std::exception); } // When I create a configuration::tag with a null type // Then an exception is thrown. TEST_F(ConfigTag, NewTagWithNoLevel) { + configuration::error_cnt err; configuration::tag tg({1, 0}); - ASSERT_THROW(tg.check_validity(), std::exception); + ASSERT_THROW(tg.check_validity(err), std::exception); } // When I create a configuration::tag with an empty name // Then an exception is thrown. TEST_F(ConfigTag, NewTagWithNoName) { + configuration::error_cnt err; configuration::tag tg({1, 0}); tg.parse("type", "hostcategory"); - ASSERT_THROW(tg.check_validity(), std::exception); + ASSERT_THROW(tg.check_validity(err), std::exception); } // When I create a configuration::tag with a non empty name, // non null id and non null type // Then no exception is thrown. TEST_F(ConfigTag, NewTagWellFilled) { + configuration::error_cnt err; configuration::tag tg({1, 0}); tg.parse("type", "servicegroup"); tg.parse("tag_name", "foobar"); ASSERT_EQ(tg.key().first, 1); ASSERT_EQ(tg.key().second, engine::configuration::tag::servicegroup); ASSERT_EQ(tg.tag_name(), "foobar"); - ASSERT_NO_THROW(tg.check_validity()); + ASSERT_NO_THROW(tg.check_validity(err)); } // When I create a configuration::tag with a non empty name, // non null id and non null type. // Then we can get the type value. TEST_F(ConfigTag, NewTagIconId) { + configuration::error_cnt err; configuration::tag tg({1, 0}); tg.parse("type", "hostgroup"); tg.parse("tag_name", "foobar"); ASSERT_EQ(tg.key().second, engine::configuration::tag::hostgroup); - ASSERT_NO_THROW(tg.check_validity()); + ASSERT_NO_THROW(tg.check_validity(err)); } diff --git a/engine/tests/configuration/timeperiod-test.cc b/engine/tests/configuration/timeperiod-test.cc index 3cce0dc866e..838e84f00fd 100644 --- a/engine/tests/configuration/timeperiod-test.cc +++ b/engine/tests/configuration/timeperiod-test.cc @@ -20,15 +20,12 @@ #include +#include #include -#include "com/centreon/engine/timerange.hh" - #include "com/centreon/engine/common.hh" #include "com/centreon/engine/configuration/applier/timeperiod.hh" -#include "com/centreon/engine/configuration/timeperiod.hh" #include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/string.hh" using namespace com::centreon::engine::configuration; using namespace com::centreon::engine; @@ -673,7 +670,9 @@ std::vector parse_timeperiods_cfg(const std::string& file_path) { current.clear(); continue; } - current.push_back(com::centreon::engine::string::trim(line)); + + absl::StripAsciiWhitespace(&line); + current.push_back(std::move(line)); } } @@ -714,4 +713,4 @@ TEST_P(timeperiod_config_parser_test, VerifyParserContent) { ASSERT_TRUE(comparator.is_equal()); ASSERT_TRUE(comparator.is_result_equal()); -} \ No newline at end of file +} diff --git a/engine/tests/configuration/timeperiods.cfg b/engine/tests/configuration/timeperiods.cfg index be670adf37b..970c610c90f 100644 --- a/engine/tests/configuration/timeperiods.cfg +++ b/engine/tests/configuration/timeperiods.cfg @@ -179,21 +179,21 @@ define timeperiod { define timeperiod { name 01h25-23h55 timeperiod_name 01h25-23h55 - alias 01h25-23h55 - sunday 01:25-23:55 - monday 01:25-23:55 + alias 01h25-23h55 + sunday 01:25-23:55 + monday 01:25-23:55 tuesday 01:25-23:55 wednesday 01:25-23:55 - thursday 01:25-23:55 + thursday 01:25-23:55 friday 01:25-23:55 - saturday 01:25-23:55 + saturday 01:25-23:55 } define timeperiod { - name 06h00-22h00 - timeperiod_name 06h00-22h00 - alias 06h00-22h00 - sunday 06:00-22:00 + name 06h00-22h00 + timeperiod_name 06h00-22h00 + alias 06h00-22h00 + sunday 06:00-22:00 monday 06:00-22:00 tuesday 06:00-22:00 wednesday 06:00-22:00 @@ -402,50 +402,77 @@ define timeperiod { name nonworkhours timeperiod_name nonworkhours alias Non-Work_Hours - sunday 00:00-24:00 ; Every Sunday of every week - monday 00:00-09:00,17:00-24:00 ; Every Monday of every week - tuesday 00:00-09:00,17:00-24:00 ; Every Tuesday of every week - wednesday 00:00-09:00,17:00-24:00 ; Every Wednesday of every week - thursday 00:00-09:00,17:00-24:00 ; Every Thursday of every week - friday 00:00-09:00,17:00-24:00 ; Every Friday of every week - saturday 00:00-24:00 ; Every Saturday of every week + # Every Sunday of every week + sunday 00:00-24:00 + # Every Monday of every week + monday 00:00-09:00,17:00-24:00 + # Every Tuesday of every week + tuesday 00:00-09:00,17:00-24:00 + # Every Wednesday of every week + wednesday 00:00-09:00,17:00-24:00 + # Every Thursday of every week + thursday 00:00-09:00,17:00-24:00 + # Every Friday of every week + friday 00:00-09:00,17:00-24:00 + # Every Saturday of every week + saturday 00:00-24:00 } define timeperiod { name misc-single-days timeperiod_name misc-single-days alias Misc Single Days - 1999-01-28 00:00-24:00 ; January 28th, 1999 - monday 3 00:00-24:00 ; 3rd Monday of every month - day 2 00:00-24:00 ; 2nd day of every month - february 10 00:00-24:00 ; February 10th of every year - february -1 00:00-24:00 ; Last day in February of every year - friday -2 00:00-24:00 ; 2nd to last Friday of every month - thursday -1 november 00:00-24:00 ; Last Thursday in November of every year + # January 28th, 1999 + 1999-01-28 00:00-24:00 + # 3rd Monday of every month + monday 3 00:00-24:00 + # 2nd day of every month + day 2 00:00-24:00 + # February 10th of every year + february 10 00:00-24:00 + # Last day in February of every year + february -1 00:00-24:00 + # 2nd to last Friday of every month + friday -2 00:00-24:00 + # Last Thursday in November of every year + thursday -1 november 00:00-24:00 } define timeperiod { name misc-date-ranges timeperiod_name misc-date-ranges alias Misc Date Ranges - 2007-01-01 - 2008-02-01 00:00-24:00 ; January 1st, 2007 to February 1st, 2008 - monday 3 - thursday 4 00:00-24:00 ; 3rd Monday to 4th Thursday of every month - day 1 - 15 00:00-24:00 ; 1st to 15th day of every month - day 20 - -1 00:00-24:00 ; 20th to the last day of every month - july 10 - 15 00:00-24:00 ; July 10th to July 15th of every year - april 10 - may 15 00:00-24:00 ; April 10th to May 15th of every year - tuesday 1 april - friday 2 may 00:00-24:00 ; 1st Tuesday in April to 2nd Friday in May of every year + # January 1st, 2007 to February 1st, 2008 + 2007-01-01 - 2008-02-01 00:00-24:00 + # 3rd Monday to 4th Thursday of every month + monday 3 - thursday 4 00:00-24:00 + # 1st to 15th day of every month + day 1 - 15 00:00-24:00 + # 20th to the last day of every month + day 20 - -1 00:00-24:00 + # July 10th to July 15th of every year + july 10 - 15 00:00-24:00 + # April 10th to May 15th of every year + april 10 - may 15 00:00-24:00 + # 1st Tuesday in April to 2nd Friday in May of every year + tuesday 1 april - friday 2 may 00:00-24:00 } define timeperiod { name misc-skip-ranges timeperiod_name misc-skip-ranges alias Misc Skip Ranges - 2007-01-01 - 2008-02-01 / 3 00:00-24:00 ; Every 3 days from January 1st, 2007 to February 1st, 2008 - 2008-04-01 / 7 00:00-24:00 ; Every 7 days from April 1st, 2008 (continuing forever) - monday 3 - thursday 4 / 2 00:00-24:00 ; Every other day from 3rd Monday to 4th Thursday of every month - day 1 - 15 / 5 00:00-24:00 ; Every 5 days from the 1st to the 15th day of every month - july 10 - 15 / 2 00:00-24:00 ; Every other day from July 10th to July 15th of every year - tuesday 1 april - friday 2 may / 6 00:00-24:00 ; Every 6 days from the 1st Tuesday in April to the 2nd Friday in May of every year + # Every 3 days from January 1st, 2007 to February 1st, 2008 + 2007-01-01 - 2008-02-01 / 3 00:00-24:00 + # Every 7 days from April 1st, 2008 (continuing forever) + 2008-04-01 / 7 00:00-24:00 + # Every other day from 3rd Monday to 4th Thursday of every month + monday 3 - thursday 4 / 2 00:00-24:00 + # Every 5 days from the 1st to the 15th day of every month + day 1 - 15 / 5 00:00-24:00 + # Every other day from July 10th to July 15th of every year + july 10 - 15 / 2 00:00-24:00 + # Every 6 days from the 1st Tuesday in April to the 2nd Friday in May of every year + tuesday 1 april - friday 2 may / 6 00:00-24:00 } diff --git a/engine/tests/custom_vars/extcmd.cc b/engine/tests/custom_vars/extcmd.cc index 0bde69f2481..5833fd7584e 100755 --- a/engine/tests/custom_vars/extcmd.cc +++ b/engine/tests/custom_vars/extcmd.cc @@ -45,6 +45,7 @@ class CustomVar : public ::testing::Test { // When the command is removed from the configuration, // Then the command is totally removed. TEST_F(CustomVar, UpdateHostCustomVar) { + configuration::error_cnt err; configuration::applier::command cmd_aply; configuration::applier::host hst_aply; configuration::applier::contact cnt_aply; @@ -84,7 +85,7 @@ TEST_F(CustomVar, UpdateHostCustomVar) { ASSERT_TRUE(config->hosts().size() == 1); hst_aply.expand_objects(*config); - hst_aply.resolve_object(hst); + hst_aply.resolve_object(hst, err); ASSERT_TRUE(hst_found->second->custom_variables.size() == 3); nagios_macros* macros(get_global_macros()); grab_host_macros_r(macros, hst_found->second.get()); diff --git a/engine/tests/downtimes/downtime_finder.cc b/engine/tests/downtimes/downtime_finder.cc index 94e01a6f996..423aeed7630 100644 --- a/engine/tests/downtimes/downtime_finder.cc +++ b/engine/tests/downtimes/downtime_finder.cc @@ -40,6 +40,7 @@ using namespace com::centreon::engine::downtimes; class DowntimeFinderFindMatchingAllTest : public TestEngine { public: void SetUp() override { + configuration::error_cnt err; init_config_state(); configuration::contact ctc{new_configuration_contact("admin", false, "a")}; configuration::applier::contact ctc_aply; @@ -55,8 +56,8 @@ class DowntimeFinderFindMatchingAllTest : public TestEngine { configuration::host hst2{new_configuration_host("other_host", "admin", 2)}; hst_aply.add_object(hst2); - hst_aply.resolve_object(hst); - hst_aply.resolve_object(hst1); + hst_aply.resolve_object(hst, err); + hst_aply.resolve_object(hst1, err); configuration::service svc{ new_configuration_service("first_host", "test_service", "admin", 8)}; @@ -79,11 +80,11 @@ class DowntimeFinderFindMatchingAllTest : public TestEngine { new_configuration_service("test_host", "new_svc2", "admin", 12)}; svc_aply.add_object(svc4); - svc_aply.resolve_object(svc); - svc_aply.resolve_object(svc1); - svc_aply.resolve_object(svc2); - svc_aply.resolve_object(svc3); - svc_aply.resolve_object(svc4); + svc_aply.resolve_object(svc, err); + svc_aply.resolve_object(svc1, err); + svc_aply.resolve_object(svc2, err); + svc_aply.resolve_object(svc3, err); + svc_aply.resolve_object(svc4, err); downtime_manager::instance().clear_scheduled_downtimes(); downtime_manager::instance().initialize_downtime_data(); diff --git a/engine/tests/enginerpc/enginerpc.cc b/engine/tests/enginerpc/enginerpc.cc index 2cc77c5d18e..c44963989b1 100644 --- a/engine/tests/enginerpc/enginerpc.cc +++ b/engine/tests/enginerpc/enginerpc.cc @@ -66,12 +66,13 @@ class EngineRpc : public TestEngine { config->execute_service_checks(true); + configuration::error_cnt err; /* contact */ configuration::applier::contact ct_aply; configuration::contact ctct{new_configuration_contact("admin", true)}; ct_aply.add_object(ctct); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct); + ct_aply.resolve_object(ctct, err); /* hosts */ configuration::host hst_child; @@ -87,8 +88,8 @@ class EngineRpc : public TestEngine { hst.parse("_HOST_ID", "12"); hst_aply.add_object(hst); - hst_aply.resolve_object(hst); - hst_aply2.resolve_object(hst_child); + hst_aply.resolve_object(hst, err); + hst_aply2.resolve_object(hst_child, err); ASSERT_EQ(engine::host::hosts.size(), 2u); @@ -105,7 +106,7 @@ class EngineRpc : public TestEngine { hg.parse("members", "test_host"); hg_aply.add_object(hg); hg_aply.expand_objects(*config); - hg_aply.resolve_object(hg); + hg_aply.resolve_object(hg, err); /* service */ configuration::service svc{ @@ -119,7 +120,7 @@ class EngineRpc : public TestEngine { svc_aply.add_object(svc); cmd_aply.add_object(cmd); - svc_aply.resolve_object(svc); + svc_aply.resolve_object(svc, err); configuration::anomalydetection ad{new_configuration_anomalydetection( "test_host", "test_ad", "admin", @@ -129,7 +130,7 @@ class EngineRpc : public TestEngine { configuration::applier::anomalydetection ad_aply; ad_aply.add_object(ad); - ad_aply.resolve_object(ad); + ad_aply.resolve_object(ad, err); host_map const& hm{engine::host::hosts}; _host = hm.begin()->second; @@ -161,7 +162,7 @@ class EngineRpc : public TestEngine { sg_aply.add_object(sg); sg_aply.expand_objects(*config); - sg_aply.resolve_object(sg); + sg_aply.resolve_object(sg, err); } void TearDown() override { diff --git a/engine/tests/external_commands/anomalydetection.cc b/engine/tests/external_commands/anomalydetection.cc index 09bae184388..96afd9e5d5d 100644 --- a/engine/tests/external_commands/anomalydetection.cc +++ b/engine/tests/external_commands/anomalydetection.cc @@ -30,6 +30,7 @@ #include "com/centreon/engine/configuration/applier/host.hh" #include "com/centreon/engine/configuration/applier/service.hh" #include "com/centreon/engine/configuration/contact.hh" +#include "com/centreon/engine/configuration/state.hh" #include "com/centreon/engine/events/loop.hh" #include "com/centreon/engine/timezone_manager.hh" #include "com/centreon/engine/version.hh" @@ -43,11 +44,12 @@ class ADExtCmd : public TestEngine { void SetUp() override { init_config_state(); + configuration::error_cnt err; configuration::applier::contact ct_aply; configuration::contact ctct{new_configuration_contact("admin", true)}; ct_aply.add_object(ctct); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct); + ct_aply.resolve_object(ctct, err); configuration::host hst{new_configuration_host("test_host", "admin")}; configuration::applier::host hst_aply; @@ -58,8 +60,8 @@ class ADExtCmd : public TestEngine { configuration::applier::service svc_aply; svc_aply.add_object(svc); - hst_aply.resolve_object(hst); - svc_aply.resolve_object(svc); + hst_aply.resolve_object(hst, err); + svc_aply.resolve_object(svc, err); configuration::anomalydetection ad{new_configuration_anomalydetection( "test_host", "test_ad", "admin", @@ -69,7 +71,7 @@ class ADExtCmd : public TestEngine { configuration::applier::anomalydetection ad_aply; ad_aply.add_object(ad); - ad_aply.resolve_object(ad); + ad_aply.resolve_object(ad, err); host_map const& hm{engine::host::hosts}; _host = hm.begin()->second; diff --git a/engine/tests/external_commands/service.cc b/engine/tests/external_commands/service.cc index be4b0bb1ab3..e9f55852974 100644 --- a/engine/tests/external_commands/service.cc +++ b/engine/tests/external_commands/service.cc @@ -24,6 +24,7 @@ #include "com/centreon/engine/commands/commands.hh" #include "com/centreon/engine/configuration/applier/command.hh" #include "com/centreon/engine/configuration/applier/host.hh" +#include "com/centreon/engine/configuration/state.hh" #include "com/centreon/engine/events/loop.hh" #include "com/centreon/process_manager.hh" #include "helper.hh" @@ -42,6 +43,7 @@ class ServiceExternalCommand : public ::testing::Test { }; TEST_F(ServiceExternalCommand, AddServiceDowntime) { + configuration::error_cnt err; configuration::applier::host hst_aply; configuration::applier::service svc_aply; configuration::applier::command cmd_aply; @@ -73,8 +75,8 @@ TEST_F(ServiceExternalCommand, AddServiceDowntime) { hst_aply.expand_objects(*config); svc_aply.expand_objects(*config); - hst_aply.resolve_object(hst); - svc_aply.resolve_object(svc); + hst_aply.resolve_object(hst, err); + svc_aply.resolve_object(svc, err); set_time(20000); time_t now = time(nullptr); @@ -123,8 +125,9 @@ TEST_F(ServiceExternalCommand, AddServiceDowntimeByHostIpAddress) { hst_aply.expand_objects(*config); svc_aply.expand_objects(*config); - hst_aply.resolve_object(hst); - svc_aply.resolve_object(svc); + configuration::error_cnt err; + hst_aply.resolve_object(hst, err); + svc_aply.resolve_object(svc, err); set_time(20000); time_t now = time(nullptr); @@ -173,8 +176,9 @@ TEST_F(ServiceExternalCommand, AddServiceComment) { hst_aply.expand_objects(*config); svc_aply.expand_objects(*config); - hst_aply.resolve_object(hst); - svc_aply.resolve_object(svc); + configuration::error_cnt err; + hst_aply.resolve_object(hst, err); + svc_aply.resolve_object(svc, err); std::string cmd_com1{ "test_host;test_description;1;user;this is a first comment"}; diff --git a/engine/tests/loop/loop.cc b/engine/tests/loop/loop.cc index 2a7a04d91c9..2d9988dbed8 100644 --- a/engine/tests/loop/loop.cc +++ b/engine/tests/loop/loop.cc @@ -40,13 +40,14 @@ using namespace com::centreon::engine::configuration; class LoopTest : public TestEngine { public: void SetUp() override { + error_cnt err; init_config_state(); configuration::applier::contact ct_aply; configuration::contact ctct{new_configuration_contact("admin", true)}; ct_aply.add_object(ctct); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct); + ct_aply.resolve_object(ctct, err); configuration::host hst{new_configuration_host("test_host", "admin")}; configuration::applier::host hst_aply; @@ -57,8 +58,8 @@ class LoopTest : public TestEngine { configuration::applier::service svc_aply; svc_aply.add_object(svc); - hst_aply.resolve_object(hst); - svc_aply.resolve_object(svc); + hst_aply.resolve_object(hst, err); + svc_aply.resolve_object(svc, err); host_map const& hm{engine::host::hosts}; _host = hm.begin()->second; diff --git a/engine/tests/macros/macro.cc b/engine/tests/macros/macro.cc old mode 100755 new mode 100644 index 9a12b752e6d..fff4d22da81 --- a/engine/tests/macros/macro.cc +++ b/engine/tests/macros/macro.cc @@ -19,6 +19,7 @@ #include #include +#include "com/centreon/engine/configuration/state.hh" #include "com/centreon/engine/globals.hh" #include @@ -78,6 +79,7 @@ class Macro : public TestEngine { TEST_F(Macro, pollerName) { configuration::parser parser; configuration::state st; + configuration::error_cnt err; std::remove("/tmp/test-config.cfg"); @@ -86,8 +88,8 @@ TEST_F(Macro, pollerName) { ofs << "log_file=\"\"" << std::endl; ofs.close(); - parser.parse("/tmp/test-config.cfg", st); - configuration::applier::state::instance().apply(st); + parser.parse("/tmp/test-config.cfg", st, err); + configuration::applier::state::instance().apply(st, err); std::string out; nagios_macros* mac(get_global_macros()); @@ -98,6 +100,7 @@ TEST_F(Macro, pollerName) { TEST_F(Macro, pollerId) { configuration::parser parser; configuration::state st; + configuration::error_cnt err; std::remove("/tmp/test-config.cfg"); @@ -106,8 +109,8 @@ TEST_F(Macro, pollerId) { ofs << "log_file=\"\"" << std::endl; ofs.close(); - parser.parse("/tmp/test-config.cfg", st); - configuration::applier::state::instance().apply(st); + parser.parse("/tmp/test-config.cfg", st, err); + configuration::applier::state::instance().apply(st, err); std::string out; nagios_macros* mac(get_global_macros()); process_macros_r(mac, "$POLLERID$", out, 0); @@ -320,6 +323,7 @@ TEST_F(Macro, ContactPager) { TEST_F(Macro, FullCmd) { configuration::parser parser; configuration::state st; + configuration::error_cnt err; std::remove("/tmp/test-config.cfg"); @@ -329,14 +333,14 @@ TEST_F(Macro, FullCmd) { ofs << "admin_pager=\"pager\"" << std::endl; ofs.close(); - parser.parse("/tmp/test-config.cfg", st); - configuration::applier::state::instance().apply(st); + parser.parse("/tmp/test-config.cfg", st, err); + configuration::applier::state::instance().apply(st, err); init_macros(); std::string out; nagios_macros* mac(get_global_macros()); - //process_macros_r(mac, "$ADMINEMAIL:test_host$", out, 1); + // process_macros_r(mac, "$ADMINEMAIL:test_host$", out, 1); process_macros_r(mac, "/bin/sh -c '/bin/echo \"LogFile: $LOGFILE$ - AdminEmail: " "$ADMINEMAIL$ - AdminPager: $ADMINPAGER$\"", @@ -349,6 +353,7 @@ TEST_F(Macro, FullCmd) { TEST_F(Macro, AdminEmail) { configuration::parser parser; configuration::state st; + configuration::error_cnt err; std::remove("/tmp/test-config.cfg"); @@ -357,14 +362,14 @@ TEST_F(Macro, AdminEmail) { ofs << "log_file=\"\"" << std::endl; ofs.close(); - parser.parse("/tmp/test-config.cfg", st); - configuration::applier::state::instance().apply(st); + parser.parse("/tmp/test-config.cfg", st, err); + configuration::applier::state::instance().apply(st, err); init_macros(); std::string out; nagios_macros* mac(get_global_macros()); - //process_macros_r(mac, "$ADMINEMAIL:test_host$", out, 1); + // process_macros_r(mac, "$ADMINEMAIL:test_host$", out, 1); process_macros_r(mac, "$ADMINEMAIL$", out, 1); ASSERT_EQ(out, "contactadmin@centreon.com"); } @@ -372,6 +377,7 @@ TEST_F(Macro, AdminEmail) { TEST_F(Macro, AdminPager) { configuration::parser parser; configuration::state st; + configuration::error_cnt err; std::remove("/tmp/test-config.cfg"); @@ -380,8 +386,8 @@ TEST_F(Macro, AdminPager) { ofs << "log_file=\"\"" << std::endl; ofs.close(); - parser.parse("/tmp/test-config.cfg", st); - configuration::applier::state::instance().apply(st); + parser.parse("/tmp/test-config.cfg", st, err); + configuration::applier::state::instance().apply(st, err); init_macros(); @@ -394,6 +400,7 @@ TEST_F(Macro, AdminPager) { TEST_F(Macro, MainConfigFile) { configuration::parser parser; configuration::state st; + configuration::error_cnt err; std::remove("/tmp/test-config.cfg"); @@ -401,8 +408,8 @@ TEST_F(Macro, MainConfigFile) { ofs << "log_file=\"\"" << std::endl; ofs.close(); - parser.parse("/tmp/test-config.cfg", st); - configuration::applier::state::instance().apply(st); + parser.parse("/tmp/test-config.cfg", st, err); + configuration::applier::state::instance().apply(st, err); init_macros(); std::string out; @@ -414,6 +421,7 @@ TEST_F(Macro, MainConfigFile) { TEST_F(Macro, StatusDataFile) { configuration::parser parser; configuration::state st; + configuration::error_cnt err; std::remove("/tmp/test-config.cfg"); @@ -422,8 +430,8 @@ TEST_F(Macro, StatusDataFile) { ofs << "log_file=\"\"" << std::endl; ofs.close(); - parser.parse("/tmp/test-config.cfg", st); - configuration::applier::state::instance().apply(st); + parser.parse("/tmp/test-config.cfg", st, err); + configuration::applier::state::instance().apply(st, err); init_macros(); std::string out; @@ -435,6 +443,7 @@ TEST_F(Macro, StatusDataFile) { TEST_F(Macro, RetentionDataFile) { configuration::parser parser; configuration::state st; + configuration::error_cnt err; std::remove("/tmp/test-config.cfg"); @@ -444,8 +453,8 @@ TEST_F(Macro, RetentionDataFile) { ofs << "log_file=\"\"" << std::endl; ofs.close(); - parser.parse("/tmp/test-config.cfg", st); - configuration::applier::state::instance().apply(st); + parser.parse("/tmp/test-config.cfg", st, err); + configuration::applier::state::instance().apply(st, err); init_macros(); std::string out; @@ -457,6 +466,7 @@ TEST_F(Macro, RetentionDataFile) { TEST_F(Macro, TempFile) { configuration::parser parser; configuration::state st; + configuration::error_cnt err; std::remove("/tmp/test-config.cfg"); @@ -464,8 +474,8 @@ TEST_F(Macro, TempFile) { ofs << "log_file=\"\"" << std::endl; ofs.close(); - parser.parse("/tmp/test-config.cfg", st); - configuration::applier::state::instance().apply(st); + parser.parse("/tmp/test-config.cfg", st, err); + configuration::applier::state::instance().apply(st, err); init_macros(); std::string out; @@ -477,6 +487,7 @@ TEST_F(Macro, TempFile) { TEST_F(Macro, LogFile) { configuration::parser parser; configuration::state st; + configuration::error_cnt err; std::remove("/tmp/test-config.cfg"); @@ -484,8 +495,8 @@ TEST_F(Macro, LogFile) { ofs << "log_file=/tmp/centengine.log" << std::endl; ofs.close(); - parser.parse("/tmp/test-config.cfg", st); - configuration::applier::state::instance().apply(st); + parser.parse("/tmp/test-config.cfg", st, err); + configuration::applier::state::instance().apply(st, err); init_macros(); std::string out; @@ -497,6 +508,7 @@ TEST_F(Macro, LogFile) { TEST_F(Macro, CommandFile) { configuration::parser parser; configuration::state st; + configuration::error_cnt err; std::remove("/tmp/test-config.cfg"); @@ -505,8 +517,8 @@ TEST_F(Macro, CommandFile) { ofs << "log_file=\"\"" << std::endl; ofs.close(); - parser.parse("/tmp/test-config.cfg", st); - configuration::applier::state::instance().apply(st); + parser.parse("/tmp/test-config.cfg", st, err); + configuration::applier::state::instance().apply(st, err); init_macros(); std::string out; @@ -518,6 +530,7 @@ TEST_F(Macro, CommandFile) { TEST_F(Macro, TempPath) { configuration::parser parser; configuration::state st; + configuration::error_cnt err; std::remove("/tmp/test-config.cfg"); @@ -525,8 +538,8 @@ TEST_F(Macro, TempPath) { ofs << "log_file=\"\"" << std::endl; ofs.close(); - parser.parse("/tmp/test-config.cfg", st); - configuration::applier::state::instance().apply(st); + parser.parse("/tmp/test-config.cfg", st, err); + configuration::applier::state::instance().apply(st, err); init_macros(); std::string out; @@ -536,18 +549,19 @@ TEST_F(Macro, TempPath) { } TEST_F(Macro, ContactGroupName) { + configuration::error_cnt err; configuration::applier::contact ct_aply; configuration::contact ctct{new_configuration_contact("test_contact", true)}; ct_aply.add_object(ctct); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct); + ct_aply.resolve_object(ctct, err); configuration::applier::contactgroup cg_aply; configuration::contactgroup cg{ new_configuration_contactgroup("test_cg", "test_contact")}; cg_aply.add_object(cg); cg_aply.expand_objects(*config); - cg_aply.resolve_object(cg); + cg_aply.resolve_object(cg, err); init_macros(); int now{500000000}; @@ -560,18 +574,19 @@ TEST_F(Macro, ContactGroupName) { } TEST_F(Macro, ContactGroupAlias) { + configuration::error_cnt err; configuration::applier::contact ct_aply; configuration::contact ctct{new_configuration_contact("test_contact", true)}; ct_aply.add_object(ctct); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct); + ct_aply.resolve_object(ctct, err); configuration::applier::contactgroup cg_aply; configuration::contactgroup cg{ new_configuration_contactgroup("test_cg", "test_contact")}; cg_aply.add_object(cg); cg_aply.expand_objects(*config); - cg_aply.resolve_object(cg); + cg_aply.resolve_object(cg, err); init_macros(); int now{500000000}; set_time(now); @@ -587,14 +602,15 @@ TEST_F(Macro, ContactGroupMembers) { configuration::contact ctct{new_configuration_contact("test_contact", true)}; ct_aply.add_object(ctct); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct); + configuration::error_cnt err; + ct_aply.resolve_object(ctct, err); configuration::applier::contactgroup cg_aply; configuration::contactgroup cg{ new_configuration_contactgroup("test_cg", "test_contact")}; cg_aply.add_object(cg); cg_aply.expand_objects(*config); - cg_aply.resolve_object(cg); + cg_aply.resolve_object(cg, err); init_macros(); int now{500000000}; set_time(now); @@ -606,18 +622,19 @@ TEST_F(Macro, ContactGroupMembers) { } TEST_F(Macro, ContactGroupNames) { + configuration::error_cnt err; configuration::applier::contact ct_aply; configuration::contact ctct{new_configuration_contact("test_contact", true)}; ct_aply.add_object(ctct); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct); + ct_aply.resolve_object(ctct, err); configuration::applier::contactgroup cg_aply; configuration::contactgroup cg{ new_configuration_contactgroup("test_cg", "test_contact")}; cg_aply.add_object(cg); cg_aply.expand_objects(*config); - cg_aply.resolve_object(cg); + cg_aply.resolve_object(cg, err); init_macros(); int now{500000000}; set_time(now); @@ -637,13 +654,14 @@ TEST_F(Macro, NotificationRecipients) { new_configuration_contact("admin1", false, "c,r")}; ct_aply.add_object(ctct1); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct); - ct_aply.resolve_object(ctct1); + configuration::error_cnt err; + ct_aply.resolve_object(ctct, err); + ct_aply.resolve_object(ctct1, err); configuration::contact ctct2{ new_configuration_contact("test_contact", false)}; ct_aply.add_object(ctct2); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct2); + ct_aply.resolve_object(ctct2, err); configuration::host hst{new_configuration_host("test_host", "admin")}; configuration::applier::host hst_aply; @@ -654,8 +672,8 @@ TEST_F(Macro, NotificationRecipients) { configuration::applier::service svc_aply; svc_aply.add_object(svc); - hst_aply.resolve_object(hst); - svc_aply.resolve_object(svc); + hst_aply.resolve_object(hst, err); + svc_aply.resolve_object(svc, err); host_map const& hm{engine::host::hosts}; _host3 = hm.begin()->second; @@ -683,6 +701,7 @@ TEST_F(Macro, NotificationRecipients) { } TEST_F(Macro, NotificationAuthor) { + configuration::error_cnt err; init_macros(); configuration::applier::contact ct_aply; configuration::contact ctct{new_configuration_contact("admin", true)}; @@ -691,13 +710,13 @@ TEST_F(Macro, NotificationAuthor) { new_configuration_contact("admin1", false, "c,r")}; ct_aply.add_object(ctct1); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct); - ct_aply.resolve_object(ctct1); + ct_aply.resolve_object(ctct, err); + ct_aply.resolve_object(ctct1, err); configuration::contact ctct2{ new_configuration_contact("test_contact", false)}; ct_aply.add_object(ctct2); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct2); + ct_aply.resolve_object(ctct2, err); configuration::host hst{new_configuration_host("test_host", "admin")}; configuration::applier::host hst_aply; @@ -708,8 +727,8 @@ TEST_F(Macro, NotificationAuthor) { configuration::applier::service svc_aply; svc_aply.add_object(svc); - hst_aply.resolve_object(hst); - svc_aply.resolve_object(svc); + hst_aply.resolve_object(hst, err); + svc_aply.resolve_object(svc, err); host_map const& hm{engine::host::hosts}; _host3 = hm.begin()->second; @@ -737,6 +756,7 @@ TEST_F(Macro, NotificationAuthor) { } TEST_F(Macro, NotificationAuthorName) { + configuration::error_cnt err; init_macros(); configuration::applier::contact ct_aply; configuration::contact ctct{new_configuration_contact("admin", true)}; @@ -745,13 +765,13 @@ TEST_F(Macro, NotificationAuthorName) { new_configuration_contact("admin1", false, "c,r")}; ct_aply.add_object(ctct1); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct); - ct_aply.resolve_object(ctct1); + ct_aply.resolve_object(ctct, err); + ct_aply.resolve_object(ctct1, err); configuration::contact ctct2{ new_configuration_contact("test_contact", false)}; ct_aply.add_object(ctct2); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct2); + ct_aply.resolve_object(ctct2, err); configuration::host hst{new_configuration_host("test_host", "admin")}; configuration::applier::host hst_aply; @@ -762,8 +782,8 @@ TEST_F(Macro, NotificationAuthorName) { configuration::applier::service svc_aply; svc_aply.add_object(svc); - hst_aply.resolve_object(hst); - svc_aply.resolve_object(svc); + hst_aply.resolve_object(hst, err); + svc_aply.resolve_object(svc, err); host_map const& hm{engine::host::hosts}; _host3 = hm.begin()->second; @@ -790,6 +810,7 @@ TEST_F(Macro, NotificationAuthorName) { } TEST_F(Macro, NotificationAuthorAlias) { + configuration::error_cnt err; init_macros(); configuration::applier::contact ct_aply; configuration::contact ctct{new_configuration_contact("admin", true)}; @@ -798,13 +819,13 @@ TEST_F(Macro, NotificationAuthorAlias) { new_configuration_contact("admin1", false, "c,r")}; ct_aply.add_object(ctct1); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct); - ct_aply.resolve_object(ctct1); + ct_aply.resolve_object(ctct, err); + ct_aply.resolve_object(ctct1, err); configuration::contact ctct2{ new_configuration_contact("test_contact", false)}; ct_aply.add_object(ctct2); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct2); + ct_aply.resolve_object(ctct2, err); configuration::host hst{new_configuration_host("test_host", "admin")}; configuration::applier::host hst_aply; @@ -815,8 +836,8 @@ TEST_F(Macro, NotificationAuthorAlias) { configuration::applier::service svc_aply; svc_aply.add_object(svc); - hst_aply.resolve_object(hst); - svc_aply.resolve_object(svc); + hst_aply.resolve_object(hst, err); + svc_aply.resolve_object(svc, err); host_map const& hm{engine::host::hosts}; _host3 = hm.begin()->second; @@ -843,6 +864,7 @@ TEST_F(Macro, NotificationAuthorAlias) { } TEST_F(Macro, NotificationComment) { + configuration::error_cnt err; init_macros(); configuration::applier::contact ct_aply; configuration::contact ctct{new_configuration_contact("admin", true)}; @@ -851,13 +873,13 @@ TEST_F(Macro, NotificationComment) { new_configuration_contact("admin1", false, "c,r")}; ct_aply.add_object(ctct1); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct); - ct_aply.resolve_object(ctct1); + ct_aply.resolve_object(ctct, err); + ct_aply.resolve_object(ctct1, err); configuration::contact ctct2{ new_configuration_contact("test_contact", false)}; ct_aply.add_object(ctct2); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct2); + ct_aply.resolve_object(ctct2, err); configuration::host hst{new_configuration_host("test_host", "admin")}; configuration::applier::host hst_aply; @@ -868,8 +890,8 @@ TEST_F(Macro, NotificationComment) { configuration::applier::service svc_aply; svc_aply.add_object(svc); - hst_aply.resolve_object(hst); - svc_aply.resolve_object(svc); + hst_aply.resolve_object(hst, err); + svc_aply.resolve_object(svc, err); host_map const& hm{engine::host::hosts}; _host3 = hm.begin()->second; diff --git a/engine/tests/macros/macro_hostname.cc b/engine/tests/macros/macro_hostname.cc index 4d5010cb06c..4a57cec5449 100644 --- a/engine/tests/macros/macro_hostname.cc +++ b/engine/tests/macros/macro_hostname.cc @@ -19,6 +19,7 @@ #include #include +#include "com/centreon/engine/configuration/state.hh" #include "com/centreon/engine/globals.hh" #include @@ -518,6 +519,7 @@ TEST_F(MacroHostname, HostPercentChange) { } TEST_F(MacroHostname, HostGroupName) { + configuration::error_cnt err; configuration::applier::hostgroup hg_aply; configuration::applier::host hst_aply; configuration::hostgroup hg; @@ -543,9 +545,9 @@ TEST_F(MacroHostname, HostGroupName) { ASSERT_NO_THROW(hst_aply.expand_objects(*config)); ASSERT_NO_THROW(hg_aply.expand_objects(*config)); - ASSERT_NO_THROW(hst_aply.resolve_object(hst_a)); - ASSERT_NO_THROW(hst_aply.resolve_object(hst_c)); - ASSERT_NO_THROW(hg_aply.resolve_object(hg)); + ASSERT_NO_THROW(hst_aply.resolve_object(hst_a, err)); + ASSERT_NO_THROW(hst_aply.resolve_object(hst_c, err)); + ASSERT_NO_THROW(hg_aply.resolve_object(hg, err)); int now{500000000}; set_time(now); @@ -584,9 +586,10 @@ TEST_F(MacroHostname, HostGroupAlias) { ASSERT_NO_THROW(hst_aply.expand_objects(*config)); ASSERT_NO_THROW(hg_aply.expand_objects(*config)); - ASSERT_NO_THROW(hst_aply.resolve_object(hst_a)); - ASSERT_NO_THROW(hst_aply.resolve_object(hst_c)); - ASSERT_NO_THROW(hg_aply.resolve_object(hg)); + configuration::error_cnt err; + ASSERT_NO_THROW(hst_aply.resolve_object(hst_a, err)); + ASSERT_NO_THROW(hst_aply.resolve_object(hst_c, err)); + ASSERT_NO_THROW(hg_aply.resolve_object(hg, err)); int now{500000000}; set_time(now); @@ -693,6 +696,7 @@ TEST_F(MacroHostname, HostCheckCommand) { TEST_F(MacroHostname, HostPerDataFile) { configuration::parser parser; configuration::state st; + configuration::error_cnt err; std::remove("/tmp/test-config.cfg"); @@ -702,8 +706,8 @@ TEST_F(MacroHostname, HostPerDataFile) { ofs << "log_file=\"\"" << std::endl; ofs.close(); - parser.parse("/tmp/test-config.cfg", st); - configuration::applier::state::instance().apply(st); + parser.parse("/tmp/test-config.cfg", st, err); + configuration::applier::state::instance().apply(st, err); init_macros(); std::string out; @@ -1095,9 +1099,10 @@ TEST_F(MacroHostname, HostGroupNames) { ASSERT_NO_THROW(hst_aply.expand_objects(*config)); ASSERT_NO_THROW(hg_aply.expand_objects(*config)); - ASSERT_NO_THROW(hst_aply.resolve_object(hst_a)); - ASSERT_NO_THROW(hst_aply.resolve_object(hst_c)); - ASSERT_NO_THROW(hg_aply.resolve_object(hg)); + configuration::error_cnt err; + ASSERT_NO_THROW(hst_aply.resolve_object(hst_a, err)); + ASSERT_NO_THROW(hst_aply.resolve_object(hst_c, err)); + ASSERT_NO_THROW(hg_aply.resolve_object(hg, err)); int now{500000000}; set_time(now); @@ -1256,9 +1261,10 @@ TEST_F(MacroHostname, HostGroupNotes) { ASSERT_NO_THROW(hst_aply.expand_objects(*config)); ASSERT_NO_THROW(hg_aply.expand_objects(*config)); - ASSERT_NO_THROW(hst_aply.resolve_object(hst_a)); - ASSERT_NO_THROW(hst_aply.resolve_object(hst_c)); - ASSERT_NO_THROW(hg_aply.resolve_object(hg)); + configuration::error_cnt err; + ASSERT_NO_THROW(hst_aply.resolve_object(hst_a, err)); + ASSERT_NO_THROW(hst_aply.resolve_object(hst_c, err)); + ASSERT_NO_THROW(hg_aply.resolve_object(hg, err)); int now{500000000}; set_time(now); @@ -1297,9 +1303,10 @@ TEST_F(MacroHostname, HostGroupNotesUrl) { ASSERT_NO_THROW(hst_aply.expand_objects(*config)); ASSERT_NO_THROW(hg_aply.expand_objects(*config)); - ASSERT_NO_THROW(hst_aply.resolve_object(hst_a)); - ASSERT_NO_THROW(hst_aply.resolve_object(hst_c)); - ASSERT_NO_THROW(hg_aply.resolve_object(hg)); + configuration::error_cnt err; + ASSERT_NO_THROW(hst_aply.resolve_object(hst_a, err)); + ASSERT_NO_THROW(hst_aply.resolve_object(hst_c, err)); + ASSERT_NO_THROW(hg_aply.resolve_object(hg, err)); int now{500000000}; set_time(now); @@ -1338,9 +1345,10 @@ TEST_F(MacroHostname, HostGroupActionUrl) { ASSERT_NO_THROW(hst_aply.expand_objects(*config)); ASSERT_NO_THROW(hg_aply.expand_objects(*config)); - ASSERT_NO_THROW(hst_aply.resolve_object(hst_a)); - ASSERT_NO_THROW(hst_aply.resolve_object(hst_c)); - ASSERT_NO_THROW(hg_aply.resolve_object(hg)); + configuration::error_cnt err; + ASSERT_NO_THROW(hst_aply.resolve_object(hst_a, err)); + ASSERT_NO_THROW(hst_aply.resolve_object(hst_c, err)); + ASSERT_NO_THROW(hg_aply.resolve_object(hg, err)); int now{500000000}; set_time(now); @@ -1379,9 +1387,10 @@ TEST_F(MacroHostname, HostGroupMembers) { ASSERT_NO_THROW(hst_aply.expand_objects(*config)); ASSERT_NO_THROW(hg_aply.expand_objects(*config)); - ASSERT_NO_THROW(hst_aply.resolve_object(hst_a)); - ASSERT_NO_THROW(hst_aply.resolve_object(hst_c)); - ASSERT_NO_THROW(hg_aply.resolve_object(hg)); + configuration::error_cnt err; + ASSERT_NO_THROW(hst_aply.resolve_object(hst_a, err)); + ASSERT_NO_THROW(hst_aply.resolve_object(hst_c, err)); + ASSERT_NO_THROW(hg_aply.resolve_object(hg, err)); int now{500000000}; set_time(now); @@ -1522,9 +1531,10 @@ TEST_F(MacroHostname, HostChildren) { ASSERT_EQ(engine::host::hosts.size(), 2u); + configuration::error_cnt err; hst_aply.expand_objects(*config); - hst_aply.resolve_object(hst_child); - hst_aply.resolve_object(hst_parent); + hst_aply.resolve_object(hst_child, err); + hst_aply.resolve_object(hst_parent, err); int now{500000000}; set_time(now); diff --git a/engine/tests/macros/macro_service.cc b/engine/tests/macros/macro_service.cc index f1b1df136f7..01be150cfc9 100644 --- a/engine/tests/macros/macro_service.cc +++ b/engine/tests/macros/macro_service.cc @@ -19,6 +19,7 @@ #include #include +#include "com/centreon/engine/configuration/state.hh" #include "com/centreon/engine/globals.hh" #include @@ -723,12 +724,13 @@ TEST_F(MacroService, ServiceGroupName) { // We fake here the expand_object on configuration::service svc.set_host_id(12); + configuration::error_cnt err; aply_svc.add_object(svc); ASSERT_TRUE(svc.parse("servicegroups", "test_group")); grp.parse("members", "test_host,test"); aply_grp.add_object(grp); aply_grp.expand_objects(*config); - ASSERT_NO_THROW(aply_grp.resolve_object(grp)); + ASSERT_NO_THROW(aply_grp.resolve_object(grp, err)); init_macros(); int now{500000000}; @@ -763,13 +765,14 @@ TEST_F(MacroService, ServiceGroupAlias) { // We fake here the expand_object on configuration::service svc.set_host_id(12); + configuration::error_cnt err; aply_svc.add_object(svc); ASSERT_TRUE(svc.parse("servicegroups", "test_group")); grp.parse("members", "test_host,test"); grp.parse("alias", "test_group_alias"); aply_grp.add_object(grp); aply_grp.expand_objects(*config); - ASSERT_NO_THROW(aply_grp.resolve_object(grp)); + ASSERT_NO_THROW(aply_grp.resolve_object(grp, err)); init_macros(); int now{500000000}; @@ -969,6 +972,7 @@ TEST_F(MacroService, ServiceCheckCommand) { TEST_F(MacroService, ServicePerfDataFile) { configuration::parser parser; configuration::state st; + configuration::error_cnt err; std::remove("/tmp/test-config.cfg"); @@ -978,8 +982,8 @@ TEST_F(MacroService, ServicePerfDataFile) { ofs << "log_file=\"\"" << std::endl; ofs.close(); - parser.parse("/tmp/test-config.cfg", st); - configuration::applier::state::instance().apply(st); + parser.parse("/tmp/test-config.cfg", st, err); + configuration::applier::state::instance().apply(st, err); init_macros(); std::string out; @@ -1636,12 +1640,13 @@ TEST_F(MacroService, ServiceGroupNames) { // We fake here the expand_object on configuration::service svc.set_host_id(12); + configuration::error_cnt err; aply_svc.add_object(svc); ASSERT_TRUE(svc.parse("servicegroups", "test_group")); grp.parse("members", "test_host,test"); aply_grp.add_object(grp); aply_grp.expand_objects(*config); - ASSERT_NO_THROW(aply_grp.resolve_object(grp)); + ASSERT_NO_THROW(aply_grp.resolve_object(grp, err)); init_macros(); int now{500000000}; @@ -1716,13 +1721,14 @@ TEST_F(MacroService, ServiceGroupNotes) { // We fake here the expand_object on configuration::service svc.set_host_id(12); + configuration::error_cnt err; aply_svc.add_object(svc); ASSERT_TRUE(svc.parse("servicegroups", "test_group")); grp.parse("members", "test_host,test"); ASSERT_TRUE(grp.parse("notes", "test_notes")); aply_grp.add_object(grp); aply_grp.expand_objects(*config); - ASSERT_NO_THROW(aply_grp.resolve_object(grp)); + ASSERT_NO_THROW(aply_grp.resolve_object(grp, err)); init_macros(); int now{500000000}; set_time(now); @@ -1758,13 +1764,14 @@ TEST_F(MacroService, ServiceGroupNotesUrl) { // We fake here the expand_object on configuration::service svc.set_host_id(12); + configuration::error_cnt err; aply_svc.add_object(svc); ASSERT_TRUE(svc.parse("servicegroups", "test_group")); grp.parse("members", "test_host,test"); ASSERT_TRUE(grp.parse("notes_url", "test_notes_url")); aply_grp.add_object(grp); aply_grp.expand_objects(*config); - ASSERT_NO_THROW(aply_grp.resolve_object(grp)); + ASSERT_NO_THROW(aply_grp.resolve_object(grp, err)); init_macros(); int now{500000000}; set_time(now); @@ -1798,13 +1805,14 @@ TEST_F(MacroService, ServiceGroupActionUrl) { // We fake here the expand_object on configuration::service svc.set_host_id(12); + configuration::error_cnt err; aply_svc.add_object(svc); ASSERT_TRUE(svc.parse("servicegroups", "test_group")); grp.parse("members", "test_host,test"); ASSERT_TRUE(grp.parse("action_url", "test_notes_url")); aply_grp.add_object(grp); aply_grp.expand_objects(*config); - ASSERT_NO_THROW(aply_grp.resolve_object(grp)); + ASSERT_NO_THROW(aply_grp.resolve_object(grp, err)); init_macros(); int now{500000000}; set_time(now); @@ -1838,13 +1846,14 @@ TEST_F(MacroService, ServiceGroupMembers) { // We fake here the expand_object on configuration::service svc.set_host_id(12); + configuration::error_cnt err; aply_svc.add_object(svc); ASSERT_TRUE(svc.parse("servicegroups", "test_group")); grp.parse("members", "test_host,test"); ASSERT_TRUE(grp.parse("action_url", "test_notes_url")); aply_grp.add_object(grp); aply_grp.expand_objects(*config); - ASSERT_NO_THROW(aply_grp.resolve_object(grp)); + ASSERT_NO_THROW(aply_grp.resolve_object(grp, err)); init_macros(); int now{500000000}; set_time(now); @@ -2010,6 +2019,7 @@ TEST_F(MacroService, LastServiceStateId) { TEST_F(MacroService, ServiceProblemID) { init_macros(); + configuration::error_cnt err; configuration::applier::contact ct_aply; configuration::contact ctct{new_configuration_contact("admin", true)}; ct_aply.add_object(ctct); @@ -2017,8 +2027,8 @@ TEST_F(MacroService, ServiceProblemID) { new_configuration_contact("admin1", false, "c,r")}; ct_aply.add_object(ctct1); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct); - ct_aply.resolve_object(ctct1); + ct_aply.resolve_object(ctct, err); + ct_aply.resolve_object(ctct1, err); configuration::host hst{new_configuration_host("test_host", "admin")}; configuration::applier::host hst_aply; @@ -2029,8 +2039,8 @@ TEST_F(MacroService, ServiceProblemID) { configuration::applier::service svc_aply; svc_aply.add_object(svc); - hst_aply.resolve_object(hst); - svc_aply.resolve_object(svc); + hst_aply.resolve_object(hst, err); + svc_aply.resolve_object(svc, err); host_map const& hm{engine::host::hosts}; _host3 = hm.begin()->second; diff --git a/engine/tests/notifications/host_downtime_notification.cc b/engine/tests/notifications/host_downtime_notification.cc index 61f2003faa5..a4f2a32a4c9 100644 --- a/engine/tests/notifications/host_downtime_notification.cc +++ b/engine/tests/notifications/host_downtime_notification.cc @@ -42,18 +42,19 @@ using namespace com::centreon::engine::configuration::applier; class HostDowntimeNotification : public TestEngine { public: void SetUp() override { + error_cnt err; init_config_state(); configuration::applier::contact ct_aply; configuration::contact ctct{new_configuration_contact("admin", true)}; ct_aply.add_object(ctct); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct); + ct_aply.resolve_object(ctct, err); configuration::host hst{new_configuration_host("test_host", "admin")}; configuration::applier::host aply; aply.add_object(hst); - aply.resolve_object(hst); + aply.resolve_object(hst, err); host_map const& hm{engine::host::hosts}; _host = hm.begin()->second; diff --git a/engine/tests/notifications/host_flapping_notification.cc b/engine/tests/notifications/host_flapping_notification.cc index 0f9b7e6c3e3..f670d0bb46c 100644 --- a/engine/tests/notifications/host_flapping_notification.cc +++ b/engine/tests/notifications/host_flapping_notification.cc @@ -26,6 +26,7 @@ #include "com/centreon/engine/configuration/applier/contact.hh" #include "com/centreon/engine/configuration/applier/host.hh" #include "com/centreon/engine/configuration/host.hh" +#include "com/centreon/engine/configuration/state.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/host.hh" #include "com/centreon/engine/hostescalation.hh" @@ -40,13 +41,14 @@ using namespace com::centreon::engine::configuration::applier; class HostFlappingNotification : public TestEngine { public: void SetUp() override { + configuration::error_cnt err; init_config_state(); configuration::applier::contact ct_aply; configuration::contact ctct{new_configuration_contact("admin", true)}; ct_aply.add_object(ctct); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct); + ct_aply.resolve_object(ctct, err); configuration::applier::host hst_aply; configuration::host hst; @@ -55,7 +57,7 @@ class HostFlappingNotification : public TestEngine { hst.parse("_HOST_ID", "12"); hst.parse("contacts", "admin"); hst_aply.add_object(hst); - hst_aply.resolve_object(hst); + hst_aply.resolve_object(hst, err); host_map const& hm{engine::host::hosts}; _host = hm.begin()->second; _host->set_current_state(engine::host::state_up); @@ -70,7 +72,7 @@ class HostFlappingNotification : public TestEngine { hst_child.parse("_HOST_ID", "13"); hst_child.parse("contacts", "admin"); hst_aply.add_object(hst_child); - hst_aply.resolve_object(hst_child); + hst_aply.resolve_object(hst_child, err); _host2 = hm.begin()->second; _host2->set_current_state(engine::host::state_up); diff --git a/engine/tests/notifications/host_normal_notification.cc b/engine/tests/notifications/host_normal_notification.cc index c53cbd34795..67b513bd6dc 100644 --- a/engine/tests/notifications/host_normal_notification.cc +++ b/engine/tests/notifications/host_normal_notification.cc @@ -56,16 +56,17 @@ class HostNotification : public TestEngine { events_logger->set_level(spdlog::level::off); + error_cnt err; configuration::applier::contact ct_aply; configuration::contact ctct{new_configuration_contact("admin", true)}; ct_aply.add_object(ctct); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct); + ct_aply.resolve_object(ctct, err); configuration::host hst{new_configuration_host("test_host", "admin")}; configuration::applier::host hst_aply; hst_aply.add_object(hst); - hst_aply.resolve_object(hst); + hst_aply.resolve_object(hst, err); host_map const& hm{engine::host::hosts}; _host = hm.begin()->second; _host->set_current_state(engine::host::state_up); @@ -557,25 +558,26 @@ TEST_F(HostNotification, CheckFirstNotificationDelay) { // Then contacts from the escalation are notified when notification number // is in [2,6] and are separated by at less 4*60s. TEST_F(HostNotification, HostEscalation) { + error_cnt err; configuration::applier::contact ct_aply; configuration::contact ctct{new_configuration_contact("test_contact", false)}; ct_aply.add_object(ctct); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct); + ct_aply.resolve_object(ctct, err); configuration::applier::contactgroup cg_aply; configuration::contactgroup cg{ new_configuration_contactgroup("test_cg", "test_contact")}; cg_aply.add_object(cg); cg_aply.expand_objects(*config); - cg_aply.resolve_object(cg); + cg_aply.resolve_object(cg, err); configuration::applier::hostescalation he_aply; configuration::hostescalation he{ new_configuration_hostescalation("test_host", "test_cg")}; he_aply.add_object(he); he_aply.expand_objects(*config); - he_aply.resolve_object(he); + he_aply.resolve_object(he, err); int now{50000}; set_time(now); @@ -682,36 +684,37 @@ TEST_F(HostNotification, HostEscalation) { } TEST_F(HostNotification, HostDependency) { + error_cnt err; configuration::applier::contact ct_aply; configuration::contact ctct{new_configuration_contact("test_contact", false)}; ct_aply.add_object(ctct); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct); + ct_aply.resolve_object(ctct, err); configuration::applier::contactgroup cg_aply; configuration::contactgroup cg{ new_configuration_contactgroup("test_cg", "test_contact")}; cg_aply.add_object(cg); cg_aply.expand_objects(*config); - cg_aply.resolve_object(cg); + cg_aply.resolve_object(cg, err); configuration::applier::host h_aply; configuration::host h{new_configuration_host("dep_host", "admin", 15)}; h_aply.add_object(h); h_aply.expand_objects(*config); - h_aply.resolve_object(h); + h_aply.resolve_object(h, err); configuration::applier::hostdependency hd_aply; configuration::hostdependency hd{ new_configuration_hostdependency("test_host", "dep_host")}; hd_aply.expand_objects(*config); hd_aply.add_object(hd); - hd_aply.resolve_object(hd); + hd_aply.resolve_object(hd, err); int now{50000}; set_time(now); - int w{0}, e{0}; + uint32_t w = 0, e = 0; pre_flight_circular_check(&w, &e); ASSERT_EQ(w, 0); @@ -823,25 +826,26 @@ TEST_F(HostNotification, HostDependency) { // is sent 1 time // Then both are sent to contacts from the escalation. TEST_F(HostNotification, HostEscalationOneTime) { + error_cnt err; configuration::applier::contact ct_aply; configuration::contact ctct{new_configuration_contact("test_contact", false)}; ct_aply.add_object(ctct); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct); + ct_aply.resolve_object(ctct, err); configuration::applier::contactgroup cg_aply; configuration::contactgroup cg{ new_configuration_contactgroup("test_cg", "test_contact")}; cg_aply.add_object(cg); cg_aply.expand_objects(*config); - cg_aply.resolve_object(cg); + cg_aply.resolve_object(cg, err); configuration::applier::hostescalation he_aply; configuration::hostescalation he{ new_configuration_hostescalation("test_host", "test_cg", 1, 0)}; he_aply.add_object(he); he_aply.expand_objects(*config); - he_aply.resolve_object(he); + he_aply.resolve_object(he, err); int now{50000}; set_time(now); @@ -918,25 +922,26 @@ TEST_F(HostNotification, HostEscalationOneTime) { // is sent 1 time // Then both are sent to contacts from the escalation. TEST_F(HostNotification, HostEscalationOneTimeNotifInter0) { + error_cnt err; configuration::applier::contact ct_aply; configuration::contact ctct{new_configuration_contact("test_contact", false)}; ct_aply.add_object(ctct); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct); + ct_aply.resolve_object(ctct, err); configuration::applier::contactgroup cg_aply; configuration::contactgroup cg{ new_configuration_contactgroup("test_cg", "test_contact")}; cg_aply.add_object(cg); cg_aply.expand_objects(*config); - cg_aply.resolve_object(cg); + cg_aply.resolve_object(cg, err); configuration::applier::hostescalation he_aply; configuration::hostescalation he{ new_configuration_hostescalation("test_host", "test_cg", 1, 0, 0)}; he_aply.add_object(he); he_aply.expand_objects(*config); - he_aply.resolve_object(he); + he_aply.resolve_object(he, err); int now{50000}; set_time(now); @@ -1013,25 +1018,26 @@ TEST_F(HostNotification, HostEscalationOneTimeNotifInter0) { // is sent 1 time // Then both are sent to contacts from the escalation. TEST_F(HostNotification, HostEscalationRetention) { + error_cnt err; configuration::applier::contact ct_aply; configuration::contact ctct{new_configuration_contact("test_contact", false)}; ct_aply.add_object(ctct); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct); + ct_aply.resolve_object(ctct, err); configuration::applier::contactgroup cg_aply; configuration::contactgroup cg{ new_configuration_contactgroup("test_cg", "test_contact")}; cg_aply.add_object(cg); cg_aply.expand_objects(*config); - cg_aply.resolve_object(cg); + cg_aply.resolve_object(cg, err); configuration::applier::hostescalation he_aply; configuration::hostescalation he{ new_configuration_hostescalation("test_host", "test_cg", 1, 0, 0)}; he_aply.add_object(he); he_aply.expand_objects(*config); - he_aply.resolve_object(he); + he_aply.resolve_object(he, err); int now{50000}; set_time(now); diff --git a/engine/tests/notifications/service_downtime_notification_test.cc b/engine/tests/notifications/service_downtime_notification_test.cc index f0bd0266fd4..003b497d863 100644 --- a/engine/tests/notifications/service_downtime_notification_test.cc +++ b/engine/tests/notifications/service_downtime_notification_test.cc @@ -50,12 +50,13 @@ class ServiceDowntimeNotification : public TestEngine { public: void SetUp() override { init_config_state(); + error_cnt err; configuration::applier::contact ct_aply; configuration::contact ctct{new_configuration_contact("admin", true)}; ct_aply.add_object(ctct); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct); + ct_aply.resolve_object(ctct, err); configuration::host hst{new_configuration_host("test_host", "admin")}; configuration::applier::host hst_aply; @@ -66,8 +67,8 @@ class ServiceDowntimeNotification : public TestEngine { configuration::applier::service svc_aply; svc_aply.add_object(svc); - hst_aply.resolve_object(hst); - svc_aply.resolve_object(svc); + hst_aply.resolve_object(hst, err); + svc_aply.resolve_object(svc, err); host_map const& hm{engine::host::hosts}; _host = hm.begin()->second; diff --git a/engine/tests/notifications/service_flapping_notification.cc b/engine/tests/notifications/service_flapping_notification.cc index 140d4690273..3d3f5563af0 100644 --- a/engine/tests/notifications/service_flapping_notification.cc +++ b/engine/tests/notifications/service_flapping_notification.cc @@ -45,13 +45,14 @@ using namespace com::centreon::engine::retention; class ServiceFlappingNotification : public TestEngine { public: void SetUp() override { + error_cnt err; init_config_state(); configuration::applier::contact ct_aply; configuration::contact ctct{new_configuration_contact("admin", true)}; ct_aply.add_object(ctct); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct); + ct_aply.resolve_object(ctct, err); configuration::applier::command cmd_aply; configuration::command cmd("cmd"); @@ -65,7 +66,7 @@ class ServiceFlappingNotification : public TestEngine { hst.parse("_HOST_ID", "12"); hst.parse("check_command", "cmd"); hst_aply.add_object(hst); - hst_aply.resolve_object(hst); + hst_aply.resolve_object(hst, err); configuration::applier::service svc_aply; configuration::service svc; @@ -79,7 +80,7 @@ class ServiceFlappingNotification : public TestEngine { svc.set_host_id(12); svc_aply.add_object(svc); - svc_aply.resolve_object(svc); + svc_aply.resolve_object(svc, err); service_map const& sv{engine::service::services}; diff --git a/engine/tests/notifications/service_normal_notification.cc b/engine/tests/notifications/service_normal_notification.cc index 2f1111e2f5e..d56a713cde6 100644 --- a/engine/tests/notifications/service_normal_notification.cc +++ b/engine/tests/notifications/service_normal_notification.cc @@ -50,6 +50,7 @@ class ServiceNotification : public TestEngine { public: void SetUp() override { init_config_state(); + error_cnt err; configuration::applier::contact ct_aply; configuration::contact ctct{new_configuration_contact("admin", true)}; @@ -58,8 +59,8 @@ class ServiceNotification : public TestEngine { new_configuration_contact("admin1", false, "c,r")}; ct_aply.add_object(ctct1); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct); - ct_aply.resolve_object(ctct1); + ct_aply.resolve_object(ctct, err); + ct_aply.resolve_object(ctct1, err); configuration::host hst{new_configuration_host("test_host", "admin")}; configuration::applier::host hst_aply; @@ -70,8 +71,8 @@ class ServiceNotification : public TestEngine { configuration::applier::service svc_aply; svc_aply.add_object(svc); - hst_aply.resolve_object(hst); - svc_aply.resolve_object(svc); + hst_aply.resolve_object(hst, err); + svc_aply.resolve_object(svc, err); host_map const& hm{engine::host::hosts}; _host = hm.begin()->second; @@ -759,21 +760,22 @@ TEST_F(ServiceNotification, ServiceEscalationCG) { configuration::contact ctct{new_configuration_contact("test_contact", false)}; ct_aply.add_object(ctct); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct); + error_cnt err; + ct_aply.resolve_object(ctct, err); configuration::applier::contactgroup cg_aply; configuration::contactgroup cg{ new_configuration_contactgroup("test_cg", "test_contact")}; cg_aply.add_object(cg); cg_aply.expand_objects(*config); - cg_aply.resolve_object(cg); + cg_aply.resolve_object(cg, err); configuration::applier::serviceescalation se_aply; configuration::serviceescalation se{ new_configuration_serviceescalation("test_host", "test_svc", "test_cg")}; se_aply.add_object(se); se_aply.expand_objects(*config); - se_aply.resolve_object(se); + se_aply.resolve_object(se, err); int now{50000}; set_time(now); diff --git a/engine/tests/notifications/service_timeperiod_notification.cc b/engine/tests/notifications/service_timeperiod_notification.cc index 4288dbda448..86b9a0376f3 100644 --- a/engine/tests/notifications/service_timeperiod_notification.cc +++ b/engine/tests/notifications/service_timeperiod_notification.cc @@ -38,6 +38,7 @@ #include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/configuration/host.hh" #include "com/centreon/engine/configuration/service.hh" +#include "com/centreon/engine/configuration/state.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/serviceescalation.hh" #include "com/centreon/engine/timeperiod.hh" @@ -53,6 +54,7 @@ using namespace com::centreon::engine::configuration::applier; class ServiceTimePeriodNotification : public TestEngine { public: void SetUp() override { + error_cnt err; init_config_state(); configuration::applier::contact ct_aply; @@ -62,8 +64,8 @@ class ServiceTimePeriodNotification : public TestEngine { new_configuration_contact("admin1", false, "c,r")}; ct_aply.add_object(ctct1); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct); - ct_aply.resolve_object(ctct1); + ct_aply.resolve_object(ctct, err); + ct_aply.resolve_object(ctct1, err); configuration::host hst{new_configuration_host("test_host", "admin")}; configuration::applier::host hst_aply; @@ -74,8 +76,8 @@ class ServiceTimePeriodNotification : public TestEngine { configuration::applier::service svc_aply; svc_aply.add_object(svc); - hst_aply.resolve_object(hst); - svc_aply.resolve_object(svc); + hst_aply.resolve_object(hst, err); + svc_aply.resolve_object(svc, err); host_map const& hm{engine::host::hosts}; _host = hm.begin()->second; @@ -119,6 +121,7 @@ class ServiceTimePeriodNotification : public TestEngine { // Then contacts from the escalation are notified when notification number // is in [2,6] and are separated by at less 4*60s. TEST_F(ServiceTimePeriodNotification, NoTimePeriodOk) { + error_cnt err; init_macros(); std::unique_ptr tperiod{ new engine::timeperiod("tperiod", "alias")}; @@ -129,21 +132,21 @@ TEST_F(ServiceTimePeriodNotification, NoTimePeriodOk) { configuration::contact ctct{new_configuration_contact("test_contact", false)}; ct_aply.add_object(ctct); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct); + ct_aply.resolve_object(ctct, err); configuration::applier::contactgroup cg_aply; configuration::contactgroup cg{ new_configuration_contactgroup("test_cg", "test_contact")}; cg_aply.add_object(cg); cg_aply.expand_objects(*config); - cg_aply.resolve_object(cg); + cg_aply.resolve_object(cg, err); configuration::applier::serviceescalation se_aply; configuration::serviceescalation se{ new_configuration_serviceescalation("test_host", "test_svc", "test_cg")}; se_aply.add_object(se); se_aply.expand_objects(*config); - se_aply.resolve_object(se); + se_aply.resolve_object(se, err); // uint64_t id{_svc->get_next_notification_id()}; for (int i = 0; i < 7; ++i) { @@ -223,6 +226,7 @@ TEST_F(ServiceTimePeriodNotification, NoTimePeriodOk) { } TEST_F(ServiceTimePeriodNotification, NoTimePeriodKo) { + error_cnt err; init_macros(); std::unique_ptr tperiod{ new engine::timeperiod("tperiod", "alias")}; @@ -233,14 +237,14 @@ TEST_F(ServiceTimePeriodNotification, NoTimePeriodKo) { configuration::contact ctct{new_configuration_contact("test_contact", false)}; ct_aply.add_object(ctct); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct); + ct_aply.resolve_object(ctct, err); configuration::applier::contactgroup cg_aply; configuration::contactgroup cg{ new_configuration_contactgroup("test_cg", "test_contact")}; cg_aply.add_object(cg); cg_aply.expand_objects(*config); - cg_aply.resolve_object(cg); + cg_aply.resolve_object(cg, err); configuration::applier::serviceescalation se_aply; configuration::serviceescalation se; @@ -253,7 +257,7 @@ TEST_F(ServiceTimePeriodNotification, NoTimePeriodKo) { se.parse("contact_groups", "test_cg"); se_aply.add_object(se); se_aply.expand_objects(*config); - se_aply.resolve_object(se); + se_aply.resolve_object(se, err); for (int i = 0; i < 7; ++i) { timerange_list list_time; list_time.emplace_back(35000, 85000); @@ -338,6 +342,7 @@ TEST_F(ServiceTimePeriodNotification, NoTimePeriodKo) { } TEST_F(ServiceTimePeriodNotification, TimePeriodOut) { + error_cnt err; init_macros(); std::unique_ptr tperiod{ new engine::timeperiod("tperiod", "alias")}; @@ -348,21 +353,21 @@ TEST_F(ServiceTimePeriodNotification, TimePeriodOut) { configuration::contact ctct{new_configuration_contact("test_contact", false)}; ct_aply.add_object(ctct); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct); + ct_aply.resolve_object(ctct, err); configuration::applier::contactgroup cg_aply; configuration::contactgroup cg{ new_configuration_contactgroup("test_cg", "test_contact")}; cg_aply.add_object(cg); cg_aply.expand_objects(*config); - cg_aply.resolve_object(cg); + cg_aply.resolve_object(cg, err); configuration::applier::serviceescalation se_aply; configuration::serviceescalation se{ new_configuration_serviceescalation("test_host", "test_svc", "test_cg")}; se_aply.add_object(se); se_aply.expand_objects(*config); - se_aply.resolve_object(se); + se_aply.resolve_object(se, err); // uint64_t id{_svc->get_next_notification_id()}; for (int i = 0; i < 7; ++i) { @@ -442,6 +447,7 @@ TEST_F(ServiceTimePeriodNotification, TimePeriodOut) { } TEST_F(ServiceTimePeriodNotification, TimePeriodUserOut) { + error_cnt err; init_macros(); std::unique_ptr tiperiod{ new engine::timeperiod("tperiod", "alias")}; @@ -473,21 +479,21 @@ TEST_F(ServiceTimePeriodNotification, TimePeriodUserOut) { ct_aply.add_object(ctct); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct); + ct_aply.resolve_object(ctct, err); configuration::applier::contactgroup cg_aply; configuration::contactgroup cg{ new_configuration_contactgroup("test_cg", "test_contact")}; cg_aply.add_object(cg); cg_aply.expand_objects(*config); - cg_aply.resolve_object(cg); + cg_aply.resolve_object(cg, err); configuration::applier::serviceescalation se_aply; configuration::serviceescalation se{ new_configuration_serviceescalation("test_host", "test_svc", "test_cg")}; se_aply.add_object(se); se_aply.expand_objects(*config); - se_aply.resolve_object(se); + se_aply.resolve_object(se, err); // uint64_t id{_svc->get_next_notification_id()}; for (int i = 0; i < 7; ++i) { @@ -566,6 +572,7 @@ TEST_F(ServiceTimePeriodNotification, TimePeriodUserOut) { } TEST_F(ServiceTimePeriodNotification, TimePeriodUserIn) { + error_cnt err; init_macros(); std::unique_ptr tiperiod{ new engine::timeperiod("tperiod", "alias")}; @@ -597,21 +604,21 @@ TEST_F(ServiceTimePeriodNotification, TimePeriodUserIn) { ct_aply.add_object(ctct); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct); + ct_aply.resolve_object(ctct, err); configuration::applier::contactgroup cg_aply; configuration::contactgroup cg{ new_configuration_contactgroup("test_cg", "test_contact")}; cg_aply.add_object(cg); cg_aply.expand_objects(*config); - cg_aply.resolve_object(cg); + cg_aply.resolve_object(cg, err); configuration::applier::serviceescalation se_aply; configuration::serviceescalation se{ new_configuration_serviceescalation("test_host", "test_svc", "test_cg")}; se_aply.add_object(se); se_aply.expand_objects(*config); - se_aply.resolve_object(se); + se_aply.resolve_object(se, err); // uint64_t id{_svc->get_next_notification_id()}; for (int i = 0; i < 7; ++i) { @@ -719,23 +726,24 @@ TEST_F(ServiceTimePeriodNotification, TimePeriodUserAll) { ctct.parse("host_notifications_enabled", "1"); ctct.parse("service_notifications_enabled", "1"); + error_cnt err; ct_aply.add_object(ctct); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct); + ct_aply.resolve_object(ctct, err); configuration::applier::contactgroup cg_aply; configuration::contactgroup cg{ new_configuration_contactgroup("test_cg", "test_contact")}; cg_aply.add_object(cg); cg_aply.expand_objects(*config); - cg_aply.resolve_object(cg); + cg_aply.resolve_object(cg, err); configuration::applier::serviceescalation se_aply; configuration::serviceescalation se{ new_configuration_serviceescalation("test_host", "test_svc", "test_cg")}; se_aply.add_object(se); se_aply.expand_objects(*config); - se_aply.resolve_object(se); + se_aply.resolve_object(se, err); // uint64_t id{_svc->get_next_notification_id()}; for (int i = 0; i < 7; ++i) { @@ -836,23 +844,24 @@ TEST_F(ServiceTimePeriodNotification, TimePeriodUserNone) { ctct.parse("host_notifications_enabled", "1"); ctct.parse("service_notifications_enabled", "1"); + error_cnt err; ct_aply.add_object(ctct); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct); + ct_aply.resolve_object(ctct, err); configuration::applier::contactgroup cg_aply; configuration::contactgroup cg{ new_configuration_contactgroup("test_cg", "test_contact")}; cg_aply.add_object(cg); cg_aply.expand_objects(*config); - cg_aply.resolve_object(cg); + cg_aply.resolve_object(cg, err); configuration::applier::serviceescalation se_aply; configuration::serviceescalation se{ new_configuration_serviceescalation("test_host", "test_svc", "test_cg")}; se_aply.add_object(se); se_aply.expand_objects(*config); - se_aply.resolve_object(se); + se_aply.resolve_object(se, err); // uint64_t id{_svc->get_next_notification_id()}; for (int i = 0; i < 7; ++i) { @@ -952,23 +961,24 @@ TEST_F(ServiceTimePeriodNotification, NoTimePeriodUser) { ctct.parse("host_notifications_enabled", "1"); ctct.parse("service_notifications_enabled", "1"); + error_cnt err; ct_aply.add_object(ctct); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct); + ct_aply.resolve_object(ctct, err); configuration::applier::contactgroup cg_aply; configuration::contactgroup cg{ new_configuration_contactgroup("test_cg", "test_contact")}; cg_aply.add_object(cg); cg_aply.expand_objects(*config); - cg_aply.resolve_object(cg); + cg_aply.resolve_object(cg, err); configuration::applier::serviceescalation se_aply; configuration::serviceescalation se{ new_configuration_serviceescalation("test_host", "test_svc", "test_cg")}; se_aply.add_object(se); se_aply.expand_objects(*config); - se_aply.resolve_object(se); + se_aply.resolve_object(se, err); // uint64_t id{_svc->get_next_notification_id()}; for (int i = 0; i < 7; ++i) { diff --git a/engine/tests/opentelemetry/open_telemetry_test.cc b/engine/tests/opentelemetry/open_telemetry_test.cc index 58603487909..14e2ec38470 100644 --- a/engine/tests/opentelemetry/open_telemetry_test.cc +++ b/engine/tests/opentelemetry/open_telemetry_test.cc @@ -114,13 +114,14 @@ void open_telemetry_test::SetUpTestSuite() { } void open_telemetry_test::SetUp() { + configuration::error_cnt err; init_config_state(); config->contacts().clear(); configuration::applier::contact ct_aply; configuration::contact ctct{new_configuration_contact("admin", true)}; ct_aply.add_object(ctct); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct); + ct_aply.resolve_object(ctct, err); configuration::host hst{new_configuration_host("localhost", "admin")}; configuration::applier::host hst_aply; @@ -131,8 +132,8 @@ void open_telemetry_test::SetUp() { configuration::applier::service svc_aply; svc_aply.add_object(svc); - hst_aply.resolve_object(hst); - svc_aply.resolve_object(svc); + hst_aply.resolve_object(hst, err); + svc_aply.resolve_object(svc, err); data_point_fifo::update_fifo_limit(std::numeric_limits::max(), 10); } diff --git a/engine/tests/opentelemetry/otl_converter_test.cc b/engine/tests/opentelemetry/otl_converter_test.cc index 8ebc07f4282..558970ad7fe 100644 --- a/engine/tests/opentelemetry/otl_converter_test.cc +++ b/engine/tests/opentelemetry/otl_converter_test.cc @@ -53,13 +53,14 @@ class otl_converter_test : public TestEngine { }; void otl_converter_test::SetUp() { + configuration::error_cnt err; init_config_state(); config->contacts().clear(); configuration::applier::contact ct_aply; configuration::contact ctct{new_configuration_contact("admin", true)}; ct_aply.add_object(ctct); ct_aply.expand_objects(*config); - ct_aply.resolve_object(ctct); + ct_aply.resolve_object(ctct, err); configuration::host hst{new_configuration_host("localhost", "admin")}; configuration::applier::host hst_aply; @@ -70,8 +71,8 @@ void otl_converter_test::SetUp() { configuration::applier::service svc_aply; svc_aply.add_object(svc); - hst_aply.resolve_object(hst); - svc_aply.resolve_object(svc); + hst_aply.resolve_object(hst, err); + svc_aply.resolve_object(svc, err); data_point_fifo::update_fifo_limit(std::numeric_limits::max(), 10); } From 7d96154b4181f8e9732191a6b6428b9655751adc Mon Sep 17 00:00:00 2001 From: jean-christophe81 <98889244+jean-christophe81@users.noreply.github.com> Date: Tue, 25 Jun 2024 09:53:39 +0200 Subject: [PATCH 50/60] feature(centagent): first centagent executable (#1464) * first centagent executable * use json configuration instead * centreon-agent => centreon-monitoring-agent * move process common * Apply suggestions from code review Co-authored-by: omercier <32134301+omercier@users.noreply.github.com> * github issue --------- Co-authored-by: omercier <32134301+omercier@users.noreply.github.com> --- .github/scripts/collect-unit-tests.sh | 1 + .github/workflows/centreon-collect.yml | 2 + .github/workflows/package-collect.yml | 5 +- .gitignore | 5 + CMakeLists.txt | 5 +- agent/CMakeLists.txt | 177 ++++++++++++++++++ agent/conf/CMakeLists.txt | 43 +++++ agent/conf/centagent.json.in | 15 ++ agent/doc/agent-doc.md | 23 +++ agent/doc/pictures/logo.jpg | Bin 0 -> 49244 bytes agent/inc/com/centreon/agent/config.hh | 67 +++++++ agent/precomp_inc/precomp.hh | 45 +++++ agent/proto/agent.proto | 91 +++++++++ agent/scripts/centagent.service.in | 33 ++++ agent/src/config.cc | 148 +++++++++++++++ agent/src/main.cc | 168 +++++++++++++++++ agent/test/CMakeLists.txt | 58 ++++++ agent/test/config_test.cc | 67 +++++++ agent/test/test_main.cc | 59 ++++++ clib/inc/com/centreon/process.hh | 4 +- clib/src/process.cc | 2 +- common/CMakeLists.txt | 6 +- common/inc/com/centreon/common/process.hh | 24 +-- common/process/CMakeLists.txt | 30 +++ common/{src => process}/process.cc | 4 +- common/tests/CMakeLists.txt | 3 + packaging/centreon-engine-daemon.yaml | 5 - .../centreon-monitoring-agent-debuginfo.yaml | 42 +++++ .../centreon-monitoring-agent-selinux.yaml | 40 ++++ packaging/centreon-monitoring-agent.yaml | 66 +++++++ .../centreon-engine-daemon-postinstall.sh | 17 ++ .../centreon-monitoring-agent-postinstall.sh | 31 +++ .../centreon-monitoring-agent-postremove.sh | 8 + .../centreon-monitoring-agent-preinstall.sh | 10 + .../centreon-monitoring-agent-preremove.sh | 3 + ...on-monitoring-agent-selinux-postinstall.sh | 25 +++ ...reon-monitoring-agent-selinux-preremove.sh | 5 + .../centreon-monitoring-agent.fc | 1 + .../centreon-monitoring-agent.if | 1 + .../centreon-monitoring-agent.te | 170 +++++++++++++++++ 40 files changed, 1482 insertions(+), 27 deletions(-) create mode 100644 agent/CMakeLists.txt create mode 100644 agent/conf/CMakeLists.txt create mode 100644 agent/conf/centagent.json.in create mode 100644 agent/doc/agent-doc.md create mode 100644 agent/doc/pictures/logo.jpg create mode 100644 agent/inc/com/centreon/agent/config.hh create mode 100644 agent/precomp_inc/precomp.hh create mode 100644 agent/proto/agent.proto create mode 100644 agent/scripts/centagent.service.in create mode 100644 agent/src/config.cc create mode 100644 agent/src/main.cc create mode 100644 agent/test/CMakeLists.txt create mode 100644 agent/test/config_test.cc create mode 100644 agent/test/test_main.cc create mode 100644 common/process/CMakeLists.txt rename common/{src => process}/process.cc (98%) create mode 100644 packaging/centreon-monitoring-agent-debuginfo.yaml create mode 100644 packaging/centreon-monitoring-agent-selinux.yaml create mode 100644 packaging/centreon-monitoring-agent.yaml create mode 100644 packaging/scripts/centreon-monitoring-agent-postinstall.sh create mode 100644 packaging/scripts/centreon-monitoring-agent-postremove.sh create mode 100644 packaging/scripts/centreon-monitoring-agent-preinstall.sh create mode 100644 packaging/scripts/centreon-monitoring-agent-preremove.sh create mode 100644 packaging/scripts/centreon-monitoring-agent-selinux-postinstall.sh create mode 100644 packaging/scripts/centreon-monitoring-agent-selinux-preremove.sh create mode 100644 selinux/centreon-monitoring-agent/centreon-monitoring-agent.fc create mode 100644 selinux/centreon-monitoring-agent/centreon-monitoring-agent.if create mode 100644 selinux/centreon-monitoring-agent/centreon-monitoring-agent.te diff --git a/.github/scripts/collect-unit-tests.sh b/.github/scripts/collect-unit-tests.sh index cd8e89bd0b4..077ff0291b9 100755 --- a/.github/scripts/collect-unit-tests.sh +++ b/.github/scripts/collect-unit-tests.sh @@ -25,4 +25,5 @@ tests/ut_engine --gtest_output=xml:ut_engine.xml tests/ut_clib --gtest_output=xml:ut_clib.xml tests/ut_connector --gtest_output=xml:ut_connector.xml tests/ut_common --gtest_output=xml:ut_common.xml +tests/ut_agent --gtest_output=xml:ut_agent.xml echo "---------------------------------------------------------- end of ut tests ------------------------------------------------" diff --git a/.github/workflows/centreon-collect.yml b/.github/workflows/centreon-collect.yml index 5525e3df391..b0dc3532ac1 100644 --- a/.github/workflows/centreon-collect.yml +++ b/.github/workflows/centreon-collect.yml @@ -8,6 +8,7 @@ on: workflow_dispatch: pull_request: paths: + - agent/** - bbdo/** - broker/** - ccc/** @@ -33,6 +34,7 @@ on: - master - "[2-9][0-9].[0-9][0-9].x" paths: + - agent/** - bbdo/** - broker/** - ccc/** diff --git a/.github/workflows/package-collect.yml b/.github/workflows/package-collect.yml index b3b0cc4ded6..0fd36641a3c 100644 --- a/.github/workflows/package-collect.yml +++ b/.github/workflows/package-collect.yml @@ -105,7 +105,7 @@ jobs: if: ${{ matrix.package_extension == 'rpm' }} run: | cd selinux - for MODULE in "centreon-engine" "centreon-broker"; do + for MODULE in "centreon-engine" "centreon-broker" "centreon-monitoring-agent"; do cd $MODULE sed -i "s/@VERSION@/${{ inputs.version }}/g" $MODULE.te make -f /usr/share/selinux/devel/Makefile @@ -187,7 +187,8 @@ jobs: "build/engine/modules/bench/centengine_bench_passive" "build/connectors/perl/centreon_connector_perl" "build/connectors/ssh/centreon_connector_ssh" - "build/ccc/ccc") + "build/ccc/ccc" + "build/agent/centagent") for file in ${exe[@]}; do echo "Making a debug file of $file" objcopy --only-keep-debug $file $file.debug diff --git a/.gitignore b/.gitignore index 8243275dd6e..77cd000405a 100644 --- a/.gitignore +++ b/.gitignore @@ -65,6 +65,10 @@ log.html output.xml report.html +# agent +agent/scripts/centagent.service +opentelemetry-proto + # bbdo bbdo/*_accessor.hh @@ -140,3 +144,4 @@ tests/bench.unqlite tests/resources/*_pb2.py tests/resources/*_pb2_grpc.py tests/resources/grpc_stream.proto +tests/resources/opentelemetry diff --git a/CMakeLists.txt b/CMakeLists.txt index 0291bc4f58f..f8f21ebd513 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -150,6 +150,7 @@ endif() set(USER_BROKER centreon-broker) set(USER_ENGINE centreon-engine) + find_package(fmt CONFIG REQUIRED) find_package(spdlog CONFIG REQUIRED) find_package(gRPC CONFIG REQUIRED) @@ -239,6 +240,7 @@ add_subdirectory(bbdo) add_subdirectory(engine) add_subdirectory(connectors) add_subdirectory(ccc) +add_subdirectory(agent) if (WITH_MALLOC_TRACE) add_subdirectory(malloc-trace) @@ -250,9 +252,10 @@ add_custom_target(test-engine COMMAND tests/ut_engine) add_custom_target(test-clib COMMAND tests/ut_clib) add_custom_target(test-connector COMMAND tests/ut_connector) add_custom_target(test-common COMMAND tests/ut_common) +add_custom_target(test-agent COMMAND tests/ut_agent) add_custom_target(test DEPENDS test-broker test-engine test-clib test-connector - test-common) + test-common test-agent) add_custom_target(test-coverage DEPENDS broker-test-coverage engine-test-coverage clib-test-coverage) diff --git a/agent/CMakeLists.txt b/agent/CMakeLists.txt new file mode 100644 index 00000000000..4d37d055ee2 --- /dev/null +++ b/agent/CMakeLists.txt @@ -0,0 +1,177 @@ +# +# Copyright 2024 Centreon +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may not +# use this file except in compliance with the License. You may obtain a copy of +# the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations under +# the License. +# +# For more information : contact@centreon.com +# + +# Global options. +project("Centreon agent" CXX) + +# Set directories. +set(INCLUDE_DIR "${PROJECT_SOURCE_DIR}/inc/com/centreon/agent") +set(SRC_DIR "${PROJECT_SOURCE_DIR}/src") +set(SCRIPT_DIR "${PROJECT_SOURCE_DIR}/scripts") + + +add_definitions("-D_GLIBCXX_USE_CXX11_ABI=1") +add_definitions(-DSPDLOG_ACTIVE_LEVEL=SPDLOG_LEVEL_TRACE) + +option(WITH_LIBCXX "compiles and links cbd with clang++/libc++") + +if(WITH_LIBCXX) + set(CMAKE_CXX_COMPILER "clang++") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -stdlib=libc++") + + # set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=thread -Werror -O1 + # -fno-omit-frame-pointer") +endif() + +#otel service +set(service_files + opentelemetry/proto/collector/metrics/v1/metrics_service +) + +foreach(name IN LISTS service_files) + set(proto_file "${name}.proto") + add_custom_command( + OUTPUT "${SRC_DIR}/${name}.grpc.pb.cc" + COMMENT "Generating grpc files from the otl service file ${proto_file}" + DEPENDS opentelemetry-proto-files + COMMAND + ${Protobuf_PROTOC_EXECUTABLE} ARGS + --plugin=protoc-gen-grpc=${GRPC_CPP_PLUGIN} + --proto_path=${CMAKE_SOURCE_DIR}/opentelemetry-proto + --grpc_out=${SRC_DIR} ${proto_file} + VERBATIM + WORKING_DIRECTORY ${CMAKE_BINARY_DIR}) + +endforeach() + +set(otl_protobuf_files + opentelemetry/proto/collector/metrics/v1/metrics_service + opentelemetry/proto/metrics/v1/metrics + opentelemetry/proto/common/v1/common + opentelemetry/proto/resource/v1/resource +) +foreach(name IN LISTS otl_protobuf_files) + set(proto_file "${name}.proto") + add_custom_command( + OUTPUT "${SRC_DIR}/${name}.pb.cc" + COMMENT "Generating interface files from the otl file ${proto_file}" + DEPENDS opentelemetry-proto-files + COMMAND + ${Protobuf_PROTOC_EXECUTABLE} ARGS --cpp_out=${SRC_DIR} + --proto_path=${CMAKE_SOURCE_DIR}/opentelemetry-proto ${proto_file} + VERBATIM) +endforeach() + + +#centagent server and client +add_custom_command( + DEPENDS ${PROJECT_SOURCE_DIR}/proto/agent.proto + COMMENT "Generating interface files from the conf centagent proto file (grpc)" + OUTPUT ${SRC_DIR}/agent.grpc.pb.cc + COMMAND + ${Protobuf_PROTOC_EXECUTABLE} ARGS + --plugin=protoc-gen-grpc=${GRPC_CPP_PLUGIN} + --proto_path=${PROJECT_SOURCE_DIR}/proto --proto_path=${CMAKE_SOURCE_DIR}/opentelemetry-proto + --grpc_out=${SRC_DIR} ${PROJECT_SOURCE_DIR}/proto/agent.proto + DEPENDS ${PROJECT_SOURCE_DIR}/proto/agent.proto + COMMENT "Generating interface files from the conf centagent proto file (protobuf)" + OUTPUT ${SRC_DIR}/agent.pb.cc + COMMAND + ${Protobuf_PROTOC_EXECUTABLE} ARGS --cpp_out=${SRC_DIR} + --proto_path=${PROJECT_SOURCE_DIR}/proto --proto_path=${CMAKE_SOURCE_DIR}/opentelemetry-proto + ${PROJECT_SOURCE_DIR}/proto/agent.proto + WORKING_DIRECTORY ${CMAKE_BINARY_DIR}) + + +add_library(centagent_lib STATIC + ${SRC_DIR}/opentelemetry/proto/collector/metrics/v1/metrics_service.grpc.pb.cc + ${SRC_DIR}/opentelemetry/proto/collector/metrics/v1/metrics_service.pb.cc + ${SRC_DIR}/opentelemetry/proto/metrics/v1/metrics.pb.cc + ${SRC_DIR}/opentelemetry/proto/common/v1/common.pb.cc + ${SRC_DIR}/opentelemetry/proto/resource/v1/resource.pb.cc + ${SRC_DIR}/config.cc +) + +include_directories( + ${INCLUDE_DIR} + ${SRC_DIR} + ${CMAKE_SOURCE_DIR}/common/inc + ${CMAKE_SOURCE_DIR}/common/grpc/inc +) + +target_precompile_headers(centagent_lib PRIVATE precomp_inc/precomp.hh) + +SET(CENTREON_AGENT centagent) + +add_executable(${CENTREON_AGENT} ${SRC_DIR}/main.cc) + +target_link_libraries( + ${CENTREON_AGENT} PRIVATE + -L${PROTOBUF_LIB_DIR} + gRPC::gpr gRPC::grpc gRPC::grpc++ gRPC::grpc++_alts + centagent_lib + centreon_common + centreon_grpc + -L${Boost_LIBRARY_DIR_RELEASE} + boost_program_options + fmt::fmt) + +target_precompile_headers(${CENTREON_AGENT} REUSE_FROM centagent_lib) + +target_include_directories(${CENTREON_AGENT} PRIVATE + ${INCLUDE_DIR} + ${SRC_DIR} + ${CMAKE_SOURCE_DIR}/common/inc +) + +set(AGENT_VAR_LOG_DIR + "${CMAKE_INSTALL_FULL_LOCALSTATEDIR}/log/centreon-monitoring-agent") + + +install(TARGETS ${CENTREON_AGENT} RUNTIME DESTINATION "${CMAKE_INSTALL_FULL_BINDIR}") + +if(WITH_TESTING) + add_subdirectory(test) +endif() + + +set(PREFIX_AGENT_CONF "${CMAKE_INSTALL_FULL_SYSCONFDIR}/centreon-monitoring-agent") +set(USER_AGENT centreon-monitoring-agent) + + +if(WITH_CONF) + add_subdirectory(conf) +endif() + +# Generate Systemd script. +message(STATUS "Generating systemd startup script.") +configure_file("${SCRIPT_DIR}/centagent.service.in" + "${SCRIPT_DIR}/centagent.service") + +# Startup dir. +if(WITH_STARTUP_DIR) + set(STARTUP_DIR "${WITH_STARTUP_DIR}") +else() + set(STARTUP_DIR "/etc/systemd/system") +endif() + +# Script install rule. +install( + PROGRAMS "${SCRIPT_DIR}/centagent.service" + DESTINATION "${STARTUP_DIR}" + COMPONENT "runtime") diff --git a/agent/conf/CMakeLists.txt b/agent/conf/CMakeLists.txt new file mode 100644 index 00000000000..1d8104e4429 --- /dev/null +++ b/agent/conf/CMakeLists.txt @@ -0,0 +1,43 @@ +# +# Copyright 2024 Centreon +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may not +# use this file except in compliance with the License. You may obtain a copy of +# the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations under +# the License. +# +# For more information : contact@centreon.com +# + +# Set directories. +set(SRC_DIR "${PROJECT_SOURCE_DIR}/conf") + +# Configure files. +configure_file("${SRC_DIR}/centagent.json.in" + "${SRC_DIR}/centagent.json") + +# Install files if necessary. +option(WITH_SAMPLE_CONFIG "Install sample configuration files." ON) +if (WITH_SAMPLE_CONFIG) + install(DIRECTORY "${SRC_DIR}/" + DESTINATION "${PREFIX_AGENT_CONF}" + COMPONENT "runtime" + FILES_MATCHING PATTERN "*.cfg") + + install(CODE " + function(my_chown user group file) + if (APPLE OR (UNIX AND NOT CYGWIN)) + execute_process(COMMAND \"chown\" \"\${user}:\${group}\" \"\${file}\") + endif () + endfunction() + + my_chown(\"${USER_AGENT}\" \"${USER_AGENT}\" \"${PREFIX_AGENT_CONF}/centagent.json\") + ") +endif () diff --git a/agent/conf/centagent.json.in b/agent/conf/centagent.json.in new file mode 100644 index 00000000000..cf3bc510cb2 --- /dev/null +++ b/agent/conf/centagent.json.in @@ -0,0 +1,15 @@ +{ + "log_file":"@AGENT_VAR_LOG_DIR@/@CENTREON_AGENT@.log", + "log_level":"info", + "log_type":"file", + "log_max_file_size":10, + "log_max_files":3, + "endpoint":":4317", + "encryption":false, + "certificate":"", + "private_key":"", + "ca_certificate":"", + "ca_name":"", + "host":"my-centreon-host", + "reversed_grpc_streaming":false +} diff --git a/agent/doc/agent-doc.md b/agent/doc/agent-doc.md new file mode 100644 index 00000000000..ab326f5fbdc --- /dev/null +++ b/agent/doc/agent-doc.md @@ -0,0 +1,23 @@ +# Centreon Monitoring Agent documentation {#mainpage} + +## Introduction + +The purpose of this program is to run checks on the Windows and Linux operating systems. It is entirely asynchronous, with the exception of the gRPC layers. It is also single-threaded and therefore needs no mutexes, except in the gRPC part. +This is why, when a request is received, it is posted to ASIO for processing in the main thread. + +## Configuration +The configuration is given by Engine by an AgentConfiguration message sent over gRPC. +The configuration object is embedded in MessageToAgent::config + +## Scheduler +We try to spread checks over the check_period. +Example: We have 10 checks to execute during one second. Check1 will start at now, second at now + 0.1s.. + +When the Agent receives the configuration, all checks are recreated. +For example, we have 100 checks to execute in 10 minutes, at it is 12:00:00. +The first service check will start right now, the second one at 12:00:06, third at 12:00:12... and the last one at 12:09:54 +We don't care about the duration of tests, we work with time points. +In the previous example, the second check for the first service will be scheduled at 12:00:10 even if all other checks has not been yet started. + +In case of check duration is too long, we might exceed maximum of concurrent checks. In that case checks will be executed as soon one will be ended. +This means that the second check may start later than the scheduled time point (12:00:10) if the other first checks are too long. The order of checks is always respected even in case of a bottleneck. diff --git a/agent/doc/pictures/logo.jpg b/agent/doc/pictures/logo.jpg new file mode 100644 index 0000000000000000000000000000000000000000..0bcd7358aa9c7ffa817d9a30008efcd4d1fe676d GIT binary patch literal 49244 zcmeFZcUW7;wl^%7#Btn0FkqXOfDOSIu)tJNj$?{#ieh7W3y3a+=uH9=lb8+xOh+g- z-GF3)L>Cx?kf|~V5J(_Qw*Ub`AUeEq&PndQ-*fNxKJPzypYQq3puP9Z-fPyH`OTU& zvuCg2ck1DI zlmqaS8VW$50#Ne_P+3b^RST%1a9dUD_HDpv0N}SXpU!~W%F4ITrl0zQ^HCB2aPs$m zN=fI7I`yC8pCo>|_o>XMHavrZ{Irymd;=AoKb1le0*5JuIr}LA6>lp6wDrRLoFP!R zpl@8chAk!>wZLln|XxU6G#LUqUkE7r~8d|m{u6f z59Su+{7o3l$2U+bOh@Vu=34ytr`t+W-~2%m1l5uHXWgw$fB5DeJizT6RYf%g2v9}i z8+A=ZpsJ>Z@||0suuxOFt*HdOqi`Fjbz4*GHt?H&1u4F?09SXd$NGl6=}7TQ`p+uB{QhG5-(vMAp)2GsI=|ompFf1VLX_Nm++c3LL4kZ+fuE}XCsR|? zzsUbvwlLUV)PX^d-TtF)|1EXklW;#brN?f8@ZbQ58=qYIlPEu}djW3FLGXYlaJbK( zi2uK6+keXArtci&rX%(LRKI`f-aqL~;jUip;r~6|Uuyacb(ypW5NiysrO|_ul`Q_mf7${P>df-2%Kq+*}O< z;IME0Xbml||G6xh|0BPD<#qj^%X0UB%&WvNjM69l{7?G&=PiCG_!RxC_wf^d^z|*f! zoe%(=6gY88;KXq!K$362PMkh@>JJ0;$w&bJU!M8m?70)4pFI89DL#SYSD&7rIC=Wy z>CewzIRC{N0N}*QQ>Q=s{LB{uXTSay_@&_GyN{fOr2KzQTNjpA)(A^~fvXp}rmC*_ zy;X1sp3pvY|o}=r@0f z{deTw2>cs?ek-*-^R5wGv~)oA zm#Qv7qrUdI3$~fl9+mTjq*y|lVf^aiO<7lStfG%KkfG?4NlFwmp^xG%aRQ_6?onYbsV(qG;&z*@QjP&PQkqg8f7~rixm}+Tik*{jEAycBL^dE z2i?5@;bLixY9%v;aGfQBy*?$J+q;vm=3q7c7y1_}L+Ytx%>m zROM+s+2*jB<_?;5s1AvIv#>eLl@Yg$fJ#ocOvgi1NV0ecIGQ4V&E6{EL5j z@5MBdeOleF_PgGzl@UiT9=oj)v()dw<&;&ZZJ}?-Ax;xzxWpZFiR?`l+j|}3G|G{~ zn(?5{L!*%#0zrf^`;gL@ypvjtR&dU@`gL8wx78&izTZd7o3hepr&D+Ms&hYUH7K4nYdB*??yRKW=v%w$(;3G+N|Z8xGicyA+01(aZmCt(%`AA#^?JV%avs+rng=yraF_#T0IK_vx!7_3QmyO3j}T~MCgaz z9JwUC`j2?FJ@zXW&E}Bn&-fgAZ5~|x*jR|o<2kKaadV0cjsadqnzMMYzzXG=cg5nB z;HGNr18RC+&K^_`q)5vr0C(wHcGFNR_S((S`WZ&?c;MB#^`ntE1HhRb@~{9FM7_k&0H|+Ye+pGAIGFCgyh@N7?&xjckzf)F2@qG zup(HG8L~y!de*NQK$h)!X)_{214|!2WFT>+lbN>36;0Fd>6}8iyk1Jt zFs1goY4l+eZP|g>R=bRF*Ai>3eC-@!V)Ah$R`zMnJ-;S3A=fPJ4<250AbRL_~hkOB9jvB3h6N88Sl%u5XX-2o$y-{+{L6-c3#G} zF|65#Wu-HjZci^vg{GWm4r)gyB{indzD*lDxK*+9D&A{XKOmwp$%$lYzIf@uk=&~~ znCy-9Cci$>KEq0@$=>pu^+f7va0Q9YxV|I>>5(n6(Zmjc;=Mi8vY$7=G@{NjrOhiC zGU3=|^NUAimv_lk1svUXg-IqG9(sXJz;3Rl-t$n{==C(WM9F-LWBvt)W!XL}YP*rV z+|WVPVfqzO#-L8#vu6KQ|Aj&iJVkPrj*+*{EnKjt6 zltpQhRka`DTDFzl@H16A2L+FS32l2&iTQ67k{6I3!Hq4Hq*Z_>GZN$Ct}W~K{jAdp z8{H-XX`7;x9J_?svj^a5&iqctrG4EOS^HOx0oQ`jyJBtoV?xbMhpo&h|MGnbp*979 zrT;ECV&1gBe`I#}hOJe{YVgdJaog-Ka~@Ilv8)WZw(4?pZE6M^1YLOHqMELIv=UHh zUzm`PP;M{Q++Q%*qqWD;wO9~`D{`)}>tMo_y4ly+pia}*%na{+s8?QJP)<&W3nl-v z=AA&h3q=EUd50hqC2s72X*k&+t5EN^8S)0ES#;KQ$aP#;6!x^~rgUp^A(?i+`d#vB z+upq0*Z0fgYHLT#1DlmM_u260%3gSTb}E>zbegPMU8Zei+*x@aedJjCnU15eK3rwT z60Nfa(x1mBL>u+(tq2MY>qCM29^Oo81~Vmt+evBb&&FI_mWeUrLrq%OID+Nw?BDwVxoM134KNY@xa$d)>!?fnp9z!3LiX-4Nr|H2iYk(rQ> z4-IN!ZWlN+dF_?Si)9}gYv|HmM7a+wceEk*uyIK?h+HHqIs=~HGsw>C+vho`N5i9? z-1Ik(0dK}&2U^DfJxaRyQn;kqKmIRty8sWNr;zF6DXLGL*?5 z-cynLQd$*+yndxiRQFLR;m(lPoss;x-t<9}psFxB4^M&$uyeW3&NMZ15Ks1e6Nk{5 zwhN|qH+mae?9$%NTLJq9w+^ZvERFJ<%3ObRvaswh9s(Jc9~MX4Ut87yd*DE3Tiu<3 zkiz_90IwlH--In5>FaHFh{y>^m_ymHPYs=e+jVGO3Qr-leboy-%k%P^i(5}AtXB=4 zidt1VpYc?u$ZK5P_PEpao+N!JqPg}; zC-hM@^pUEx6Lv<-%Bq~kF?DzR7CYR>P_(BJHXK7a1T3)({!)GeiicgWr$M(0j4jX( zox!1_%fW$a-5CmO{%@98jW8{Z(vi}#@*H3PQhWjFX3(;Kw`JcRt~>P=0B}>}+A+Yx z=NOQ%5?x?%yA3Wm6BTnX9eap=+>1(zPS&Cvq`(i^TJ_gb#@_(Mww(z7nEj*s`Y}To zQ8E3gNVsbfB8R6bK_>LjRQsJ&>}gWl(6q=$=CsBwW83U%mRAW22n2#mOw2ey;HZpj z6*x^?HjH(W<2hO^YP9tm_Dm*#fzbRv-}`}jf=wsH3BKqG0+ zggyM1dH!my*_QH$UQyH6OMZ@W+2A}JP^a&C6}{Gu+Lkgx#1dt&;A+xU{5a%>EGwRy zsJ|7z4eoC$&K@fN+xy>%$n1@?>uL8J>+{3*%LcUjHmq*A=O?^zxt7*`+DXx;E>uog z)ANJh9Z6}2wBE5m$+={)QCw1b_*_EE-SkHzTCGAbZ2xFL&)NC zj+_1Lm*OvZWn|5La}8zvb>^w3lPg+UPDDXqTc{#}ZPT0GqaIhPag>7dBCsK!Uw2_I z(l1F0hObZkF2--9lP~bRy$k`L56~YmK-W zF`K&Fi zQz4;TLUeg0BduUN(cpk}*!$ilY9@!(N`+EtwAd1AIrMLn5SDC@=OD3p2k;$kND~l}vUMl#p@~_gQ+XUSFH%ht zo$1BWRJQZ6mTNVsFM(9)M#L=ZJ=dzAnjdRa`Bq5G?E%K9$g81Iq96W1Y8m@nRzp@%%DS&(`{fxiHI5)mL3+U<&)fWg6{C4e1HVbAQFkHh(b&#RrRjs7@1B=A-eO`W$md>tp zYIri2;mI(ERTu6*9!!xIl1hx6%8brv3I%r`EEWWUI!(Y2QYGc4stotHj)0?AFS zWtOv#7#e?M(KOgUTEj9{9H)MmKqR*wat39!-VQhJa z3%k{Pr8?F0tIxtW*hTou?&QqGNysKo^l0Fs&CCHPt#Lnh>v^4`P+!YE;}|1hmVHJC z$6NYQUK$8))BOr_@gS%mN6D<#7#6uvC`vW0==aPaXN@GRwK=YsaV1!5`bh6yP1e`! zzgaQQtq_SvFLb{K|58P((ya^2C_>4NqlUPFh*6i!?2i*(N%*csULp|t4pynOp>sQ8 zBE*W2^b6Zk%5bOB$en6uL!CI4tr2_MTUw$}$1-1xouT>?@jO+$Xn@9htd7>CH~0NG zFo8hMwRVJkMwmcoLw94GjKLSDt+4_XqmH$BTPmRlTwJ~9KH`cEky0?R=*@3Vct5x# zQl4VA1WykXL-p8n*M!?YA0o$hlCBSaAehMZBcE?gLd9>T`05Fs5{n-fqJpJ#Nfqw3 z*K72C46`~r=m(R~k%$!uNE;nxF^P4{(1AgnWw6tQqAE*y(R*(Ps0gzK=4d$9p&vPk zt*f*t&o>kkP)pWLJQLxb=OCk*Z>X&?6S>{(S&$1uW)T-+kI+#^g~tFm>$(SKpNt4& zcqPw3un*!n@yrOYSuGnf$)mf3gHr_d&o>MowMku%8?7P4D#3Fnk=4)KoQ^zd zRG9;ZJ$pP0uKG~wU{sh6;jkpc?d`&W{Eh1TL_d_S2KvpSSDiytqEN&@Rs_SmgltnF zsFEQBIa5VW^xT(Yo2d@QWQ7-535^;K4|#8xF`J~lX`e&EU>ngRV}-hcd_xc=+N&+# zQ1=*+!PvS-Y0WpX=D&xa;WaME?PEXzT!req2V2S6L8x)}BEn*O=RPUi|JhWGpJ85y zx^dKIErK4>Gh#SBMx0Z&%7vdGSws61-ROB;H3;t8-})6BtLxlfS@(9I#~pOHV4f8O z6xS5ZSwkrV-DKS)dorUZg5&%6~bMZB7-|pi9YkAZ)2bY&v7=2HPh)-;wIoZS6PPo|5A?B$p_ruWwZQ zad(@Wi<I(7zy&FJ!g)tBnY zwK7%oWb!-d?(R64>t_6B_I%;nFn1jxpjD3Masq^aM`|e%{LQ@*mbQ4<9#ZMrW{JE& zwuLu6r!*5|GWLSiJJJ3Qx%N)(1L>);8DESo4`W4gpK~-``G=&6#8#il z(%O3IZ6tUt4mGi;GtRyD``~)NqJl)Cm~+Q7X>T%myIN%w=C!O=SUW8)A;E3a4pjFn z=+BtE5|`sE^t4u`1mDL{YrB__24cC(w!NZ0R&UoiXsEmb8t%Xo zpYtjlg7388`u0$S!8#oo?DfrFaj6^?I#QXuFxw4hX+7qO(BTtp;I=v5;SbzZP_1uh__J@9HAje#0p_wKI2V#-dl&5iFoMPsAR|7!MWy4i%H8~?)IwN z9GcBpW57y1$jx9RIb~9Ql_}+#U*eTVmVjP?shf5TzgZ5u1}jM>4W)Kp2C7GTJf} zjbWo6Z{@9bFPBKkC8XIx5{7WrON-v3YkW_o6*VS=v9>%rySck>)@qL51@VZlkyAI$ zQNX$5S8Y2+qJ36~>2d}0hf_7GQ&UpA76|^ZsWOx}7!szjjq! zc^TpPuC(=opp>QusI^x^L$bpr48`xZbXLMbGHNg*5QiQ0TYCgf_C@uyKUkj+ z2})9&LQ_qTer@+8eitm)9X#D!ydHghfio(Q__>WLG7EG;OA}P|d*A$vr&ZPL<;fdQ zw)W5U{=y5Vh=pW!zil*ksBDLyZ;P2DCxmh_CYdD)M}^EChZd#Z8Y#(-8#O#`K~*)B zb{lmJDpEq%8H)F-6(skv@BJPI-+Gby4*Xl&Tbdj#L;RMBvFNj(GOAMZT9RGf^jFxE zYw z9*>^d*-g2y?$ye%;V7Mt-Hb(r>F)9wRHnaI zM{GC&-yrQIlnN`m7pZR$d1Nw~9mCNE^>2pDNRNxJO-{nqJtw-x3$qMSRgv@o>&1$I z7J^T^6r#qPi^IlG(#HD@%qEj=R1Pj}Ufp1+?wRB%I9|&mR$>GMw zJ&&x6U^D|Kb2#zw@eywFKLJv&h`bnFyFY$ZqDHEJ?rU_GWPR?!;d7snS=T_vnywn_ zt*X;?SE{lVG#J89HwC#Q2H7&v1T{bZ(^$%jGW-{c`DRrOO3M7a_Gs zX=-ak79zX411f}H(`Xi2n{H?n!(e?=bUUNMYVwzD(`(<21X-7r6_N`X!uW8J=i%~7 zU$yE=ll%vCKJ$ohL1*|dcT<;Uw<(LehEygBuvxZAd>^2eAIFOv&;E+s89t>0i?!+W zqc`66i$g7ENXQ#S ze>Yd74tvO|c4&*5OU;^Zltred+ej=D*Q_)x>`T2$lyC8ao-EMz{*pwL6{1Uu@-$j^g`E-Q5`!s~3Am zZ6#pr-oet3pI|~nIx>kFTiaVsLxF8cU~BXhUgypld#Z1_l>-9Tk8_(>+g=x!_lPj# zWnJB%mzi7af7V*6WDhbLxAGntrGb0JD6dwR@)3)bI3jIObR4n0rEfM#Jk+H)9#V8?z35N@AgokI_X$i_ z6gIExIL1Zo`51+`xG0E2irMwgkw>~~m=L$XV)U2H#|s}>tM=_OcCkB5*94MQ9ggks z4NSE#j@K*_`%X%x`7Y;GrSDYyYUoVUmugZGCixe}X+>)i3+1HF-MoN+sZ)6U(X3K> zzkbkis`xSBMRDiaRTWDZYz7*8!=r^F_VbvP*n;iMjCRMeCL)I6Rb`vD;~3EwHcN`i zfdWUB7phA=yfE@ZE`w;M$VYCO;^`M=^^%;B#*3DfMVb2{QNM`F%)1Z6R_YvT+-9;O zyyv-~`6sp`d6+}Y=dv#vkl1nT^^FvXjn9hNZhx>{!KvpYFE)20BpXJN(;1QEK&Z5LI4;Krl`NP+?eS`Som!tcfVIYi3B%`4t7`7u2r z>#JPJ;(L@Wm<<6oYm<|cS(a~F(e71hFG2>+3ffd1P=T}sW@RHQ`bCP#0;)(fI%Jf0 zK`@a8{;ZD)SN(oKP`03a#3w#+S}la=m+#~L@r!A5KPX3=c( zoUo|+ydB~C=ODcyhJ=G7*6P`w$zGowsR-PG^C$^$Z4FCVS$dgK#{aOZEXyeMC`l^`Yz2OTKtIniztY`~(4 zU2n$Zt>WWeEousKN?-2^QL?$vl=~q+K4_i-BRBxCV%Pl2c)dH zzt`rN+~pE^2^CNZ%~PS@tZ-K}wye6E+6>dqh6Q^}MRs>3LN-X*Fq5FD@k=mASqzVeL4%Z$h73 zw)F@{UqxTdJ&Jm*!Sv_~{U?T+hLxGuhAjeKNk6KX?3s6bm#h!A3U!*7nDTJKlF5w4 zw$%Kbwa}N)7DiOz$B8!k^)6NE1BDAQV^VHmzOJ9$rT9QKgXC4_&ACOw!c)OR2Wc z3pB%$9M$TY)ORn_Jw8KZDBW zs#a~2+wT@89iOgiM0_`@nt*wtzbd8Rm0&3Y3y+J7W4crMgSpngYSQj&*6W2~ZxyT0 z(O^3#8DqNKLr7I21Xy zx_Vt&A;>2-KXyA4>`W~|q9sI-kwU5Lka99tO`VjANMCiISA0;K(h!z?g)}vK6r!z0 zhb9gvgmHT%fPzCALs3q#>5k6}bLg#}y(EOzN|}?EnFZYsy3;C0RN-8@Hc$P?-tf5i zbZ|o{PkPjQmUx*EREK_h``)-Ng~r%Tdd{u-7xa=8^JRC)+jB4JEz8{@np3~|uc4E6 zqE+vXi3P{mE+L|?e?O*dy;r+C_!wy>BSIy5q0(x`2;Ymye+Vw8Npcr&Q!We|ogZSr zJie;hUW~$bjMf6{f0;uq+i(&{Exat=o&fJcEMCH=o35_RBEoM5s3DzVTnM3L%*+Tw zQEMtJr%wEWheVNrI(-*gR?@t47%XFRn6Ywj48YFaJF^p}lOOOm>B)Z;b7EZ$R^&ic zJ?NsX5nGxG_% zv$Lq{Llt;9Dg*P%Wq8Kz3AETH`Y}&+sJ1|oq3i1ykq*AkV9_J=4S(m36dZrKaXY8l zMH(&{WMmVkPwRwqPB|}GNvF-ETz$8o8g;tl`esetAQciQR(mT@r8iJjB(vuIa2iL| z8{$~b8jMOy^XT8T@LH5GpIgzEdQMyB(9{L-a3`$~Q+s$0lY0my-!FX567=Ha55*2q z;zKH4jRe5IU8-GA8Nl-hDok|}I*G0z`J5uIlzPvmDgvcYS9d?Bw;~=tODgL;5rt^U z)BhJbC-&~0uaik2h7}iv&$-_25EQ>&Yb>9ZMiTQeuzI)HSU#+8Vev$NOAsiaqJlR{ zqWq%E8QKkikPH*zQZBt%g=V1CUQz3oT`ZmQOAtR$ehe@0Bw>wd}qK{NFQaD#*j5$Yk9C!AH2dV!8%&u|20@ zv91nuDZb*yGH>oaeeqpV^|_I2U5#s@?!Xj8nn*1;My*m;L9H+&TNh#AWnEYc1>fH` z8kd*@i_Y4sWNWBjUbv`UU3T%qf#~NBmSsBIt26D-GLYG*m+m3e?k-X?RFEZ31t@qC z`xRI~hgx+Z#T0C7M^8PmysL_~ACZ*0m%&i9M9fy#`Bn-}WY}9a4pbOmf+H?uZ<~*C z$D<1mh$_*?YcE7OJ1hJ!Ul)PulU8y2DN<=)|1N$=>J0&}^XOjv< zY70g3U?u!Ftbk=DvrQ`-Y+m2!xHc>XEa(#vhCXul#u?DS`*U4ttOr>L^^%2ZzBbEZo_;m zt6)Pe<1)Z5>O7u5l={#m;iQBv*v!f#>YQ)qhDpq>;Nb=r0&A&?ZH%9nN|Mm4W_U_S#uuUE=d4}_P@wLu{ zjaygbTrtfu(S|e?!OnRIBc{2=ygooRO>`#>eB;ZlVjfp{Ij3^xF#Ed@P*2`~|03$l z7w^rkjO?Kdy$zwJaw@4}eOuLVosXF9xCH)yfq6e1ZF;1F`EZn~P2CYlIVqkCe9Cn@8S9NJ;p(Me6(e&iny&rF9!+fLoxJg4UxO?KiL?R>H5#NL!#zN+^@ z^4IA@Xylpqw+_>e0pii)pLj;szmKkRJqG*~B@(+;y(#&RTAtBC@G-zO`lpoOqp7<` zxQwF{JC2g0_3tD9KOqfU=1Fa%E%Nq{0Reh%z*=M{r{7t}fVqFx@tM|kH3*Tbw;n+% zYFeJH6xMy*l!fgUmfv<<%4jq09d?opIvl#|4R5Ot6bT`X!&Nr0-*PSjJ8M|5m*jj? zc<}+y0%jxtDq$W6hLpi!~y_O=tA9G@>HFPLln^GR7c~ zY9_Jt)8DAje~IF2cJynFLflP}Vf5LVruYx5M$>)7xC)hE+FV6ScmKIEcS+|Wm-CqV z9BbQhmW`FBk)-_C2(&mwoxA|n%8vdfFskUc-Hx9E9kVj>!VJTRoX%|z#d9Rw5)eKu zn0;Z*IyXKJPbzCqLD;Qu4d_@8ZN@vTiL_EI(91*O)+jdWwl|L6h|gVURk7D9u&%Mi z0oAJbC+72SG-F~LFFn;f1?obgF$|ho)#;_~<$;8~@Gs$rp)BaR;A=@e)3>_Fy2PAJ z>rDgiU02s6`0I(ve&jinhD2gcc%Xwr^!d?F6I(q!ao%oNpm}(mcEdslQHeiEs^h5U zM+G%rl zTK@^&xvg~)W0o2*^C7?Px{pPzO#!b+xtU6l8LwFMv)&m*l+A+V10|C8M+Ar8I;Lsg zoUp^K29h53Z?OD-9MLygVi7a~nNdDL-CjE;`*xs@;bh$UrTeY@Tbeb7+V)0|%HQ`< z?&m}CS}3*eb{M)Q{u1MKWQgevA;ca(C`~SZtl;fQJk-1E5K50Q(T@3J!vAOK{;unZ zw=boXY9f?Ij$W+$4{7Zv=vAhqY0xSMH1ka-zx9=M?JB0-N#^~k#q|ijRa@j_Jqnh` zekh9o)|YD;8o4Dwb9Q`4j-590HAlnYu{EoDjtXy;cFbZP5mfW!>4PyA39?bm@Ck}z zZLBKPiwx={aTqt0e%TLPQF;yvoHr>rmE#}v8EMnsrvMZ`OE&fn(kxYDsnl0fT~S5m zrG#bsk+>X!GF902UR(KUo~B(1@rWY1QFwOKBVw!;v-0G~b&ok6`z-o-Ul%dmQuWrG z@{g@PN`^MCSaw3?E@_WMMjY?*oo^8LKjiEzDl9`(rJL<{ls1B|+1H8=+~V8cO85vK zo_bxMA-*O63R9xfT(wza6qUvKl)!0pj9Yya-PBQMt(f+qx*1nKG*6crSznvQTd7^e zo2zNr!9Jcq;(q*BYn^eUsudI_*Dp0=z6NLJ4y&2S492I~SKr^T7R&T0k*&-l4pz8S zMINorg^El^_^Q4QL!TKnZ!4amBk4W_x-2rB!w{Oqg8T6+IrFRP)$^@7?V5?trW!jn zE@Dlq+ChD=Y}344+zt#B$`V~c>xr*6L_K)F+4?Ht0<+{dUFpgnpd8H%IF->d8=yQ*40pdiZ%+Z{IFL*_i658OkFgFzNN2nBj>(kBE31?v>duDO@EL&_p>QS71~7f6r8`$YS{ zOIiP`oHJj>GggiPR!p=r*{oJi@U7POQ+uhb+Qf+B+5CyXo+}}Ys_h4Gr!lYMA69Im zU@q3v{mbKLy4H%u;O^IPI+BjVPWbVJ`?MOziJ$40ltcW+J8EjG82K#--D}hdQ(iD?;q(ZHgfk?H+OK`A26u@y&*{_tLit_7DU6CNRn8 z?cuD%JC?Yx6!yzp`3R$!$mWnU13EF>JAP3=7W+$_>y)BRPncf>(M+qzPS?N@YNS^r zLCIgdN_hksmredxr&2rHyU(q^`xmUI!@7>nDu> zcOuu8Rali?%RWuo+pV^=uAuQ&1D8CgG3Z&Yj_iL`fxj)KiY+8yWg;HV7fSbN zFTMqGQqFWjH!6IyN$FCEykuSL-7uAz++1?D7-?C>6UE}MpkAUW-97kukTDxu<$Al%l|YH8JWSrKPmo9{w!db}^jE_)hM_O>Dg zW+vVrA?B~ue|dnhl`v3bESy_ss#6V|g}SyQ47Jl}5+;R$5k`BefqFk4AY>wDy1O(_ zCAj5GPnbzZt?tvCbV5T27zHp@z&(1@-ZJD*gRVMZmW&PUlbj|Fi zT)5)0Y%FKMaoF6vtXH%zlm%O;kITu2blVh!`}5zQW{8}r2>ScnH3O65cX@csQKwN&w@ zrmn>jZ~OQv_aNe;LnkZ(({8${q9Hc<9UOukjrNdsd*+VKvb;a~;Bu8^?|GcEbz%1v za&he0nFH`o9C0O)5A>B5_4to45fb{sLav-A&sN(75=QWdVAiVQP2F9b`TqP$e!AWt zChlc7rvCclti52uY=LdET9J5wbMJ#?LM8lcRi|w>hDMGU-6X(m=~9nqi?N?C4z;@T zcF9{C4D?CYYAxHwEQ1>>6p3CJ$3bUxgQrSIrzq0WWzRS2u8!DUc>c7fD@#Xf#khV| zfNq$2>9g5ff4{;`COhKcQG)0RcOIv?ls2S6nc7(%XB>@(W9lW-|~w zcyrrGtws}6(wn?jWOg`4GTV@k1OdfL+*6Gr4VtM$KWZ0J#$CH|jkhmd73?rk+j}hq zRKC^d;*lN6Ey0=A6WvEO;jUK{V4ys>z(avw3=q2g}q)6uMlm+)JF?iQHihXU* zir%@Zm7$r^{3``gC0)7jTFplAst)Kp@)GpQ9Mnk+3>Twyw=@n+oU!V)?|#eSC|-Dl zwKahuLz8D3{g`U4x9|r`Ze&#=Vl*CA>Js9Vp_!i?5=m+Zy*76k+@RJR8$@2J+X^M? zp%T?}@x2L$I_}z;c-tt8R(rm)qQluR%DR%d^+X7&-$p$8XHCpC&OP_i_UstZu6t{B{MQITAiI+ z@$o4cg5sg6N`ae~UIWB#@(i4CLPivv3f^S@N)_iUC*@;mN2+6wQEy9z5q#l`rFRVy z=mz?#I%NJ<$zlgrPF*K8fqs{~W3@ZB)s~-C0FTGoK4QKe9f^Xi6b*9mg|uL6g*Od4 zJE2PSsmz(Co+{2kY88`gX>*V5d^wtqdb-O@TJUulvM5kieuU#K3TMGaq_vcO%m% zW$|6LgUBkgkKFgZpM4Y>cT9|(C6RZwMP`v^5T9I}81Eze~z6p8QPEMWd08`j^vu z7jy{9PRPOhTVuCoodM7|#;ig@^Omdf9c49%%&+@F0p`_#_RS%i$}=rLza_LV#r>L2whL4LyaE;o*@0=VbMTb{#gY=49U+bhMvn?C3Po6w^T=bxF#8Xu( z(l_=|q)hFDh&fWWcxf(hu9#F2;aDqNUCEzi=y!H@tryLR>D?m*X$^>WZiY3)UZTym zitVUCF!nY$*D9KfcEg&W-OyGpKSK`QjQRy(Cw|9yKJ3PBir0q(^}rV3^%{q>=#?WxMez&c*l5YE-uw`=6n9GT3|K2Tg?+ zm`s>wE^~JWhJ>h=2CyOw!->+g*Zo_(H8y`Gtu4BLPh{2Hhi_`Txb_~kZd2(w_!r@f*8vx)EZRr?bEq*SDdDDAj((y8^V1l#zYS@BnWP{y=Rid(+ zUDl@FQ6}$~qtdP=%+wkc)s+saF&m(})J2t*)He7fAx5t~wtTh`qUNyf*Jl~mol$Jd z6>OO$wLL&J*$!@a&GOgi6{04aMXJV{eQj>p668y8+KH2tOy;ZkeE}halo{k_&WbHNE>1^`IcS`N8O9^?d`TeDVmXHX8 zka*PgNAfX1?!dKaBIuUov~Fx|wsPt!Jv_>M;o23t5Q;I#3+^{IBixwd$|G=%wuk#l z>|b}=^;Wh=?GzOHP$e_uXVM7sdmU_q-K72a)}4d{kIz~qOjuE>;*pMg&8ADQOtGJx zZ)(^{Iru>fQaSR()i{s3ez00tl}&9{?I*1{ILLbs?9+_x!|+kSme6%qA`&}z zH$Q%f3l42ts?@b$>1k7X_HI0dZm-QNPIS+$GWcFy!XAy$-$wP(6q$|QR;KPFy&)2; zTjS{-#Etvgnv}qi0SgNYHMsCCYapZ}R@`rzWL@oLOM=>V!i1__q@-}-Qv9IxeM-at zchs>gc;Bpjj;x7+<}IrB2WVovUuj|t3=F)>YPR(c&j<>5=F!#Tr=s;FMI3B}$Fl2*lOZi6rit10!6YOtcAK8#5Um2w2b_ zgls69UzIg8SH<>hl024-Yc0*+o!{Z01|ukqJ`fIuA?t%vGI(h|bw zFa`ySQ8|8s;HS{)`EBNPl76l6)7T@4(RT9YxA6|TR}(V2p~57@l60$^u!3Q=cRqJa zsrWgR{c^5#P!;Fky6x{7R%#5pTE_K?aR@JD2lRzPQ_VqEO3%WRYDK!|XeFU9kn4H= z5<|^m(;?j*MQ!K=KW)`Dvpm^(*Ac%Ke^CZlP`EDgG8`$ObExWZ+U%CbsqM9`C@{RX z9$Q}@J>a{dzloX&-QGn?Qz8%Q=(_0Jb*y>4fg=Yk_?D(75&-yUSI2gGg8A(qqc(l? zREllwh~-Vr%~v-nJrhtxT zN%U)~n6P$y&(e3LbS>DkOPsYsSY5u;+ceF#AjFgB`S4!v zIp@>)@PFP9XMftswXbVmd+*=+t+np8?t7I{{v4X^D5bb1iTuY4_+3NRM}|*E_Vx7< zmDUeF@x&Z<_^$9yPLM5IB%kkm%UfqYu&Uxu&0n~ncGqH$#Wg^@?RhopJKs$p$#(Sk zx9@!OAaUfa*(T&czo0O2Y*Sfeb#7>7YiN$}py`xUy@ok9iH)_K@{{^Uo9_pn-KG57 z?)rkA#?)oK>6V10REsR?W01Ii2wI*-*fC8S<@_M(brM$nAn?;f6^&Mb6KM9iw) z3dZG{i|k|o#7Q+qxNin1G-nT>SPm;j`zKy=gWNqi+%Bh#g;P4&fhM04$1W{jnb+M! zkA!4%XrL|H%m(W2XsV4JsRF&UfBM9l7p%o-m&wO0=>bupC-R7ftknJgwgF1V5YUb7 z`|-5-h39|5+ugqoR~;S&7eqe)V)wCGy*{X!Eadhf0V~CAPxIb=89#9!(=nc*(z$mW@&s}l^#Vc zTF=k1Z+1PlKfrAJfr4JYgh^dWSGechsg6A+4-0&YvxvGMIU|R;_i$2W9nGv+EpA3S zu#cK^3t2FgGQ4d+!1k7NwZ3kKd@i;rvnZ38ONDl=_}bxq!b0Z?((s#biMXZ4ij+sI z99{fRd`J2GW>`H!L_)s447VCpQua&n52a`F)~Wz&XUU-B%oG*H%WC!>uo zg0o83)rrauxzhw}k)osRkcv-VfJ1!zq}#J2E~z>g_iZJwb=B1ty$7wdUh=~sVjX&y z{GN|iedinVQ`bj;m5W6x5@qwY7fo(C6b}uQF*S0M?s8UXl_y2|-}#Jtn={y6%95jz zeM7!ZYCmzUcEv51PxRpXGXVp22oKP@&VA?mHGGDh z^@KZC`TBbO`H(q(SfjBlU05hOaC0n1p$R>41ar zZU0MfD+M{oR7&Wxn-GnSnK$BAPN*zyMr#6(6fW<|Gd4XX*|&baQ+98>akTGzu{k`@ zFEsI5*bL~@?-5GE(0g89LyIMt*5IWTCNRUhU{DvVV@o-3{ExxGk58jXCe--#bv977 zFxUjy#y&v1nEcmWo$?rM{S@(W*x=lk*y>-t^IfWxesafCJLXM=J8U56rTj$yvy--z zfA;czOO6rR$1oBF8>8xF|7_h>usyjUJXNsJ=;+;iem{=7Cs{XD-9Hh~uC2qo){({V z=x-~F40x0tmHVi9=BEJPz`dP_`RDUA$A|K;*{BStWr9&(Z4QgKOew16lbWT~ZC*Ai@5G7r9NqaFpYF=LQX*NWxz>Ugc$fzw1q zo+lQHpVZS~v(L9h@F#J#M|TGF+iG7#%(Ahs91_(PWA)YC3u?SiT^=SHKP=3e39yrz z$eteBoU9FPKU5sNnP=;=T2^R+LCH=LN1ZSm@pJ(JeF4E*`1MdKz7%TKZsa{IqleHJ zO+S0-KM9FSr-YUaz|58xr%98^)eh@wi~9r4v%F=@_pfh}W8BdO<-Pxh<01Yp$HU7M z)_{}y7A{$dL;qPJKlH%S>zw&035$?|mZ&^k15wg1ip^N5*cv_Wo<_%Je#MaVynl8x zLC?Esgm*ogErIzRlcWwdXZrp|b=p#>Sa$R)e!Z07l3aZ&Vq^a5rWs@R6-B-Vd(O+b zbZ$XH@JvX{MU;vsm2w#Xwgy#_)9}=JvRS)r18+wgvBC*l%ReZU0i?(%`3rx_Ka$H_ z_f;d10&YFr81cyd_cQ%Bk8_f#1|_FI>vR3}^kl!pxeCTyl$6I7AP|NNi|yW$X3(RV z)PxB+}RGC^+0?rG)3X7GLU^aj#9Ew8X~E!umSUT1m>R9O0f zX0_LCEHuN@2T+tNuWqY5BKM{*4PUWm4(?MWt4Dag*?<$BX7#@Cx?x|hG#n}iDmdA_ z3A|vm>($}U@{i9@aagj=UXysJvTfH$ORWu1`W!`TYEp0n?&E zbqs17w)(sf7YWv=*L$BsPD>Xq#X2P3Vk;&5=ZpP+-GYD6r!*XsYr)vWdH@CO0=3<= zyyk<48nQPWaJsasckJHEVaf{jh{;f~gsR|F?4$Jw1Ld@aa^FVft7Td_c<;wd0iST?d_Dw$_5Bg@ns?UibPoQ!cE-FO-SH$W?tS~@9MHPjqYJ~XaO;m zAwBrgWT~j+pa15f{?EOD*V|bQCuyN%$43C%TR#KhG71nmX=`~ujSTlv2aP@6rOvwM*TKt!fyUkZv zXyw`wf=732N-mQn2?(}cIvt;EN`mwJ({5VoR6b}D<(`k4BwsGeL$0DNJ3>;Q4+mZn z0I$_CRdj73?!M!4kuzs4*Y*8O$?1%CfX>*?*4o97^qf)l#f!YEPJRa3s3Pb9`)Kjl z-!lcChL<{yQ=9-}Ah{93XmsV|kkz@B_qXaER}?DQL9 z#3~*ArdxkcF1CIt-)5j#Txsm{tnN?>d{91Kt$hHh&X01p)Zw1Xr8olxznDMDQex^) zdge@rOvWQ6wB;kRb2_3%QjXg)1PLR=Q)`09=IU|LA=hQeH9nb;f&*SD0A^Gi6KUQA@VYjS5ww+6qU4)`_wQV-wjx~!=f=pEyO49Dim^rUl zc)(h9?=PsBaqev)tVcM$Q|07*5lUEBA5A{2Z&sIsH*B{ui#sAZPVvkEiesWlTj1(J zE2sxjNTMTOKRS(OGJR9a%g_J8dn5n#gYD2KCG6S0ct=-C`r79|_wXg?^sh_1EY*hm z3{&g6jDUsewi}uNZD2^Z$Wk@+jd7Mu#kaLPYx_F+x%w`JL%tD#F5`Rdb>ZNw66#1@ zge62yuM~tC_J&RR9_#z(N!6Nu;-R?;byXG-00UkeE`(h-2z;K6asx(t9-Rv``F*lC z!1=b<%1+r#pl2gc0#einkFN=x8q@A?>wlyju#$MADmcH(z3W>*Xb1R>)?`Iq&O}(5 zrpg{yANcd8pozcFT=oGLHV(nh+piA;0gje;pc=_Va?IGf?Upr=UcX%L$=HwEO3bsC zCPEvB4lXwH4w`i^< zcUNJPm34{Si_l1{ClIV$+CSAVIdjnx>JvddSk)MM6uePfr}RfF=!DWMR&XUtatZau zsw`;mi8txRTKmDRew>UvJ1;vx z*=Lr^a(>IiK-B18AUh`t6yIq33<* zrJ*ghqXqM$ zbrzO>f>b#rgE-h2m2$U=12PD28pJDF7p{tsYh>*fYk8Fq7Xb1%Wc2f0@y&ojp; zd(tDsDWf{NgNJk8TYrXic+1V&fe zJ$|CVdZ)!fRJZtv$MI#2lL|G$e4b+Obbgeek`5(LTiUv~-?@203lRlQn2cId@sYRG zS{Mv)OkYs+U6Q_kMLkh*yC;9UY;?As=@j+gth4^Qludq9%vU!igH%D@dGj{t+)L>= zNb-#;@~&-j*GQ4gb_|mJqjf#GD2($wuvwqu%+?nqd6dtL3f5G6IDPq|ub_K%o>g7F zq`(nWZ0d(KDH??yhVAc8$18G6uxl&!R2A3RRna%|Gj)#q1sEf@oCxp?EF5c+AIb`>=rY<;m0dFghk36 zW6a0?3eB15P}d}${4twqN>&jn1bm3wt=w!`)9D2s-`&2n{lAS*y!TFxqp&LYUzGBAjlY;o#eKQL3I&%fql+vWd&Nt6 znDr)esuz04NK8H^OdqHt2%es7zCOpw89hM#6Bts+D_bk1GmZ7A1*bIqAF8tK^kvU* z!%=h60pD5>Do3GuuG;s*)2^h|G$|Q?03|(ph||to!#nCd@zYKa6F;Z417?^l`QFw> z;>0y;98znnl<=q1ul3u(bgeRegUQ9olUo^G5sB_;+z#;gX-;Sv;9c;sl_BT&Rk-g9C@!M)&%`tx49#2T))M#A$)#MRbhPRX(2cr%B_K>&u6)VJ&bHSx_!kn% zt2pnd49Bc4JM`7-7v1OlYtq2@o9C)PNt-Au&{eA*W3vtrJmrYoJ&4=MUcGh6N!}8P zT?%$Qq3p#BCAY@s9F}NzIz8#&D3`m3DE+oTlug`EvhYKSmOmG36?{DAEo(nMI=XWt z_V|x(Cn{m!JD+^PTESFBMTJk8=t4_CHj5pOmYzQ@RBx{xI2^1POgDfA=(4&qsr5q) zDFI1eaaPS?VBAslsn#(OX8-TxVi;Q#g&coL_)2#In07d7D3?k{VD zMFTb3wSIF|_7lZzR?8`mIclAG8jkXx12bt!UcW8db^t-&LeF zvK0SeF%^gWG$h8o9Tz6yI2Dz8u9Ut|i4XJ7LAbSiByn|Bm$fzy90J+spuo|pfp$-h zVVZ8Y_Rjulw}kKZt!E_L`G1|kzofy+{ciXkTi^ED9n1M?UBVnv-Br7noi6L>@73We zTAeU6dORN`e^lipia`nK;dff11*Oc(bqfCZ-yZ3|b1J($4_%30>?<6%~QCSjo)spvlVq^-;oriy?rEa})S)j`z zS$&UGh4pRlD-(!XcbOyF$@}O;s@&56FEhp#BOA>>Z1+6hdG)Zb@6=g9V_vMeug`Of zTq7f6kdwT;9i^|^`JJyr(7fkq7j=#Bd|U?etkyhX3g!=-RLLqf1nEOl88DN+jH$R! zB)R7$hCvvqj*Z1*0{_sYoa`0aiS9Rc70JP+wKRTrrYMJQ?TF?FLT8_=X)I?M(!4U<&E5?LjY=d9bK(@9)*ZiBXkTma z!x_$8I$T{Ku!?6Wo!0>+^ESOI7P}(bo5=nGjw~J6cLO!UeuCKIPPZ0z8Ns8E4ZtGS;5i9Gkq8_lP@iUA1BAry8Et0W*_(aIm|C@$HC+N%t-L76Y~E-|x6MZmjdC3Bhb4Yn(z;-O>Qfh-FcC z8(2sHn$Tl-zbHh1s%&BW$L_MI87JCuu9*OnK9yY9(Klk zF#5vY(mX@mUTQJLqG02PRh9R*I zuM!v~?LIQf4$Qd8nAc_H?Hn9AYMBhqQrOj)h^HSh!`top*Tpr&yv#we#^lh(>J(cI zu;$0l-5>C_p(c>h+&yaTRqKu$ey{M#DOBvbdR>HBXeM@DxU_i`b^a-6(ZKb&STKL` zwu|Jgqt~qKe8}nyZGfz;S`&(nqmW%Tow4R~S^(hcE#MVu0I8Z6HJU&k z9RrRsBNG?$4`l7umCqzE`|IE!I&7Z6i~ZL*{1wMBK(~Ab`|Oi8BkOaGwr|xR?ax?? z`aJ4kbYpT;O-)g6c!2?sxP^ehc3|9`R%l^8}{+7p74+j!tN~YV(Lw@Ct%$4Pr{=%+1f|_-cW~xTSf3+FYMRr zg0oUKD+){3({PcFM4_kYjQtV($Ye|_=o5&&!-#3->ib^gh0|GYfh(UmvRk_jIi#{~ z#vXdp8DwDqpofG+bnL#E0da^(9-u4vO1ZYRz7=m$rWJ4X^oR0Msy#v!cU@CXU7GC9sRZow)uRsWJy}`!V&W ziSs&6Vo~AC*W~K)^#z-1jBWE5n=Zvq;GK>}7;q=e$bE3?edDiL_b^q`B3sSJf9&2} zlYTnXXseHoyDRnRWwMmW^k*%LsvNI>Z3es6x?dK$-)eBFRWv2DKbAN1AxSyKjy<-7 zbCpOxx(oI_wy>=W3wX|1DL^l5)20b5vCT)9ZNXIfn&EyW*^-#Y4%ke=bgY5q{~B5e z)JWzs5Z7_JO9cd5Y#M#+{V*p|{ui$@_gO;Km$SFcG8>g|N;WK}0e&%0BA*IH*6KJ^ z8Vu-^8Yo@!CK6!>WRhizpVY*u3ksA@(!5q_)mqlPNJtud<3&H73Cp{z6Oil`k5pii zM25yA^9S8N>nh)Ro;~%p8odU-f_-K2$OPJ9MM#KO0XO@0Te2XTno;Z4W(V3)d&J%) z@X7PL?>i!r0yQcvSOv$M+mFXwF|A<3#cV8AV2+SfuX;-A-f#pIyxit>n@K2%tf)?d z;u;pNJ;;m9PAGN`utMHAKGqcN_P?6>ekvp911s05wm9up&dZV|=d>$>jnHcnEYHFR zrXO0-&}lCzNlw%<-F3l0yqFbv?7b97*~=joKH0829U2v!Hrt)uy|)-m*SHd*IN118LZZ*2(jZ8DtZC-O1wZ zr+SAU^Hwlt;%)>WcDqJ5%31!>B`tny&9z(GCd2INU#M1LEc(jfq313B3nVFh!Aj17 z?B7j^ZR=CO5!)x-)=#>hmEm2JBHR{aOt=@nD7kG=)h&lsx@{GlF&fW^i<|csDtje= ziXGiqpN;QMpmPEj1ldE}efUCKr`6;mStlmgBW205)ti^jM^7V6`A=i2>1!r8C6Isp zb1s2DW%<_-^Nijd(z*Ga7RJaMes$kd(;C4TYXd+X4wF{Dn%+L{J8@c2QOTV9-SVe* z>aIr*t|N1js`XORV`+NE7PWUfb|(FHkiQ=m!<_DCYm$+^Iqu|6sA~${YwqXbJyh~o z{NU}yZF=MA*`eYgf-VDFz3VUUxWIwjzPaxS7QSQu)}!q2PsCJejSwWve>-EX)g!y? zm8t!tiV>QorhzJyZ=0!+;ykd6K=oR>PuR!Bop7^2!!7PnmLa;ngt&FVj6Hwf%8YOR znRlGtSh>m$edoJvc0v`Gp|)?)^QpzUMHOKWa=xwl2@1XhY^Ur;BXigBuxy$>R$!C1 zO_v$GLW&o5UCcjdZkG(1y`vZQnX!b9`^uyiU)m1=umSujczd?E1Mcp?Fx9~Zr3QEu zflJOD%CTkTDPBQ_Z6YS*iBxb z)!2RpUCwsHx!5mP>jn1zw4-0srl*RNzB**q@ia|dh1Wljz{80?RU{-B!lvEay9Y-;eG1lX|mI4Mv8vi?I$ZPjz=Ob|2qK7=K78L=WWrMKyn-Y&=TOKqbeTZR6 z1Se_BW6gocXZzCzW3WE%qubD<&sFfyshuz-&l-daugVNgUAWyy&(wJ$ncd)@Ct>JP zn=XII8@?f1LZ+_wwzC}Myd;Yy_3D$kIjHl;nKM=4qv0Q+!t-5LYunLX`kAtykMrcj z4JTGC7gKN8-$Z}*sTY|X1a$M?VQ)jP;ehuWQYHHZq ztaiuPC3+ipb^yPlQ!VBXzgcnQXPw8&k&azR8i2I58eM{%yyy`*y{D4=| zFxPODU}45!BE7)V)5yAHe`4%F&?PX3g_Kz|*Y14`?2OVHrO zpno^-eM(43q*o-a(=jZx=b=nAkH>lQG@YUR+y7|h(S}YYyNDXZ>ge`Nd{fE~ZL+w#={>U+ z&*ntauj-td%pS?f#N0|>B+mfvM*9V6Rl2k_`DRZk$rOS-Cl96=dbY~aHkqmp`P{Zb zlBC(wS!6APlz~rc6cm~1Ompx(Uafw(L;xd;fXG%fN3InIR`bLTWv(T zw0!Q*yG~aq)Yd_Kknl~$icOcNR_}xHl9Bz(8s>qjcC*U9BA+O?>LGu+0^}QQmvnN? zCSAbkCm{%dxf(d=E6xb&%bc!bO=`v=k<6M(*u9j4d8B3bN9tIg&S{8FTiE(y2M*=Q{<5@oaQVxoBZQi%8S_a%=Hn73$`~gw{|v z+^4)MSo)^lAT%Uee)W!;tW~GXrYU^8@nW_E)VXuCy>iC1`dvAseWV<;UvIWJ=Dj;# zYSElfy~sB;Tph_uuYL zT`3QHcX$JR@;j~U>$kTFOSR_48aV%ln3){AwIE7e`a-P+OC)AsKI`6WYcbF34@6#Yzum3-VhCz4@p7nl6aNw3 zZ2oQ#vTBKNyiM&{OT1rH(Pn(rJj>{1_FYyoPe^Cmk=DWnwUzaHIew}y)?bp}3r9D* zdVzqXP(wW-jsPA}eRqv$&9XZRmAX=!*=&-mMY)XVys&+{`CMp}f55YG=7@)9pKd9g^L%bC>oQncgj}2Um%onIPMP?Z2&x8$>e|xSUVyEQKiw~PH&6JgH?bLa6tVF zJ7ssKcB@jKSKh?~3(5R5xxZ{Q84UUt*nj9+e2x%q8$2`q@o&OyhP%z*ymi^Km1uY5 zqHB5V*)bftQ^1+~5j)(OeiM>DO-@H_usf%%r4Ak=M5b$lj<;{^@f*VZ!EiCubvM

-T6XX>XkTFzkUd{gwQrJ+erbvG&s zlz$RhSjccaKS;;dG3R(z+{9~;+nCllp@4r&@3(E0;T9lRSXN9cx`0&DpAnPaTvrQx zIg1kAqHMe=#>5po3P)XGaVHS^zwGM{L`N|d5n{6(h`J)>L-X0?24C9}@)}sE{94b5 z{NOV7!KL&8j1MCmN-4jbm|2$9d-ax}eBl+f<&HA42FV`TkJLta!1KNL+3KRY*<4FB z6J0hWa9FY{{k4?Llkluow%0|ojKR+ty(S&mpmFmcfOL+VC5+}uSu9ECD)(`IAHx8p z8F;%cBZNi^I7U{gdO`O)Uq3)Xs$ganP1;E&p>QJ8jXJ{1Qhzn(lKF!lX}s@^Os~z= zU{<&GCj;NX!tB#()wC{#VmcHwWImH0L?*{A;LW~9c({Ma#3%mRpsvNzDwfk;ZKXxD z^R!A508h}}W!+kv^-S??DM2Ym_{8g@7di_AJBQZRA;|h=1=9{mBaQvzf{Q`KeLTYR z>wF0*x%u9;Dzm`lJ6g2xUP~W!1t)Br&C`cA&PMI~L+Mw&Dx+GQy=dx%1qeZ&KEYgM zd|AK~Z??89x<*le1cK}?Y=cAyV}e#=)-kQ-yew*)5p&G?Ed1{TDoS?CA?G_^S@(%m zuV$?9-&>4%Sqk?-;g0^jbv;+JSecEe$W5rq2hVz_)nL^;tg?_tar0tsYDoec5KV&_D|>v zfax&UQ}RQy)=4eN(XjL`7~mb`LP=8=N^X%8U6LKPbZ=F~@H(5}RORY`)0MBSr>VdL zb1+M(KzJovbBDJ523@s^>8*>X@84WtA|IXLEE@(DG{qoF@pV#59^&C4IED+?ga#2cVnUGfHXEQYi!$h8jtVYcPAHC@F z>&Dw^m_@A0lSKoBVhcDMcUa`+=BKvM;y0`(D5CY09LlcoP~hlq*($cXVmgS`pZ+&y$iQ=jG0?;dq~Jh zgrYrmZ~B%r;O6r4!@j|!?L)SF=@7DwHst!#^K4!Hdp_56-Y+?3uTeEBsS|Kze(7g> z=^f%*^LOd0Z+gCg+aKKK)I0X7GI{~OjzgcA`x%5EI3N8Hu3AEMJ32 zdm_yo7vz%(W24uEyX@E`9c{EP)CwXc|Ec5oHjQc>bN&EMB=Pe@*MXP6q}8si zuT>LFkpZoG@6OEJOxWTD1HqleIZLDyDPB zIm^-Lftq8HIfFk38G?#k*FG~>^w8czCDwyoV1@2CeI9AAw-p`t~ zA_dtrJBQd2AJt)?hF2sK-&cWp&HKb}0{xrD>)Cj3&g`&%s@>9RS<_9V6Dvx)lq1pISZ->lj^ zjsBeaRttz&sqG+y(MYEYBqaIP-$;?4iU{J30U4`1^tLPxh^^6Y?Px|`v0wvIQm2Vc zgM*tWtY%>WD|(*rm?fCWGEb+e5mq-prM{Q@1mDLRdux(jE4V%X1q$ zvyA>AhNNsVlk;P}qN!-Ylvc0*gdf>zie$!Mxf-@}(e`n;rW87&B zb?)6o$KITwv@$bhfCiOSi}VrslQw5#US+^R_S>CvJv-@g~Z`d zn*Tmre(vytx(<9bC`?(L8kUU$z?T>12w4e_Nta1+p#kZvOT3mYr&?4Npk^0xhURs~ zbI;mTof9i&gF7Sn>VDctl}*7NJ0aMhW}6lUvmH?2E=P!PBk#%ksWv73(#2Cs_wHx=lCVi73f z`OB^=O~`S=grdVk%<2S!L^?H^Q=zm)fAk_JMZmb8xzd*g&!oV1uXLJsABOr!C{sqA zO8XvYODiUXb`;R|#=FxlRcRWIxOF|{$e!^|eTGlP`(uCiGI`+aKk<_O+#Mge0d~j_ zl;ot3H8TXZQA<{0mRBq-j7CqR=?=Me3)Fy%nS$6F-nZ$B%7vquIN2dR6=o-jft8q)R}+-?~N{@eFe z)XM)HS9Mg=Hw^^qMA2ldTUX$*!v4*65_>|;=_7<>S^YF>DA7yp!o9SwUM~(xir3PTf3WX=AwGr0?TVO%L|U_{YO;n{Bqlp%9XIN#=703 zj*Nj!lSb;H;1`jaPP5LD-Z8r1@L zpgc`my$2ntO~!K#)k#=}x6#sRIs3{zd;%#Ix42DPI+Z??gls}1zTtJ#Ik!_qR6SB^ zBar0*yN=r^Dd5i~(VuIPd{Vc*24%&QFZF-6P1uxD{SuImaVgn=E~IN#LaDc)8gOmk zuVA=TfN-Qb$hJ2z*_zPwG!W2#m#{UMbciTG2Na{ffZDu;N3FwG?YE;P4JKw5MsZ#B z!uKW&{?RhVU+YQs0c17v*c?uusJvf=>kO#%p1R=LzowfS=+(Q`W<>KKDLK>YJu94Z zy(f^{&+U2@v@Om_Z-`oi^ab6HaH3^Ab6H(0bXna9ovn1#5F31hwLgYPI$+h?a)%bc zlZd!X^fi~YDjPdM0UchASi`JUV78B@*AKE@`w4DUnlL$AwGg?;ldz*`9vjf@k7!+v zA<=4|!khT_4_Nc;{sP>3-VboGbS_9VA9SNx?R|Az<#=iDl63N-4{Ih9@99I^aLb7SgA( z8Klu36Y_ikuwa|e&t0h9ZH?Jj-5=a_UuakBSjgj;>?{8GfHAE!*RMg4*c=Ppkn&1d z@wcf}wS3nGdP_{iEA=*bxN$@k0;&PSTH~zDq>IaY_$Q-cenR?+SRYF?X`z)C^_@@d zYHoqQr6tsnic@DMb7R(T5nkI;VnDl!D-=LV+Qa4M{>TIDZQQgCSR4t!H zv1tpDc2QNlD#*x9*)yc8qA>2kF4VGSK7J?RC?cSxv_ao}gh9xs1yuZ+$C;^s3*37B zC-;`$gER1w6x3nk%0HVZ$2G~^DuDbRZ9n%&u`MOcqAK*IML8Y6L@I+0Hxf?(xJ}oP zE%O(N7G5m@!_dR8@`+UWv)Z(;Ga*H4-)tdV;@CNp#we%3>QJ(4@vZpTDu zDZjNlDbN+($yyvdMs)%Ys#kwIBCI|+5jg0HdCg4(5`Z2zbc}EOqn>iq^PMl`q|%i= z^lFQjtANL-&S2%CJKJ-FnTsITF}u9^KIGT#FHO^J-KUnYb2;QE&8P+EV3P&n?T+j; zsFru*uYM?byvL`AQAewh?0$1`>t%I=fUd5|H&qXLGp;_)ALfo-`Moe*O^s<7t#8AT zmGq062u&%FrIVhH#EjfSKl$~jQnQzZFH8>a6us%Mrc$sZc_@1Ucu-!w9)2q9`n7B2 zL^(pH8t*kExjvz&El7xQNa25&=T*-Yus;qvi454hzni$}bPcIpH`q_7O(meriGM5~ z+bwV1SrfLVvZ6_l`ASZn+{GUnc|ji5sYg!r^n$g=pKXg34w2N{b%n2=C*r%^k{;P< zf5L`z`aa2%-0j;G)krDSHA$J-fAFkVD`=rxK=AHN$&p1bk8?I=#wzCip!1B!Fg`-q z@m8%WaMzfBj5Nxf2mRaj%6YaIcp5?gOV0|I@pF+qGlymJuV*I_&Rib2@PZS7I=LOK z#<3S(Lw|}+#7KRJQ2Ufjava4g=Dla$t(|B&n{oD0Yb{9D^T|s4oGmfL4#7gPezm87OQ!YLkVfxM&AO!lDe<)mE8J9S*Z0mDFk(4Y%|9h^tJJ;&Ss8I$(kzX zm&r+$YRXZt1Fw#~iW7-?Z@uLh*?A}*+O(Og6CBk&@kE8+=Qe)p0XmV9!%M4~UT_e7 zU$?%t?W3rHhpe>RXQyfhX8YD*7UbbOCd8l`M4lmtw6 zTK4%kzAWpgbJJozZ?7RYS=A;_Vg_$KY;{ohvqIatMbWnF#Z`ecG7bRk+PJbNekJKyQM76Xb{i^?(O&@9?Tj`*E#KaAB#Bg7mk1qYA_ z0c$Y@CWshi#7u<$D$tC=r6b0jB1uCqXG;pz2Tcv865|Iw==T zcXn2K&sPm6ygA<#x^OwA{c-0w7r`5a@O<+`lKrIoh%z~@mZPhxd^lLguyJ90#N-q_ zie8S!0)4iJZ2@I%0+MpLgZn25Fmo4Fd-SJSb>y#oT=VnDw{Nh^Z;zV&$7g;D?95_r z#%h;0agyDi2!%akS?EeJww9Zk8V78Gvg9w-4WxT>vFHs)CtI9YPWCR|JtoFs9q{4E z-p^v7A~LOLOdDXodYn=2&V%hhsrWby(R$O@u2P=IQy@hQb&!fWPF#7N(p!S32KIZr z4d_%}&)tY6x@Wj1I*-anae)Ye+3jKzFRPaH!;;srHeKY0o`_ z0cmybU74bY?|f$l%1>eiTV!^9JlfRisA0(0M<29WZza0-N(qXCI`s^)PegKeJk~T_ zR%6>ie`^*DUOy}QaAHrp5I_s6U-Z3-)8amCpBTeAK>A<{}u^6S+859O$R~^&LjQ;m-lSXBi$?0P- zTqDzid8xt6fX&OhUY$*?AP?+H}HT)G)s!3p%f?CsyZF|%C*pRAcaEq=H zYnpdOA>Db&y^4yGb~^%MXLj)4`F?CBpQ;6Uedi0j`kgNc_GFAC32eTA?1%)8p!U&6 zEzUc8;SQZMck}Nxs}Ol`NFyq3e8f&$gvu_!$%NTy3mD+-c_SCVbVJMiDNViouho2`uKq}LjRp6do48zs?x(8{K z+aiS~-)ib;+b;oo89@Me5ogA=yxY-=Edza?oxL^oH4-izeuT)AT#dAHgX)rdP$Gw_ zdrvUA*cPMjd@@N@xw1Cu+tSkxWee- z$k1q1kXnUHscdSMN7C}NJ8v4jO^SPZs)iiKX_N&`ee%Sbeoa>y7dFp*CA=|q_zbeV znx{lJupvcSzc}(x8o|vm2v6VkSvind>RmW`6}hO_;oxqe67F9h=@vw|6j_thq>SLM zyo<7n`C1$^imdPE3KC{1gmuuwdBN29JC{9N)KmqWavFbGlNp=7i(AGt(*I@yJs(Uq77mv4_s?#^}=^g|0pZdI{kJU4OGvr-#dI#Yt~?np@2+zoh++O_`Vp$d%4 z;!V5;@eZTjApKzu(l=y={n|LUuC-WFmFtQ2-a{@==Ql;^83FkQhTMNPINvXQ5X^o5oliI+O0Q5T zf#nu>cB9%5I@P{}urQI8T9$RfS|&EB54fiaPedgYoa)L0lUV8E$K$jEC}Dg)9FpGF zs7odyh?4t)6ubK(mNPD^%}@K*va25S%&X}dY8N!S(WHZ~ze4-G)iGoGYA(a%REfPm zW0S#1yThO`!&|j$s%vt!nPIv6s{+!4edS-uI?&i+2@9j90cO)}(pAC*&pY&cA=@LD zBZGBaXTqyxJI1y;6IOnk(AxIw@wJ)%yubezs^z!GlPle*_7{Q$#AFgnkBlGYI|N#6 z`b^3h2rd9MN8%PlmXs3}Ow5fbOjvCBP8-bO?}aV@C8dn|sZs?Gy@l8||NLOZlV7NQ z{fB=*?zg&v%W5B@9(FClEb0!5++-T9EmA8vUU=a`z+1nR9E?lD@uTS{`VfSdg#2AQ zISbputaU*H-J^(;XPUe@++&pe6K)I#UjDBJiRzleb6>=O@m`pI_Y@u5wvfEIUfbGk z=Rdr5w5PaY=k3?+4Q>t9zVrRnb5FqwR+e*_BJg*)>5aY8PrHrkUU@6k_pRT|<}D>r z#I2=cTfNYu;zi+A&#R=Z9oPYhq4ZSz+=ktT%e`;g(4(U)Qj@m%k#1nj-ZEj)bx}!4 z_*j{XiGEk#@b4r?<)EiAN+G6o@DpivV{jE<{+$mWV>XNA>nJ3Y156dqcX^acp3d?rbMN}aB(Q6ZI#}u@K6My3 zSl@xG7ZJTzrF_{+;|oYQ<^|_k`YYdZaGjqAKM{ExlhNu>W35sNmBmY_37LnLd$+;E z+3lQfsgyvy2Fw&O+7BwJhhDWU{DhDn@Lwzt2bArPeHAJESMO4JxAEXjU-3L`d1%`g zH%+o$Q`s$b3kXmk)9~p-EDd6cD{34X^XQfs;yjzvT36E!Ivzi@X9FK`mHMU}71!0< zkfWe_gxydLFzQT?{$qEY_|dS|!h@~HjU#3K1RRXhSsJWZIKzt@fT`v}w-&F*4Bw#9 z-Ze2`Yh%TDmvxU+rH&isGQT=N69U1FZu(D6>`@nZ+*;;qf51`_zFst^TW#3AlVZTz z2__#Xdjyov%^i3k;AZHdR%I0hxA8(x z!(aVh?VVRtlj*w0-OEwOf^0=Zr5#0JV<-a%NZ)%zkQ!;BgVLpi-a?s?Eg%pO0@BGy z3ndWgQZoV}K!8XKC6EY_5<*B2NQ2URUUb>2USC?mAOAoa9$NR+5_igSI&x~+~&52SC3w86^%SJ6BAT2ICn|!-X?YX=3MLi&Qa~%#wkP%9px075mbk+qj8dt|uiY z(c)qgc0jE!m>95qPEWKW86!sapS&hT65zaVz$qEQ(r?SRjz51Qr-PwscKY!PHPs8L zU1vj^)nz?Y#3Z(F@79!6VDhoV>`iHzfsh;@r%r{JE*T09Ae4*ruL_jx*&WM}ODxak zneAV`kbDz^>6E@mLFH5ugf>V-b04DefjJ{yFS&i!?{Sj)Oyc1?D3?W!eAyuspVy*i zo|0h!w434HuUnixsvHU1lKYD4F&rXh){j&DNyuYufPH{I*LfV7WaYRgTZ75)lGDW~ zy`%x*BL@6a@0_diJ~)vaS>Jt+%luh3#OC?Eyh#x0-uE+Tc9X}N?G$;&cfzd)JpIcl z#xVM3HtG=h*Ur>A7I30S?xWO6uc^lHlqh-PnaRK$mJB@~ec?1kh0gyBdw;Xg7`2|o zU+>dCd7uH@ZY+Fbb&Y3__Dou?{D|J3<9|Gs70P~-oCJPK9*p_ju*U6K#avPjoTYT! z`fBzxH-$wz{=Cd`Y8-2VW6#zImDWn3yVDfBF8d-R4>obdo6TBNooy71kJn0YtxL?X zeR<1C`=}?|BHQ_5W7WH-H0P=pbnoajhZUa0{A4W>JYW_HkI7H;@FXm(mFZ+!5pCt2 z@e8W^WO}5q5Lwhcj!DD^tNK4GyKpZoiSJv$U&z$NiPe4XD8&A{Gsn^o)XhFHNA4#7 zYKM9_cCLreh!t0|D?ZvW^=PxN!Za)gtD8IUrlmYU`+MZZEmI_}rZ@we^ltwRoNGmv zEdDp~^nrm3Zuw7#X`aL9$N(Yy^Xg?a@vHpuuX?YcA&Ld2op)mIM1FAm+25xY)45{5 zYefqiY&24mji*$f*@GWF%Jl=FnB;+XSWaA-f$rHP4GoJl7^==n$ko% zX&)sU&juGVA(~=hA6|rDk28zPChu@1qG}V7dF4g!@Q7LRN=mzButpJ0WM0cD6Qtzc zq8rR)b-d?HHwXw^k7>dSg7Cbn1K()Q9PyZ^ESyHZ?2?{TSW02r!x^ttjyOPBmUttJ(_+znRFHEqJFiE|iPP{)Bg(nylbifT zvQPAXL0 zB;Jb}kpYjb(F`PMCM!8d(l@1g>Z05X9h)}G+WQ)#9(aX6dL!e=S&*-uZc#jXMA&@& z)AVc-^o~=Ms&odg0}beL>TzU>xLKi+Uzm$*q3Br;If+y4XIRj(L$0A z_V?(!dyFo8Cq1)V{GfJguFF!wbW)HCxgMlUdixc% z+{Qo|im4jPL(V(XqkmGr1T+|!`)TT|<6si*YER@x4Di1D^w+pF*)~sX-r|-7NlzY2 zVZx;vJl3_QL0tbbTtAuMyM{*A(L`(v%XD~COsvoMYz~h<4*y(>kjD-t&Z3vPrrs_*{eDIStQY2951omx zTF**;w(t4iUnbI{9LWp=!>^`0An1n{qEE~k*eiM>tpEw0smc`9t9X(}q&p_SdUUle zVIh_+9`nE~LOd3Wcx56iipy?s{mA!@jj4==qhbrZw~{j;FL8k}s*+lV*vG&nW&6Ba zTJDZ3u%HxSMWo{lMjzmUvCcmFIB&miFk=5XZjoGW6CGC-12Pa1G0ex2(!Zrs4d^Fb z(cbF^{zXHXy#^5>y%0(W+)PCxcgz(xC#Ys^#7sTL(-YcoC*>dh9HZkTxCyLet%5d5 zJ$I3FY1pCVTQ;UNdo0EOlVtq^qUSqKy(Pnk)X z=vU;Q1Q@oGCBFc)DgHS6*de>{Fi5(^qb2Ub<9-xn-Tic%uJVPBAt!%7180yO2(Af$ zLx2AN+I2xsqU%Jlp?)53E%fBXA##1|L1F{Rayqw>t>V{xgSJlo?8&d=FZf+JEmhg& zGs`}m`S{QOq;WrkU2v_qo%j#VZ_gVSHu;(uA;vW`vpXo2Z5H6UHo&cU%lv+1^5rqJ zSWO9W-**mO(gjV?)mANv1r*c^nzk)s-gg!_+Ia}y!KY2L>pSjP=)m#K3+Yt<{qJWg zNMpunxu>F2;fT`CvM2M>H-h4cUm@G*TtT10eDc#JbYB!5gIvIW@-^<7o@rrL&5Mrx zfM}oK5;6$s?pCEk1AeDgxqfm(5MHbWqd_GiI_!;9-vIQY%1$s1hd51HsE^ksML-nfa#2_x<906jQ? zX`6e8U@94;XWJ;nD2Nv0x|6c{+=Kf(v8y>hGm?c3Yuy$<8W|05;7DwcCU0vm-OM~C zRysXCkm7pb@671eDU=F5LJ^Civ3o@&2;B0*nO1C3PO};F(<*I~v1Xy%N+9o~Dqhyc zSJ~eK=W$iE#zKy2lyW3hZ4}JdfJ?nRe%dg{yyf~p&A=V#0bD0-OF6V=zT!P{ZsXMX z>s2$sF}of#Wi@q4i0D5a^lUxI`!4B4FqMXV`?Or$6WXe1#u_2<^Zdj_YxV4~J94Xw z#MpMD$j82G(YQi6$H{BtQs5@uax0l~c)awQS;nMJa)Lrp_x259^7ma^yy7-)cVCwv z$bh=*KV`oP209aF#bg1+y;E%uOn*y2Ysh-pD^?{r1MER*PW4cGYAhRdGa*&ve{aKn7k*amVm%HR+tw)$I-+z$Jx(E0$eIu zca36saV5&H985c&s9Cgj*X6HZp!VBM4bwYb=I_F-v>XnN5!>%94D+6%xh-Jrh0a{U49XH6}iHy zDT|7;sVR6(GNs{#GBhcHPT@$p*R}FR^^MuD42mF2D6*ytNv_Dw;w3m|B~BDDnMM0h z!9}qd06hc~6=AQR!9KdN1Idh*G&31+jfgY%AZiF@S6js+Bb$3|uv-9cZ|@{K7u6cO z;>iP9N85eV_^od z6>Fpb*24&DtgyqzUym=^v@05A{JcmoCR7QyvLCv^G?fIH4XyD>^0!pIFpqo>EP2Dj$p#+yEO$gI*&y(1*0kfms%|fze_NOdW%e)XscVoz zKlyP}F5|!(6Qs;{jb6fa?sG0FA@Ik(2t^TWjA0^JCno4hgzG%?RzZQN_4IfiG@5y)!&bjM)oEAX-2QON zlHi+idCVC=@7>f76~9C%=v195PWVO%|NH8Q#p%qLwXb)08yeVvL$punCKT`IC=iM5 z-_J~2*3GQVjVuAaRSiy4r15Qo3Da2{hOfbe4Sq_xuXSoD38x+RbMmtE5DmM$?C^Xm z_ua-2LXA|&fQ@k_%jHUH$vaFzgC;m#)eN&Z=dO4XO-q4u*$M+k*`g z60co~O6NHBbeF7H;EzOR->GF*2ROE*xm!#*XUoRWb5aXd#U;kR8pqfLB8@ZZpbi~k z6YvPk2Vg3IAuYVlIkAQxJDW@z4&JWac33;2s#ovsiRWqC%0$$YoClpyZwJXMOgm=T zOQa7#8wMKv!dWT|X}epH8W~a9R@k5G4fX~B>=C}2qt5~!y$d4C!Sj&V!YyDv!!U%b z)(ad8T`THf<6?^{(4`_$VN&|?%lKUBcF1)X6ZeY$f?vF;LD))*v5-un&TBNs&)$bU zAAGFm43^)4fj)f$6&{>0-d)ig=Gk_V?jAg)%8rm}Ns6+ff*u~4286}Oc&d38!S^_cb;z=NeER+-6me9A zn!ozKK0#6cnE?5o3E6S^J!(Z}Gr%2PN72317r*>;wFd0TOU`}RK9nrd=z;= zN@tLdnkWZGkvUx?oczHlnw6iiac&2e+7xwdHbys8L*npG$CT$flmTrFdbe#}(DVu( zwxIH*5(k84%qgR92>0aa$W2}!&26+Xe!zvbiSpfD<21?h%Sv5?o^Ek1ycH)^Mpsgs z_=%Udm0^?lS3%1;j_1I?;+M?0QhXBTvFpeGhah7m#Hk--CK1;vfdmvv< zul1Iucy|xG0{;l>Z%S=aP%UVKQR4^H-3kHcbzIbSvNWZ0BAZ^%jBn2v1&kg6)dn}v zNF40GNwkW(F3{sP`P4Mat}J$cwx6_TWPB=ht!ud{a~JJEW=UV2i`KK&6Y6CAom3lm zz!Iy2f-~!eMwV;;-7{sI-3obvz&CqG17^GnWo?72hciH%lt3@;gC^&lhOM~V>*l7z zGM1V1QwnG|p4Di-hj6)-;}}i16eNQL6Xa(~kY*+BRY`FZ_``_9je=YwP(nVK( qiHG=q&U*PDeSSQDDDXpp9}4_X;D-V~6!@XQ4+Z{H3jFQ+(tiVmB. + */ + +#ifndef CA_PRECOMP_HH +#define CA_PRECOMP_HH + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include + +#include + +namespace asio = boost::asio; + +#include +#include +#include + +#endif diff --git a/agent/proto/agent.proto b/agent/proto/agent.proto new file mode 100644 index 00000000000..5a9190d2c12 --- /dev/null +++ b/agent/proto/agent.proto @@ -0,0 +1,91 @@ +/* + * Copyright 2024 Centreon (https://www.centreon.com/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ + +syntax = "proto3"; + +import "opentelemetry/proto/collector/metrics/v1/metrics_service.proto"; + +package com.centreon.agent; + +// Agent connects to engine +service AgentService { + rpc Export(stream MessageFromAgent) returns (stream MessageToAgent) {} +} + + +// Engine connects to agent (reversed connection) +service ReversedAgentService { + rpc Import(stream MessageToAgent) returns (stream MessageFromAgent) {} +} + + +//Message sent to agent reversed connection or not +message MessageToAgent { + oneof content { + AgentConfiguration config = 1; + opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse otel_response = 2; + } +} + +//Message sent to Engine reversed connection or not +message MessageFromAgent { + oneof content { + AgentInfo init = 1; + opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest otel_request = 2; + } +} + +//Binary version Engine or Agent +message Version { + uint32 major = 1; + uint32 minor = 2; + uint32 patch = 3; +} + +//First message sent to engine +message AgentInfo { + //host name of the computer of the agent + string host=1; + Version centreon_version=2; +} + +//Agent configuration sent by Engine +message AgentConfiguration { + Version centreon_version = 1; + //delay between 2 checks of one service, so we will do all check in that period (in seconds) + uint32 check_interval = 2; + //limit the number of active checks in order to limit charge + uint32 max_concurrent_checks = 3; + //period of metric exports (in seconds) + uint32 export_period = 4; + //after this timeout, process is killed (in seconds) + uint32 check_timeout = 5; + //if true we store nagios other metrics (min max warn crit in Exemplar otel objects) + bool use_exemplar = 6; + //list of services with their commands + repeated Service services = 7; +} + +//Service (poller configuration definition) +message Service { + //empty if host check + string service_description = 1; + string command_name = 2; + string command_line = 3; +} \ No newline at end of file diff --git a/agent/scripts/centagent.service.in b/agent/scripts/centagent.service.in new file mode 100644 index 00000000000..63b041150c3 --- /dev/null +++ b/agent/scripts/centagent.service.in @@ -0,0 +1,33 @@ +# +# Copyright 2024 Centreon +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# For more information : contact@centreon.com +# + +[Unit] +Description=Centreon Agent +PartOf=centreon.service +After=centreon.service +ReloadPropagatedFrom=centreon.service + +[Service] +ExecStart=@CMAKE_INSTALL_FULL_BINDIR@/@CENTREON_AGENT@ @PREFIX_AGENT_CONF@/@CENTREON_AGENT@.json +ExecReload=/bin/kill -HUP $MAINPID +Type=simple +User=@USER_AGENT@ + +[Install] +WantedBy=default.target + diff --git a/agent/src/config.cc b/agent/src/config.cc new file mode 100644 index 00000000000..b47681037b9 --- /dev/null +++ b/agent/src/config.cc @@ -0,0 +1,148 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#include +#include + +#include "com/centreon/common/rapidjson_helper.hh" +#include "com/centreon/exceptions/msg_fmt.hh" +#include "config.hh" + +using namespace com::centreon::agent; +using com::centreon::common::rapidjson_helper; + +static constexpr std::string_view _config_schema(R"( +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "title": "agent config", + "properties": { + "host": { + "description": "Name of the host as it is configured in centreon. If omitted, the system hostname will be used", + "type": "string", + "minLength": 5 + }, + "endpoint": { + "description": "Endpoint where agent has to connect to on the poller side or listening endpoint on the agent side in case of reverse_connection", + "type": "string", + "pattern": "[\\w\\.:]+:\\w+" + }, + "encryption": { + "description": "Set to true to enable https. Default: false", + "type": "boolean" + }, + "public_cert": { + "description": "Path of the SSL certificate file .crt", + "type": "string" + }, + "private_key": { + "description": "Path of the SSL private key file .key", + "type": "string" + }, + "ca_certificate": { + "description": "Path of the SSL authority certificate file .crt", + "type": "string" + }, + "ca_name": { + "description": "Name of the SSL certification authority", + "type": "string" + }, + "reverse_connection": { + "description": "Set to true to make Engine connect to the agent. Requires the agent to be configured as a server. Default: false", + "type": "boolean" + }, + "log_level": { + "description": "Minimal severity level to log, may be critical, error, info, debug, trace", + "type": "string", + "pattern": "critical|error|info|debug|trace" + }, + "log_type": { + "description": "Define whether logs must be sent to the standard output (stdout) or to a log file (file). A path will be required in log_file field if 'file' is chosen. Default: stdout", + "type": "string", + "pattern": "stdout|file" + }, + "log_file": { + "description": "Path of the log file. Mandatory if log_type is 'file'", + "type": "string", + "minLength": 5 + }, + "log_files_max_size": { + "description:": "Maximum size (in megabytes) of the log file before it will be rotated. To be valid, log_files_max_number must be also be provided", + "type": "integer", + "min": 1 + }, + "log_files_max_number": { + "description:": "Maximum number of log files to keep. Supernumerary files will be deleted. To be valid, log_files_max_size must be also be provided", + "type": "integer", + "min": 1 + } + }, + "required": [ + "endpoint" + ], + "type": "object" +} + +)"); + +config::config(const std::string& path) { + static common::json_validator validator(_config_schema); + rapidjson::Document file_content_d; + try { + file_content_d = rapidjson_helper::read_from_file(path); + } catch (const std::exception& e) { + SPDLOG_ERROR("incorrect json file{}: {} ", path, e.what()); + throw; + } + + common::rapidjson_helper json_config(file_content_d); + + try { + json_config.validate(validator); + } catch (const std::exception& e) { + SPDLOG_ERROR("forbidden values in agent config: {}", e.what()); + throw; + } + + _endpoint = json_config.get_string("endpoint"); + + // pattern schema doesn't work so we do it ourselves + if (!RE2::FullMatch(_endpoint, "[\\w\\.:]+:\\w+")) { + throw exceptions::msg_fmt( + "bad format for endpoint {}, it must match to the regex: " + "[\\w\\.:]+:\\w+", + _endpoint); + } + _log_level = + spdlog::level::from_str(json_config.get_string("log_level", "info")); + _log_type = !strcmp(json_config.get_string("log_type", "stdout"), "file") + ? to_file + : to_stdout; + _log_file = json_config.get_string("log_file", ""); + _log_files_max_size = json_config.get_unsigned("log_files_max_size", 0); + _log_files_max_number = json_config.get_unsigned("log_files_max_number", 0); + _encryption = json_config.get_bool("encryption", false); + _certificate_file = json_config.get_string("certificate_file", ""); + _private_key_file = json_config.get_string("private_key_file", ""); + _ca_certificate_file = json_config.get_string("ca_certificate_file", ""); + _ca_name = json_config.get_string("ca_name", ""); + _host = json_config.get_string("host", ""); + if (_host.empty()) { + _host = boost::asio::ip::host_name(); + } + _reverse_connection = json_config.get_bool("reverse_connection", false); +} \ No newline at end of file diff --git a/agent/src/main.cc b/agent/src/main.cc new file mode 100644 index 00000000000..d78e1dc80ba --- /dev/null +++ b/agent/src/main.cc @@ -0,0 +1,168 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#include +#include +#include + +#include "config.hh" + +using namespace com::centreon::agent; + +std::shared_ptr g_io_context = + std::make_shared(); + +std::shared_ptr g_logger; + +static asio::signal_set _signals(*g_io_context, SIGTERM, SIGUSR1, SIGUSR2); + +static void signal_handler(const boost::system::error_code& error, + int signal_number) { + if (!error) { + switch (signal_number) { + case SIGTERM: + SPDLOG_LOGGER_INFO(g_logger, "SIGTERM received"); + g_io_context->stop(); + break; + case SIGUSR2: + SPDLOG_LOGGER_INFO(g_logger, "SIGUSR2 received"); + if (g_logger->level()) { + g_logger->set_level( + static_cast(g_logger->level() - 1)); + } + break; + case SIGUSR1: + SPDLOG_LOGGER_INFO(g_logger, "SIGUSR1 received"); + if (g_logger->level() < spdlog::level::off) { + g_logger->set_level( + static_cast(g_logger->level() + 1)); + } + break; + } + _signals.async_wait(signal_handler); + } +} + +static std::string read_file(const std::string& file_path) { + if (file_path.empty()) { + return {}; + } + try { + std::ifstream file(file_path); + if (file.is_open()) { + std::stringstream ss; + ss << file.rdbuf(); + file.close(); + return ss.str(); + } + } catch (const std::exception& e) { + SPDLOG_LOGGER_ERROR(g_logger, "{} fail to read {}: {}", file_path, + e.what()); + } + return ""; +} + +int main(int argc, char* argv[]) { + if (argc < 2) { + SPDLOG_ERROR( + "No config file passed in param.\nUsage: {} ", + argv[0]); + return 1; + } + + std::unique_ptr conf; + try { + conf = std::make_unique(argv[1]); + } catch (const std::exception& e) { + SPDLOG_ERROR("fail to parse config file {}: {}", argv[1], e.what()); + return 1; + } + + SPDLOG_INFO( + "centreon-monitoring-agent start, you can decrease log verbosity by kill " + "-USR1 " + "{} or increase by kill -USR2 {}", + getpid(), getpid()); + + const std::string logger_name = "centreon-monitoring-agent"; + + if (conf->get_log_type() == config::to_file) { + try { + if (!conf->get_log_file().empty()) { + if (conf->get_log_files_max_size() > 0 && + conf->get_log_files_max_number() > 0) { + g_logger = spdlog::rotating_logger_mt( + logger_name, conf->get_log_file(), + conf->get_log_files_max_size() * 0x100000, + conf->get_log_files_max_number()); + } else { + SPDLOG_INFO( + "no log-max-file-size option or no log-max-files option provided " + "=> logs will not be rotated by centagent"); + g_logger = spdlog::basic_logger_mt(logger_name, conf->get_log_file()); + } + } else { + SPDLOG_ERROR( + "log-type=file needs the option log-file => log to stdout"); + g_logger = spdlog::stdout_color_mt(logger_name); + } + } catch (const std::exception& e) { + SPDLOG_CRITICAL("Can't log to {}: {}", conf->get_log_file(), e.what()); + return 2; + } + } else { + g_logger = spdlog::stdout_color_mt(logger_name); + } + + g_logger->set_level(conf->get_log_level()); + + SPDLOG_LOGGER_INFO(g_logger, + "centreon-monitoring-agent start, you can decrease log " + "verbosity by kill -USR1 {} or increase by kill -USR2 {}", + getpid(), getpid()); + std::shared_ptr grpc_conf; + + try { + // ignored but mandatory because of forks + _signals.add(SIGPIPE); + + _signals.async_wait(signal_handler); + + grpc_conf = std::make_shared( + conf->get_endpoint(), conf->use_encryption(), + read_file(conf->get_certificate_file()), + read_file(conf->get_private_key_file()), + read_file(conf->get_ca_certificate_file()), conf->get_ca_name(), true, + 30); + + } catch (const std::exception& e) { + SPDLOG_CRITICAL("fail to parse input params: {}", e.what()); + return -1; + } + + try { + g_io_context->run(); + } catch (const std::exception& e) { + SPDLOG_LOGGER_CRITICAL(g_logger, "unhandled exception: {}", e.what()); + return -1; + } + + SPDLOG_LOGGER_INFO(g_logger, "centreon-monitoring-agent end"); + + return 0; +} \ No newline at end of file diff --git a/agent/test/CMakeLists.txt b/agent/test/CMakeLists.txt new file mode 100644 index 00000000000..c66ffde4ece --- /dev/null +++ b/agent/test/CMakeLists.txt @@ -0,0 +1,58 @@ +# +# Copyright 2024 Centreon +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may not +# use this file except in compliance with the License. You may obtain a copy of +# the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations under +# the License. +# +# For more information : contact@centreon.com +# + + + +add_executable(ut_agent + config_test.cc + test_main.cc + ${TESTS_SOURCES}) + +add_test(NAME tests COMMAND ut_agent) + +set_target_properties( + ut_agent + PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/tests + RUNTIME_OUTPUT_DIRECTORY_DEBUG ${CMAKE_BINARY_DIR}/tests + RUNTIME_OUTPUT_DIRECTORY_RELEASE ${CMAKE_BINARY_DIR}/tests + RUNTIME_OUTPUT_DIRECTORY_RELWITHDEBINFO ${CMAKE_BINARY_DIR}/tests + RUNTIME_OUTPUT_DIRECTORY_MINSIZEREL ${CMAKE_BINARY_DIR}/tests) + + +target_link_libraries(ut_agent PRIVATE + centagent_lib + centreon_common + GTest::gtest + GTest::gtest_main + GTest::gmock + GTest::gmock_main + -L${Boost_LIBRARY_DIR_RELEASE} + boost_program_options + stdc++fs + -L${PROTOBUF_LIB_DIR} + gRPC::gpr gRPC::grpc gRPC::grpc++ gRPC::grpc++_alts + fmt::fmt pthread + crypto ssl + ) + +add_dependencies(ut_agent centreon_common centagent_lib) + +set_property(TARGET ut_agent PROPERTY POSITION_INDEPENDENT_CODE ON) + +target_precompile_headers(ut_agent PRIVATE ${PROJECT_SOURCE_DIR}/precomp_inc/precomp.hh) + diff --git a/agent/test/config_test.cc b/agent/test/config_test.cc new file mode 100644 index 00000000000..6ebba2835e2 --- /dev/null +++ b/agent/test/config_test.cc @@ -0,0 +1,67 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#include +#include + +#include "config.hh" + +using namespace com::centreon::agent; + +static const std::string _json_config_path = + std::filesystem::temp_directory_path() / "config_test.json"; + +TEST(config, bad_format) { + ::remove(_json_config_path.c_str()); + std::ofstream f(_json_config_path); + f << "g,lezjrgerg"; + f.close(); + ASSERT_THROW(config conf(_json_config_path), std::exception); +} + +TEST(config, no_endpoint) { + ::remove(_json_config_path.c_str()); + std::ofstream f(_json_config_path); + f << R"({"encryption":false})"; + f.close(); + ASSERT_THROW(config conf(_json_config_path), std::exception); +} + +TEST(config, bad_endpoint) { + ::remove(_json_config_path.c_str()); + std::ofstream f(_json_config_path); + f << R"({"endpoint":"taratata"})"; + f.close(); + ASSERT_THROW(config conf(_json_config_path), std::exception); +} + +TEST(config, good_endpoint) { + ::remove(_json_config_path.c_str()); + std::ofstream f(_json_config_path); + f << R"({"endpoint":"host1.domain2:4317"})"; + f.close(); + ASSERT_NO_THROW(config conf(_json_config_path)); +} + +TEST(config, bad_log_level) { + ::remove(_json_config_path.c_str()); + std::ofstream f(_json_config_path); + f << R"({"endpoint":"host1.domain2:4317","log_level":"erergeg"})"; + f.close(); + ASSERT_THROW(config conf(_json_config_path), std::exception); +} diff --git a/agent/test/test_main.cc b/agent/test/test_main.cc new file mode 100644 index 00000000000..919a087af50 --- /dev/null +++ b/agent/test/test_main.cc @@ -0,0 +1,59 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#include + +std::shared_ptr g_io_context( + std::make_shared()); + +class CentreonEngineEnvironment : public testing::Environment { + public: + void SetUp() override { + setenv("TZ", ":Europe/Paris", 1); + return; + } + + void TearDown() override { return; } +}; + +/** + * Tester entry point. + * + * @param[in] argc Argument count. + * @param[in] argv Argument values. + * + * @return 0 on success, any other value on failure. + */ +int main(int argc, char* argv[]) { + // GTest initialization. + testing::InitGoogleTest(&argc, argv); + + spdlog::default_logger()->set_level(spdlog::level::trace); + + // Set specific environment. + testing::AddGlobalTestEnvironment(new CentreonEngineEnvironment()); + + auto worker{asio::make_work_guard(*g_io_context)}; + std::thread asio_thread([]() { g_io_context->run(); }); + // Run all tests. + int ret = RUN_ALL_TESTS(); + g_io_context->stop(); + asio_thread.join(); + spdlog::shutdown(); + return ret; +} diff --git a/clib/inc/com/centreon/process.hh b/clib/inc/com/centreon/process.hh index 475aef8e7ac..9948208a690 100644 --- a/clib/inc/com/centreon/process.hh +++ b/clib/inc/com/centreon/process.hh @@ -105,7 +105,7 @@ class process { bool in_stream = true, bool out_stream = true, bool err_stream = true); - virtual ~process() noexcept; + virtual ~process(); process(const process&) = delete; process& operator=(const process&) = delete; // void enable_stream(stream s, bool enable); @@ -129,6 +129,6 @@ class process { void set_timeout(bool timeout); }; -} +} // namespace com::centreon #endif // !CC_PROCESS_POSIX_HH diff --git a/clib/src/process.cc b/clib/src/process.cc index d5ef993b9bd..cf0475c5b67 100644 --- a/clib/src/process.cc +++ b/clib/src/process.cc @@ -63,7 +63,7 @@ process::process(process_listener* listener, /** * Destructor. */ -process::~process() noexcept { +process::~process() { std::unique_lock lock(_lock_process); _kill(SIGKILL); _cv_process_running.wait(lock, [this] { return !_is_running(); }); diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt index 8d06a60276e..0f67c0116e9 100644 --- a/common/CMakeLists.txt +++ b/common/CMakeLists.txt @@ -23,7 +23,8 @@ add_subdirectory(log_v2) # Set directories. set(INCLUDE_DIR "${PROJECT_SOURCE_DIR}/inc/com/centreon/common") -set (HTTP_INCLUDE_DIR "${PROJECT_SOURCE_DIR}/http/inc/com/centreon/common/http") +set(PROCESS_INCLUDE_DIR "${PROJECT_SOURCE_DIR}/process") +set(HTTP_INCLUDE_DIR "${PROJECT_SOURCE_DIR}/http/inc/com/centreon/common/http") set(SRC_DIR "${PROJECT_SOURCE_DIR}/src") set(TEST_DIR "${PROJECT_SOURCE_DIR}/tests") @@ -47,7 +48,6 @@ set(SOURCES ${SRC_DIR}/hex_dump.cc ${SRC_DIR}/perfdata.cc ${SRC_DIR}/pool.cc - ${SRC_DIR}/process.cc ${SRC_DIR}/process_stat.cc ${SRC_DIR}/process_stat.pb.cc ${SRC_DIR}/process_stat.grpc.pb.cc @@ -58,6 +58,7 @@ set(SOURCES include_directories("${INCLUDE_DIR}" ${HTTP_INCLUDE_DIR} ${VCPKG_INCLUDE_DIR} + ${PROCESS_INCLUDE_DIR} ) add_definitions(-DSPDLOG_ACTIVE_LEVEL=SPDLOG_LEVEL_TRACE) @@ -69,6 +70,7 @@ target_precompile_headers(centreon_common PRIVATE precomp_inc/precomp.hh) add_subdirectory(http) add_subdirectory(grpc) +add_subdirectory(process) if(WITH_TESTING) add_subdirectory(tests) diff --git a/common/inc/com/centreon/common/process.hh b/common/inc/com/centreon/common/process.hh index 74562bfc18b..caca6a1dbc9 100644 --- a/common/inc/com/centreon/common/process.hh +++ b/common/inc/com/centreon/common/process.hh @@ -38,9 +38,6 @@ struct boost_process; * locked */ class process : public std::enable_shared_from_this { - std::shared_ptr _io_context; - std::shared_ptr _logger; - std::string _exe_path; std::vector _args; @@ -62,6 +59,9 @@ class process : public std::enable_shared_from_this { void stderr_read(); protected: + std::shared_ptr _io_context; + std::shared_ptr _logger; + char _stdout_read_buffer[0x1000] ABSL_GUARDED_BY(_protect); char _stderr_read_buffer[0x1000] ABSL_GUARDED_BY(_protect); @@ -132,10 +132,10 @@ process::process(const std::shared_ptr& io_context, const std::string_view& exe_path, string_iterator arg_begin, string_iterator arg_end) - : _io_context(io_context), - _logger(logger), - _exe_path(exe_path), - _args(arg_begin, arg_end) {} + : _exe_path(exe_path), + _args(arg_begin, arg_end), + _io_context(io_context), + _logger(logger) {} /** * @brief Construct a new process::process object @@ -151,10 +151,10 @@ process::process(const std::shared_ptr& io_context, const std::shared_ptr& logger, const std::string_view& exe_path, const args_container& args) - : _io_context(io_context), - _logger(logger), - _exe_path(exe_path), - _args(args) {} + : _exe_path(exe_path), + _args(args), + _io_context(io_context), + _logger(logger) {} /** * @brief Construct a new process::process object @@ -171,7 +171,7 @@ process::process(const std::shared_ptr& io_context, const std::shared_ptr& logger, const std::string_view& exe_path, const std::initializer_list& args) - : _io_context(io_context), _logger(logger), _exe_path(exe_path) { + : _exe_path(exe_path), _io_context(io_context), _logger(logger) { _args.reserve(args.size()); for (const auto& str : args) { _args.emplace_back(str); diff --git a/common/process/CMakeLists.txt b/common/process/CMakeLists.txt new file mode 100644 index 00000000000..cf33af66177 --- /dev/null +++ b/common/process/CMakeLists.txt @@ -0,0 +1,30 @@ +# +# Copyright 2024 Centreon +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may not +# use this file except in compliance with the License. You may obtain a copy of +# the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations under +# the License. +# +# For more information : contact@centreon.com +# + +include_directories(${CMAKE_CURRENT_SOURCE_DIR}) +add_definitions(-DSPDLOG_ACTIVE_LEVEL=SPDLOG_LEVEL_TRACE) +add_definitions(${spdlog_DEFINITIONS}) + +add_library( + centreon_process STATIC + # Sources. + process.cc) + +target_precompile_headers(centreon_process REUSE_FROM centreon_common) + +set_property(TARGET centreon_process PROPERTY POSITION_INDEPENDENT_CODE ON) diff --git a/common/src/process.cc b/common/process/process.cc similarity index 98% rename from common/src/process.cc rename to common/process/process.cc index c66e1cbcc21..9e0282b38fb 100644 --- a/common/src/process.cc +++ b/common/process/process.cc @@ -19,6 +19,7 @@ #include #include +#include #include "process.hh" @@ -63,8 +64,7 @@ process::process(const std::shared_ptr& io_context, const std::shared_ptr& logger, const std::string_view& cmd_line) : _io_context(io_context), _logger(logger) { - auto split_res = - absl::StrSplit(cmd_line, absl::ByAnyChar(" \t"), absl::SkipEmpty()); + auto split_res = boost::program_options::split_unix(std::string(cmd_line)); if (split_res.begin() == split_res.end()) { SPDLOG_LOGGER_ERROR(_logger, "empty command line:\"{}\"", cmd_line); throw exceptions::msg_fmt("empty command line:\"{}\"", cmd_line); diff --git a/common/tests/CMakeLists.txt b/common/tests/CMakeLists.txt index 1bd982a7743..fd673759850 100644 --- a/common/tests/CMakeLists.txt +++ b/common/tests/CMakeLists.txt @@ -50,6 +50,9 @@ target_link_libraries( ut_common PRIVATE centreon_common centreon_http + centreon_process + -L${Boost_LIBRARY_DIR_RELEASE} + boost_program_options re2::re2 log_v2 crypto diff --git a/packaging/centreon-engine-daemon.yaml b/packaging/centreon-engine-daemon.yaml index 71c82f8ac0c..74573db05e8 100644 --- a/packaging/centreon-engine-daemon.yaml +++ b/packaging/centreon-engine-daemon.yaml @@ -114,11 +114,6 @@ contents: owner: centreon-engine group: centreon-engine - - src: "/usr/lib/nagios/plugins" - dst: "/usr/lib64/nagios/plugins" - type: symlink - packager: deb - scripts: preinstall: ./scripts/centreon-engine-daemon-preinstall.sh postinstall: ./scripts/centreon-engine-daemon-postinstall.sh diff --git a/packaging/centreon-monitoring-agent-debuginfo.yaml b/packaging/centreon-monitoring-agent-debuginfo.yaml new file mode 100644 index 00000000000..5aa14410670 --- /dev/null +++ b/packaging/centreon-monitoring-agent-debuginfo.yaml @@ -0,0 +1,42 @@ +name: "centreon-monitoring-agent-debuginfo" +arch: "${ARCH}" +platform: "linux" +version_schema: "none" +version: "${VERSION}" +release: "${RELEASE}${DIST}" +section: "default" +priority: "optional" +maintainer: "Centreon " +description: | + Debuginfo package for centagent. + Commit: @COMMIT_HASH@ +vendor: "Centreon" +homepage: "https://www.centreon.com" +license: "Apache-2.0" + +contents: + - src: "../build/agent/centagent.debug" + dst: "/usr/lib/debug/usr/bin/centagent.debug" + file_info: + mode: 0644 + +overrides: + rpm: + depends: + - centreon-monitoring-agent = ${VERSION}-${RELEASE}${DIST} + deb: + depends: + - centreon-monitoring-agent (= ${VERSION}-${RELEASE}${DIST}) + conflicts: + - centreon-monitoring-agent-dbgsym + replaces: + - centreon-monitoring-agent-dbgsym + provides: + - centreon-monitoring-agent-dbgsym + +rpm: + summary: Debuginfo package for centagent. + compression: zstd + signature: + key_file: ${RPM_SIGNING_KEY_FILE} + key_id: ${RPM_SIGNING_KEY_ID} diff --git a/packaging/centreon-monitoring-agent-selinux.yaml b/packaging/centreon-monitoring-agent-selinux.yaml new file mode 100644 index 00000000000..46ad02ae3ec --- /dev/null +++ b/packaging/centreon-monitoring-agent-selinux.yaml @@ -0,0 +1,40 @@ +name: "centreon-monitoring-agent-selinux" +arch: "${ARCH}" +platform: "linux" +version_schema: "none" +version: "${VERSION}" +release: "${RELEASE}${DIST}" +section: "default" +priority: "optional" +maintainer: "Centreon " +description: | + SELinux context for centreon-monitoring-agent +vendor: "Centreon" +homepage: "https://centreon.com" +license: "Apache-2.0" + +depends: + - policycoreutils + - centreon-common-selinux +replaces: + - centreon-monitoring-agent-selinux-debuginfo +conflicts: + - centreon-monitoring-agent-selinux-debuginfo +provides: + - centreon-monitoring-agent-selinux-debuginfo + +contents: + - src: "../selinux/centreon-monitoring-agent/centreon-monitoring-agent.pp" + dst: "/usr/share/selinux/packages/centreon/centreon-monitoring-agent.pp" + file_info: + mode: 0655 + +scripts: + postinstall: ./scripts/centreon-monitoring-agent-selinux-postinstall.sh + preremove: ./scripts/centreon-monitoring-agent-selinux-preremove.sh + +rpm: + summary: SELinux context for centreon-monitoring-agent + signature: + key_file: ${RPM_SIGNING_KEY_FILE} + key_id: ${RPM_SIGNING_KEY_ID} diff --git a/packaging/centreon-monitoring-agent.yaml b/packaging/centreon-monitoring-agent.yaml new file mode 100644 index 00000000000..83bba81f424 --- /dev/null +++ b/packaging/centreon-monitoring-agent.yaml @@ -0,0 +1,66 @@ +name: "centreon-monitoring-agent" +arch: "${ARCH}" +platform: "linux" +version_schema: "none" +version: "${VERSION}" +release: "${RELEASE}${DIST}" +section: "default" +priority: "optional" +maintainer: "Centreon " +description: | + This software is an agent used to execute commands on remote computers as nsclient does. + Commit: @COMMIT_HASH@ +vendor: "Centreon" +homepage: "https://www.centreon.com" +license: "Apache-2.0" + +contents: + - src: "../agent/conf/centagent.json" + dst: "/etc/centreon-monitoring-agent/centagent.json" + type: config|noreplace + file_info: + mode: 0664 + owner: centreon-monitoring-agent + group: centreon-monitoring-agent + + - src: "../agent/scripts/centagent.service" + dst: "/usr/lib/systemd/system/centagent.service" + file_info: + mode: 0644 + packager: rpm + - src: "../agent/scripts/centagent.service" + dst: "/lib/systemd/system/centagent.service" + file_info: + mode: 0644 + packager: deb + + - src: "../build/agent/centagent" + dst: "/usr/bin/centagent" + + - dst: "/etc/centreon-monitoring-agent" + type: dir + file_info: + mode: 0775 + owner: centreon-monitoring-agent + group: centreon-monitoring-agent + + - dst: "/var/log/centreon-monitoring-agent" + type: dir + file_info: + mode: 0755 + owner: centreon-monitoring-agent + group: centreon-monitoring-agent + +scripts: + preinstall: ./scripts/centreon-monitoring-agent-preinstall.sh + postinstall: ./scripts/centreon-monitoring-agent-postinstall.sh + preremove: ./scripts/centreon-monitoring-agent-preremove.sh + postremove: ./scripts/centreon-monitoring-agent-postremove.sh + + +rpm: + summary: Centreon Collect Agent. It can be used to execute plugins remotely + compression: zstd + signature: + key_file: ${RPM_SIGNING_KEY_FILE} + key_id: ${RPM_SIGNING_KEY_ID} diff --git a/packaging/scripts/centreon-engine-daemon-postinstall.sh b/packaging/scripts/centreon-engine-daemon-postinstall.sh index b3b6460a278..32c3991fcd3 100644 --- a/packaging/scripts/centreon-engine-daemon-postinstall.sh +++ b/packaging/scripts/centreon-engine-daemon-postinstall.sh @@ -8,6 +8,16 @@ startCentengine() { systemctl restart centengine.service ||: } +debianLinkNagios() { + if [ ! -r /usr/lib64/nagios/plugins ]; then + if [ ! -d /usr/lib64/nagios ]; then + mkdir -p /usr/lib64/nagios + chmod 0755 /usr/lib64/nagios + fi + ln -s /usr/lib/nagios/plugins /usr/lib64/nagios/plugins + fi +} + # on debian, it is needed to recreate centreon-engine user at each upgrade because it is removed on postrm step on versions < 23.10 if [ "$1" = "configure" ] ; then if [ ! "$(getent passwd centreon-engine)" ]; then @@ -45,6 +55,13 @@ elif [ "$1" = "configure" ] && [ -n "$2" ]; then action="upgrade" fi +#In debian nagios plugins are stored in /usr/lib/nagios/plugins instead of /usr/lib64/nagios/plugins +#so we create a link /usr/lib/nagios/plugins instead => /usr/lib64/nagios/plugins in order to have +#the same commands configuration for all pollers +if [ "$1" = "configure" ]; then + debianLinkNagios +fi + case "$action" in "1" | "install") startCentengine diff --git a/packaging/scripts/centreon-monitoring-agent-postinstall.sh b/packaging/scripts/centreon-monitoring-agent-postinstall.sh new file mode 100644 index 00000000000..0a9fb6ce0e4 --- /dev/null +++ b/packaging/scripts/centreon-monitoring-agent-postinstall.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +startCentagent() { + systemctl daemon-reload ||: + systemctl unmask centagent.service ||: + systemctl preset centagent.service ||: + systemctl enable centagent.service ||: + systemctl restart centagent.service ||: +} + + +debianLinkNagios() { + if [ ! -r /usr/lib64/nagios/plugins ]; then + if [ ! -d /usr/lib64/nagios ]; then + mkdir -p /usr/lib64/nagios + chmod 0755 /usr/lib64/nagios + fi + ln -s /usr/lib/nagios/plugins /usr/lib64/nagios/plugins + fi +} + +#In debian nagios plugins are stored in /usr/lib/nagios/plugins instead of /usr/lib64/nagios/plugins +#so we create a link /usr/lib/nagios/plugins instead => /usr/lib64/nagios/plugins in order to have +#the same commands configuration for all pollers +if [ "$1" = "configure" ]; then + debianLinkNagios +fi + + +startCentagent + diff --git a/packaging/scripts/centreon-monitoring-agent-postremove.sh b/packaging/scripts/centreon-monitoring-agent-postremove.sh new file mode 100644 index 00000000000..28bd8ec8c39 --- /dev/null +++ b/packaging/scripts/centreon-monitoring-agent-postremove.sh @@ -0,0 +1,8 @@ +#!/bin/sh + +case "$1" in + purge) + deluser centreon-monitoring-agent || : + delgroup centreon-monitoring-agent || : + ;; +esac diff --git a/packaging/scripts/centreon-monitoring-agent-preinstall.sh b/packaging/scripts/centreon-monitoring-agent-preinstall.sh new file mode 100644 index 00000000000..ac991e2ea58 --- /dev/null +++ b/packaging/scripts/centreon-monitoring-agent-preinstall.sh @@ -0,0 +1,10 @@ +#!/bin/sh + +if ! id centreon-monitoring-agent > /dev/null 2>&1; then + useradd -r centreon-monitoring-agent > /dev/null 2>&1 +fi + +if id -g nagios > /dev/null 2>&1; then + usermod -a -G centreon-monitoring-agent nagios +fi + diff --git a/packaging/scripts/centreon-monitoring-agent-preremove.sh b/packaging/scripts/centreon-monitoring-agent-preremove.sh new file mode 100644 index 00000000000..e156b0c586e --- /dev/null +++ b/packaging/scripts/centreon-monitoring-agent-preremove.sh @@ -0,0 +1,3 @@ +#!/bin/sh + +systemctl stop centagent.service ||: diff --git a/packaging/scripts/centreon-monitoring-agent-selinux-postinstall.sh b/packaging/scripts/centreon-monitoring-agent-selinux-postinstall.sh new file mode 100644 index 00000000000..0c48460d63c --- /dev/null +++ b/packaging/scripts/centreon-monitoring-agent-selinux-postinstall.sh @@ -0,0 +1,25 @@ +#!/bin/sh + +install() { + semodule -i /usr/share/selinux/packages/centreon/centreon-monitoring-agent.pp > /dev/null 2>&1 || : +} + +upgrade() { + semodule -i /usr/share/selinux/packages/centreon/centreon-monitoring-agent.pp > /dev/null 2>&1 || : +} + +action="$1" +if [ "$1" = "configure" ] && [ -z "$2" ]; then + action="install" +elif [ "$1" = "configure" ] && [ -n "$2" ]; then + action="upgrade" +fi + +case "$action" in + "1" | "install") + install + ;; + "2" | "upgrade") + upgrade + ;; +esac diff --git a/packaging/scripts/centreon-monitoring-agent-selinux-preremove.sh b/packaging/scripts/centreon-monitoring-agent-selinux-preremove.sh new file mode 100644 index 00000000000..aa557d9b61b --- /dev/null +++ b/packaging/scripts/centreon-monitoring-agent-selinux-preremove.sh @@ -0,0 +1,5 @@ +#!/bin/sh + +if [ "$1" -lt "1" ]; then # Final removal + semodule -r centreon-monitoring-agent > /dev/null 2>&1 || : +fi diff --git a/selinux/centreon-monitoring-agent/centreon-monitoring-agent.fc b/selinux/centreon-monitoring-agent/centreon-monitoring-agent.fc new file mode 100644 index 00000000000..7b127e8eb07 --- /dev/null +++ b/selinux/centreon-monitoring-agent/centreon-monitoring-agent.fc @@ -0,0 +1 @@ +/usr/bin/centagent -- gen_context(system_u:object_r:centreon_agent_exec_t,s0) diff --git a/selinux/centreon-monitoring-agent/centreon-monitoring-agent.if b/selinux/centreon-monitoring-agent/centreon-monitoring-agent.if new file mode 100644 index 00000000000..fbeed8af430 --- /dev/null +++ b/selinux/centreon-monitoring-agent/centreon-monitoring-agent.if @@ -0,0 +1 @@ +##

Centreon Agent monitoring agent. diff --git a/selinux/centreon-monitoring-agent/centreon-monitoring-agent.te b/selinux/centreon-monitoring-agent/centreon-monitoring-agent.te new file mode 100644 index 00000000000..205297ed7af --- /dev/null +++ b/selinux/centreon-monitoring-agent/centreon-monitoring-agent.te @@ -0,0 +1,170 @@ +policy_module(centreon-monitoring-agent, @VERSION@) + +######################################## +# +# Declarations +# +require { + type centreon_agent_t; + type centreon_etc_t; + type unconfined_t; + type unconfined_service_t; + type setroubleshootd_t; + type init_t; + type kernel_t; + type fs_t; + type bin_t; + type tmp_t; + type node_t; + type httpd_t; + type ld_so_cache_t; + type ldconfig_exec_t; + type sysfs_t; + type sysctl_net_t; + type var_log_t; + type var_lib_t; + type cert_t; + type nagios_unconfined_plugin_exec_t; + type snmpd_var_lib_t; + type mysqld_db_t; + type ssh_exec_t; + type ssh_home_t; + type setfiles_t; + type unconfined_domain_type; +} + +type centreon_agent_t; +type centreon_agent_exec_t; +init_daemon_domain(centreon_agent_t, centreon_agent_exec_t) + +######################################## +# +# Centreon local policy +# + +allow centreon_agent_t self:process { setpgid signal_perms execmem }; +allow centreon_agent_t self:fifo_file { read open getattr ioctl write rw_fifo_file_perms }; +allow centreon_agent_t self:tcp_socket { create accept listen bind setopt getopt getattr shutdown }; +allow centreon_agent_t self:udp_socket { create accept listen bind setopt getopt getattr }; +allow centreon_agent_t self:file { create read open write getattr read_file_perms relabelto unlink rename }; +allow centreon_agent_t self:dir { add_name write remove_name }; +allow centreon_agent_t self:capability { setuid net_raw }; +allow centreon_agent_t self:rawip_socket { create read write setopt }; +allow centreon_agent_t fs_t:filesystem associate; +allow centreon_agent_t ld_so_cache_t:file execute; +allow centreon_agent_t bin_t:file { execute execute_no_trans }; +allow centreon_agent_t sysfs_t:dir read; +allow centreon_agent_t sysctl_net_t:dir search; +allow centreon_agent_t sysctl_net_t:file { open read getattr }; +allow centreon_agent_t cert_t:dir search; +allow centreon_agent_t node_t:tcp_socket node_bind; +allow centreon_agent_t nagios_unconfined_plugin_exec_t:file { open read execute execute_no_trans }; +allow centreon_agent_t var_log_t:dir { write add_name remove_name }; +allow centreon_agent_t var_log_t:file { create open write read setattr unlink }; +allow centreon_agent_t snmpd_var_lib_t:dir { open read getattr search }; +allow centreon_agent_t snmpd_var_lib_t:file { open read getattr }; +allow centreon_agent_t centreon_agent_t:dir search; +allow centreon_agent_t centreon_agent_t:fifo_file { open read getattr ioctl }; +allow centreon_agent_t ldconfig_exec_t:file { open execute getattr ioctl read}; +allow centreon_agent_t tmp_t:dir { add_name search getattr setattr write unlink create open read remove_name rmdir }; +allow centreon_agent_t tmp_t:file { getattr setattr write unlink create open read }; +allow centreon_agent_t centreon_etc_t:dir { add_name search getattr setattr write unlink create open read remove_name rmdir }; +allow centreon_agent_t ssh_exec_t:file { create read open write getattr setattr read_file_perms relabelto unlink rename ioctl }; +allow centreon_agent_t ssh_home_t:dir { add_name search getattr setattr write unlink create open read remove_name rmdir }; +allow centreon_agent_t ssh_home_t:file { create read open write getattr setattr read_file_perms relabelto unlink rename ioctl }; + +#============= setroubleshootd_t ============== +allow setroubleshootd_t centreon_agent_t:file getattr; +allow setroubleshootd_t centreon_agent_t:dir { search getattr }; +allow setroubleshootd_t centreon_agent_t:fifo_file getattr; + +#============= unconfined_t ============== +allow unconfined_t centreon_agent_t:dir { getattr setattr search relabelto relabelfrom create write add_name }; +allow unconfined_t centreon_agent_t:file { create read open write getattr setattr read_file_perms relabelto unlink rename ioctl }; +allow unconfined_t centreon_agent_t:fifo_file { read open getattr ioctl write setattr }; + +#============= unconfined_service_t ============== +allow unconfined_service_t centreon_agent_t:fifo_file { open read write getattr ioctl }; +allow unconfined_service_t centreon_agent_t:dir { getattr setattr search relabelto relabelfrom create write add_name remove_name }; +allow unconfined_service_t centreon_agent_t:file { create read open write getattr setattr read_file_perms relabelto unlink rename ioctl }; + +#============= httpd_t ============== +allow httpd_t centreon_agent_t:dir { search getattr }; +allow httpd_t centreon_agent_t:fifo_file { open read write getattr }; +allow httpd_t centreon_agent_t:file { execute execute_no_trans map open read getattr setattr }; +allow httpd_t centreon_agent_exec_t:file { execute execute_no_trans map open read getattr setattr }; + +#============= setfiles_t ============== +allow setfiles_t centreon_agent_t:dir relabelto; +allow setfiles_t centreon_agent_t:fifo_file relabelto; +allow setfiles_t centreon_agent_t:file relabelto; + +#============= init_t ============== +allow init_t centreon_agent_t:dir { add_name open read remove_name write search }; +allow init_t centreon_agent_t:fifo_file { create open read write getattr unlink }; +allow init_t centreon_agent_t:file { create execute execute_no_trans getattr map open read unlink write rename }; + +#============= kernel_t ============== +allow kernel_t centreon_agent_t:dir { add_name open read remove_name write search }; +allow kernel_t centreon_agent_t:fifo_file { create open read write getattr unlink }; +allow kernel_t centreon_agent_t:file { create execute execute_no_trans getattr map open read unlink write rename }; + +#============= cluster =============== +allow daemon initrc_transition_domain:fifo_file { ioctl read write getattr lock append }; +allow centreon_agent_t domain:lnk_file { read getattr }; +allow centreon_agent_t domain:dir { ioctl read getattr lock search open }; +allow domain unconfined_domain_type:association recvfrom; +allow domain domain:key { search link }; +allow domain unconfined_domain_type:tcp_socket recvfrom; +allow centreon_agent_t domain:file { ioctl read getattr lock open }; +allow daemon initrc_domain:fd use; +allow daemon initrc_domain:process sigchld; +allow domain unconfined_domain_type:peer recv; +allow daemon initrc_transition_domain:fd use; +allow daemon initrc_domain:fifo_file { ioctl read write getattr lock append }; + +kernel_read_kernel_sysctls(centreon_agent_t) +kernel_read_net_sysctls(centreon_agent_t) +kernel_read_network_state(centreon_agent_t) +kernel_read_system_state(centreon_agent_t) +kernel_request_load_module(centreon_agent_t) + +corecmd_exec_bin(centreon_agent_t) +corecmd_exec_shell(centreon_agent_t) + +corenet_port(centreon_agent_t) +corenet_all_recvfrom_unlabeled(centreon_agent_t) +corenet_all_recvfrom_netlabel(centreon_agent_t) +corenet_tcp_sendrecv_generic_if(centreon_agent_t) +corenet_udp_sendrecv_generic_if(centreon_agent_t) +corenet_tcp_sendrecv_generic_node(centreon_agent_t) +corenet_udp_sendrecv_generic_node(centreon_agent_t) +corenet_tcp_bind_generic_node(centreon_agent_t) +corenet_udp_bind_generic_node(centreon_agent_t) +corenet_sendrecv_all_client_packets(centreon_agent_t) +corenet_tcp_connect_all_ports(centreon_agent_t) +corenet_tcp_sendrecv_all_ports(centreon_agent_t) + +corenet_sendrecv_inetd_child_server_packets(centreon_agent_t) +corenet_tcp_bind_inetd_child_port(centreon_agent_t) +corenet_tcp_sendrecv_inetd_child_port(centreon_agent_t) + +dev_read_sysfs(centreon_agent_t) +dev_read_urand(centreon_agent_t) + +domain_use_interactive_fds(centreon_agent_t) +domain_read_all_domains_state(centreon_agent_t) + +files_read_etc_runtime_files(centreon_agent_t) +files_read_usr_files(centreon_agent_t) + +fs_getattr_all_fs(centreon_agent_t) +fs_search_auto_mountpoints(centreon_agent_t) + +auth_use_nsswitch(centreon_agent_t) + +logging_send_syslog_msg(centreon_agent_t) + +miscfiles_read_localization(centreon_agent_t) + +userdom_dontaudit_use_unpriv_user_fds(centreon_agent_t) From 7f43769aa3cbece233a4548725f0a822b532aaac Mon Sep 17 00:00:00 2001 From: tuntoja <58987095+tuntoja@users.noreply.github.com> Date: Thu, 27 Jun 2024 09:30:58 +0200 Subject: [PATCH 51/60] fix(release): use pcre to get jira_release_id (#1471) --- .github/actions/release/action.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/actions/release/action.yml b/.github/actions/release/action.yml index 74746c3b447..205bc442042 100644 --- a/.github/actions/release/action.yml +++ b/.github/actions/release/action.yml @@ -187,7 +187,7 @@ runs: JIRA_RELEASE_NAME="" JIRA_PROJECT_ID="${{ inputs.jira_project_id }}" JIRA_RELEASE_RELEASED="false" - JIRA_RELEASE_ID="$(git log |grep -E "^\s+Centreon.*#[0-9]{5,}#)" |grep -Eo "([0-9]{5,})" |head -n 1)" + JIRA_RELEASE_ID="$(git log |grep -E "Centreon\ next.*\#[0-9]{5,}\#\)" |grep -o -P "(?<=#)[0-9]{5,}(?=#)" |head -n 1)" # Create JIRA version for each released component echo "Creating JIRA releases." From 08f5b65dd9df0f072a1429580e49a07ec12ba17c Mon Sep 17 00:00:00 2001 From: David Boucher Date: Fri, 28 Jun 2024 13:34:42 +0200 Subject: [PATCH 52/60] enh(engine/configuration): config_warnings and config_errors are removed as global variables * enh(engine/configuration): config_warnings and config_errors are removed as global variables. * cleanup(engine/configuration): headers removed when not needed * enh(collect): copyright info are updated automatically now. * fix(engine/configuration): scheduling configuration is fixed. * fix(engine): errors counts were badly propagated. * enh(engine): daterange/timerange have their configuration objects * fix(engine/configuration): daterange constructor is more robust * fix(tests): better initialization of engine * cleanup(engine/daterange): unused functions removed * cleanup(engine): some methods removed since the new configuration objects * fix(engine/configuration): clear() calls unneeded. * enh(engine): a comment fixed. * fix(engine/configuration): another dependency removed * enh(engine/configuration): a dependency to clib removed REFS: MON-34072 --- engine/CMakeLists.txt | 4 +- engine/inc/com/centreon/engine/broker.hh | 40 +- .../engine/configuration/daterange.hh | 161 +++++++ .../engine/configuration/timeperiod.hh | 13 +- engine/inc/com/centreon/engine/daterange.hh | 9 +- engine/inc/com/centreon/engine/timeperiod.hh | 4 - engine/inc/com/centreon/engine/timerange.hh | 16 +- engine/src/configuration/CMakeLists.txt | 1 + .../src/configuration/applier/timeperiod.cc | 37 +- engine/src/configuration/daterange.cc | 414 ++++++++++++++++++ engine/src/configuration/service.cc | 21 +- engine/src/configuration/state.cc | 34 +- engine/src/configuration/timeperiod.cc | 32 +- engine/src/daterange.cc | 92 ++-- engine/src/timeperiod.cc | 35 -- .../configuration/applier/applier-state.cc | 12 +- engine/tests/configuration/timeperiod-test.cc | 106 ++++- engine/tests/timeperiod/utils.cc | 49 ++- .../services-and-bulk-stmt.robot | 7 +- 19 files changed, 845 insertions(+), 242 deletions(-) create mode 100644 engine/inc/com/centreon/engine/configuration/daterange.hh create mode 100644 engine/src/configuration/daterange.cc diff --git a/engine/CMakeLists.txt b/engine/CMakeLists.txt index 0b9a62ebaaf..053f7b2a0fb 100644 --- a/engine/CMakeLists.txt +++ b/engine/CMakeLists.txt @@ -488,8 +488,8 @@ add_subdirectory(src/macros) add_subdirectory(modules) add_subdirectory(src/retention) add_subdirectory(enginerpc) -include_directories(enginerpc - ${CMAKE_SOURCE_DIR}/common/src +include_directories(enginerpc + ${CMAKE_SOURCE_DIR}/common/src ${CMAKE_SOURCE_DIR}/common/inc) # Library engine target. diff --git a/engine/inc/com/centreon/engine/broker.hh b/engine/inc/com/centreon/engine/broker.hh index 70c1cc7237d..d958522d091 100644 --- a/engine/inc/com/centreon/engine/broker.hh +++ b/engine/inc/com/centreon/engine/broker.hh @@ -1,23 +1,23 @@ -/* -** Copyright 2002-2006 Ethan Galstad -** Copyright 2011-2013 Merethis -** Copyright 2018-2022 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ +/** + * Copyright 2002-2006 Ethan Galstad + * Copyright 2011-2013 Merethis + * Copyright 2018-2024 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #ifndef CCE_BROKER_HH #define CCE_BROKER_HH diff --git a/engine/inc/com/centreon/engine/configuration/daterange.hh b/engine/inc/com/centreon/engine/configuration/daterange.hh new file mode 100644 index 00000000000..2568bfcd505 --- /dev/null +++ b/engine/inc/com/centreon/engine/configuration/daterange.hh @@ -0,0 +1,161 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ +#ifndef CCE_CONFIGURATION_DATERANGE_HH +#define CCE_CONFIGURATION_DATERANGE_HH + +namespace com::centreon::engine::configuration { + +class daterange; + +/** + * @brief The timerange configuration object. It is almost the same as the + * com::centreon::engine::timerange object. But it is needed for the + * configuration library to be Engine independent. + */ +class timerange { + uint64_t _range_start; + uint64_t _range_end; + + public: + timerange(uint64_t range_start, uint64_t range_end) + : _range_start{range_start}, _range_end{range_end} {} + + uint64_t range_start() const { return _range_start; }; + uint64_t range_end() const { return _range_end; }; + bool operator==(const timerange& other) const { + return _range_start == other._range_start && _range_end == other._range_end; + } + bool operator<(const timerange& other) const { + if (_range_start != other._range_start) + return _range_start < other._range_start; + return _range_end < other._range_end; + } +}; + +/** + * @brief The daterange configuration object. It is almost the same as the + * com::centreon::engine::daterange object. But it is needed for the + * configuration library to be Engine independent. + */ +class daterange { + public: + enum type_range { + none = -1, + calendar_date = 0, + month_date = 1, + month_day = 2, + month_week_day = 3, + week_day = 4, + daterange_types = 5, + }; + + private: + type_range _type; + /* Start year. */ + int32_t _syear; + + /* Start month. */ + int32_t _smon; + + /* Start day of month (may 3rd, last day in feb). */ + int32_t _smday; + + /* Start day of week (thursday).*/ + int32_t _swday; + + /* Start weekday offset (3rd thursday, last monday in jan). */ + int32_t _swday_offset; + + /* End year. */ + int32_t _eyear; + + /* End month. */ + int32_t _emon; + + /* End day of month (may 3rd, last day in feb). */ + int32_t _emday; + + /* End day of week (thursday).*/ + int32_t _ewday; + + /* End weekday offset (3rd thursday, last monday in jan). */ + int32_t _ewday_offset; + + int32_t _skip_interval; + + /* A list of timeranges for this daterange */ + std::list _timerange; + + public: + daterange(type_range type, + int syear, + int smon, + int smday, + int swday, + int swday_offset, + int eyear, + int emon, + int emday, + int ewday, + int ewday_offset, + int skip_interval); + daterange(type_range type); + bool is_date_data_equal(const daterange& range) const; + type_range type() const; + int32_t get_syear() const { return _syear; } + int32_t get_smon() const { return _smon; } + int32_t get_smday() const { return _smday; } + int32_t get_swday() const { return _swday; } + int32_t get_swday_offset() const { return _swday_offset; } + int32_t get_eyear() const { return _eyear; } + int32_t get_emon() const { return _emon; } + int32_t get_emday() const { return _emday; } + int32_t get_ewday() const { return _ewday; } + int32_t get_ewday_offset() const { return _ewday_offset; } + int32_t get_skip_interval() const { return _skip_interval; } + const std::list& get_timerange() const; + + void set_syear(int32_t syear); + void set_smon(int32_t smon); + void set_smday(int32_t smday); + void set_swday(int32_t swday); + void set_swday_offset(int32_t swday_offset); + void set_eyear(int32_t eyear); + void set_emon(int32_t emon); + void set_emday(int32_t emday); + void set_ewday(int32_t ewday); + void set_ewday_offset(int32_t ewday_offset); + void set_skip_interval(int32_t skip_interval); + void set_timerange(const std::list& timerange); + + bool operator==(const daterange& other) const; + bool operator<(const daterange& other) const; +}; + +std::ostream& operator<<(std::ostream& os, const timerange& obj); + +std::ostream& operator<<(std::ostream& os, const std::list& obj); + +std::ostream& operator<<( + std::ostream& os, + const std::array, daterange::daterange_types>& obj); + +} // namespace com::centreon::engine::configuration + +#endif /* !CCE_CONFIGURATION_DATERANGE_HH */ diff --git a/engine/inc/com/centreon/engine/configuration/timeperiod.hh b/engine/inc/com/centreon/engine/configuration/timeperiod.hh index b179a71d113..dc2486e41d6 100644 --- a/engine/inc/com/centreon/engine/configuration/timeperiod.hh +++ b/engine/inc/com/centreon/engine/configuration/timeperiod.hh @@ -20,9 +20,9 @@ #define CCE_CONFIGURATION_TIMEPERIOD_HH #include "com/centreon/common/opt.hh" +#include "com/centreon/engine/configuration/daterange.hh" #include "com/centreon/engine/configuration/group.hh" #include "com/centreon/engine/configuration/object.hh" -#include "com/centreon/engine/daterange.hh" namespace com::centreon::engine { @@ -48,10 +48,11 @@ class timeperiod : public object { bool parse(std::string const& line) override; std::string const& alias() const throw(); - exception_array const& exceptions() const throw(); + std::array, daterange::daterange_types> const& + exceptions() const noexcept; set_string const& exclude() const throw(); std::string const& timeperiod_name() const throw(); - days_array const& timeranges() const; + const std::array, 7>& timeranges() const; friend test::time_period_comparator; @@ -62,7 +63,7 @@ class timeperiod : public object { bool _add_other_date(std::string const& line); bool _add_week_day(std::string const& key, std::string const& value); static bool _build_timeranges(std::string const& line, - timerange_list& timeranges); + std::list& timeranges); static bool _build_time_t(std::string_view time_str, unsigned long& ret); static bool _has_similar_daterange(std::list const& lst, daterange const& range) throw(); @@ -74,10 +75,10 @@ class timeperiod : public object { std::string _alias; static std::unordered_map const _setters; - exception_array _exceptions; + std::array, daterange::daterange_types> _exceptions; group _exclude; std::string _timeperiod_name; - days_array _timeranges; + std::array, 7> _timeranges; }; typedef std::shared_ptr timeperiod_ptr; diff --git a/engine/inc/com/centreon/engine/daterange.hh b/engine/inc/com/centreon/engine/daterange.hh index e5ed8885fdb..6bf2967c507 100644 --- a/engine/inc/com/centreon/engine/daterange.hh +++ b/engine/inc/com/centreon/engine/daterange.hh @@ -56,7 +56,8 @@ class daterange { int emday, int ewday, int ewday_offset, - int skip_interval); + int skip_interval, + const std::list& timeranges); daterange(type_range type); type_range get_type() const { return _type; } @@ -91,8 +92,6 @@ class daterange { bool operator==(daterange const& obj) const; bool operator!=(daterange const& obj2) const; - bool operator<(daterange const& right) const; - bool is_date_data_equal(daterange const& obj) const; static std::string const& get_month_name(unsigned int index); static std::string const& get_weekday_name(unsigned int index); @@ -120,6 +119,6 @@ std::ostream& operator<<(std::ostream& os, std::ostream& operator<<(std::ostream& os, exception_array const& obj); -} +} // namespace com::centreon::engine -#endif // !CCE_OBJECTS_DATERANGE_HH \ No newline at end of file +#endif // !CCE_OBJECTS_DATERANGE_HH diff --git a/engine/inc/com/centreon/engine/timeperiod.hh b/engine/inc/com/centreon/engine/timeperiod.hh index c115709761a..44e24f13061 100644 --- a/engine/inc/com/centreon/engine/timeperiod.hh +++ b/engine/inc/com/centreon/engine/timeperiod.hh @@ -79,8 +79,4 @@ void get_next_valid_time(time_t pref_time, time_t* valid_time, com::centreon::engine::timeperiod* tperiod); -std::ostream& operator<<(std::ostream& os, - com::centreon::engine::timeperiod const& obj); -std::ostream& operator<<(std::ostream& os, timeperiodexclusion const& obj); - #endif // !CCE_OBJECTS_TIMEPERIOD_HH diff --git a/engine/inc/com/centreon/engine/timerange.hh b/engine/inc/com/centreon/engine/timerange.hh index 6638fbf0ac9..3ee0de199af 100644 --- a/engine/inc/com/centreon/engine/timerange.hh +++ b/engine/inc/com/centreon/engine/timerange.hh @@ -19,10 +19,13 @@ #ifndef CCE_OBJECTS_TIMERANGE_HH #define CCE_OBJECTS_TIMERANGE_HH - +#include "com/centreon/engine/configuration/daterange.hh" namespace com::centreon::engine { class timerange { + uint64_t _range_start; + uint64_t _range_end; + public: timerange(uint64_t start, uint64_t end); uint64_t get_range_start() const { return _range_start; }; @@ -35,15 +38,6 @@ class timerange { bool operator!=(timerange const& obj) const { return _range_start != obj._range_start || _range_end != obj._range_end; }; - bool operator<(timerange const& obj) const { - if (_range_start != obj._range_start) - return (_range_start < obj._range_start); - return (_range_end < obj._range_end); - } - - private: - uint64_t _range_start; - uint64_t _range_end; }; using timerange_list = std::list; @@ -53,6 +47,6 @@ std::ostream& operator<<(std::ostream& os, com::centreon::engine::timerange const& obj); std::ostream& operator<<(std::ostream& os, timerange_list const& obj); -} +} // namespace com::centreon::engine #endif // !CCE_OBJECTS_TIMERANGE_HH diff --git a/engine/src/configuration/CMakeLists.txt b/engine/src/configuration/CMakeLists.txt index ff0c4fcd7a0..2f936a13623 100644 --- a/engine/src/configuration/CMakeLists.txt +++ b/engine/src/configuration/CMakeLists.txt @@ -33,6 +33,7 @@ set(FILES "${SRC_DIR}/contact.cc" "${SRC_DIR}/contactgroup.cc" "${SRC_DIR}/customvariable.cc" + "${SRC_DIR}/daterange.cc" "${SRC_DIR}/extended_conf.cc" "${SRC_DIR}/group.cc" "${SRC_DIR}/host.cc" diff --git a/engine/src/configuration/applier/timeperiod.cc b/engine/src/configuration/applier/timeperiod.cc index df738fc3bee..0b4d1a298d7 100644 --- a/engine/src/configuration/applier/timeperiod.cc +++ b/engine/src/configuration/applier/timeperiod.cc @@ -26,7 +26,9 @@ #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" #include "com/centreon/engine/logging/logger.hh" +#include "com/centreon/engine/timeperiod.hh" +using namespace com::centreon::engine; using namespace com::centreon::engine::configuration; /** @@ -55,8 +57,20 @@ void applier::timeperiod::add_object(configuration::timeperiod const& obj) { NEBATTR_NONE, tp.get(), CMD_NONE, &tv); // Fill time period structure. - tp->days = obj.timeranges(); - tp->exceptions = obj.exceptions(); + for (uint32_t i = 0; i < obj.timeranges().size(); i++) { + for (auto& tr : obj.timeranges()[i]) + tp->days[i].push_back({tr.range_start(), tr.range_end()}); + } + for (uint32_t i = 0; i < obj.exceptions().size(); i++) { + for (auto& dr : obj.exceptions()[i]) { + tp->exceptions[i].push_back( + {static_cast(dr.type()), + dr.get_syear(), dr.get_smon(), dr.get_smday(), dr.get_swday(), + dr.get_swday_offset(), dr.get_eyear(), dr.get_emon(), dr.get_emday(), + dr.get_ewday(), dr.get_ewday_offset(), dr.get_skip_interval(), + dr.get_timerange()}); + } + } _add_exclusions(obj.exclude(), tp.get()); } @@ -109,12 +123,27 @@ void applier::timeperiod::modify_object(configuration::timeperiod const& obj) { // Time ranges modified ? if (obj.timeranges() != old_cfg.timeranges()) { - tp->days = obj.timeranges(); + for (uint32_t i = 0; i < tp->days.size(); i++) { + tp->days[i].clear(); + for (auto& tr : obj.timeranges()[i]) + tp->days[i].push_back({tr.range_start(), tr.range_end()}); + } } // Exceptions modified ? if (obj.exceptions() != old_cfg.exceptions()) { - tp->exceptions = obj.exceptions(); + for (uint32_t i = 0; i < obj.exceptions().size(); i++) { + tp->exceptions[i].clear(); + for (auto& dr : obj.exceptions()[i]) { + tp->exceptions[i].push_back( + {static_cast( + dr.type()), + dr.get_syear(), dr.get_smon(), dr.get_smday(), dr.get_swday(), + dr.get_swday_offset(), dr.get_eyear(), dr.get_emon(), + dr.get_emday(), dr.get_ewday(), dr.get_ewday_offset(), + dr.get_skip_interval(), dr.get_timerange()}); + } + } } // Exclusions modified ? diff --git a/engine/src/configuration/daterange.cc b/engine/src/configuration/daterange.cc new file mode 100644 index 00000000000..44d536ad13e --- /dev/null +++ b/engine/src/configuration/daterange.cc @@ -0,0 +1,414 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ +#include "com/centreon/engine/configuration/daterange.hh" + +using namespace com::centreon::engine::configuration; + +/** + * Create a new exception to a timeperiod. + * + * @param[in] period Base period. + * @param[in] type Type of the range (see header file). + * @param[in] syear The start year. + * @param[in] smon The start month. + * @param[in] smday The start day of month (may 3rd, last day in feb). + * @param[in] swday The start day of week (thursday). + * @param[in] swday_offset The start weekday offset (3rd thursday, last monday + * in jan). + * @param[in] eyear The end year. + * @param[in] emon The end month. + * @param[in] emday The end day of month + * @param[in] ewday The end day of week. + * @param[in] ewday_offset The end weekday offset. + * @param[in] skip_interval The interval with the next day. + */ +daterange::daterange(type_range type, + int syear, + int smon, + int smday, + int swday, + int swday_offset, + int eyear, + int emon, + int emday, + int ewday, + int ewday_offset, + int skip_interval) + : _type{type}, + _syear{syear}, + _smon{smon}, + _smday{smday}, + _swday{swday}, + _swday_offset{swday_offset}, + _eyear{eyear}, + _emon{emon}, + _emday{emday}, + _ewday{ewday}, + _ewday_offset{ewday_offset}, + _skip_interval{skip_interval} {} +daterange::type_range daterange::type() const { + return _type; +} + +daterange::daterange(type_range type) + : _type{type}, + _syear{0}, + _smon{0}, + _smday{0}, + _swday{0}, + _swday_offset{0}, + _eyear{0}, + _emon{0}, + _emday{0}, + _ewday{0}, + _ewday_offset{0}, + _skip_interval{0} {} + +/** + * @brief Almost the same as the == operator but here timeranges are not + * compared. + * + * @param obj Only date data are compared. + * + * @return A boolean that is true if they are "similar". + */ +bool daterange::is_date_data_equal(const configuration::daterange& obj) const { + return _type == obj.type() && _syear == obj.get_syear() && + _smon == obj.get_smon() && _smday == obj.get_smday() && + _swday == obj.get_swday() && _swday_offset == obj.get_swday_offset() && + _eyear == obj.get_eyear() && _emon == obj.get_emon() && + _emday == obj.get_emday() && _ewday == obj.get_ewday() && + _ewday_offset == obj.get_ewday_offset() && + _skip_interval == obj.get_skip_interval(); +} + +void daterange::set_syear(int32_t syear) { + _syear = syear; +} + +void daterange::set_smon(int32_t smon) { + _smon = smon; +} + +void daterange::set_smday(int32_t smday) { + _smday = smday; +} + +void daterange::set_swday(int32_t smday) { + _swday = smday; +} + +void daterange::set_swday_offset(int32_t smday_offset) { + _swday_offset = smday_offset; +} + +void daterange::set_eyear(int32_t eyear) { + _eyear = eyear; +} + +void daterange::set_emon(int32_t emon) { + _emon = emon; +} + +void daterange::set_emday(int32_t emday) { + _emday = emday; +} + +void daterange::set_ewday(int32_t ewday) { + _ewday = ewday; +} + +void daterange::set_ewday_offset(int32_t ewday_offset) { + _ewday_offset = ewday_offset; +} + +void daterange::set_skip_interval(int32_t skip_interval) { + _skip_interval = skip_interval; +} + +void daterange::set_timerange( + const std::list& timerange) { + _timerange = timerange; +} + +const std::list& daterange::get_timerange() const { + return _timerange; +} + +/** + * Equal operator. + * + * @param[in] other Object to compare to. + * + * @return True if this object is less than right. + */ +bool daterange::operator==(const daterange& other) const { + return _type == other.type() && _syear == other.get_syear() && + _smon == other._smon && _smday == other._smday && + _swday == other.get_swday() && _swday_offset == other._swday_offset && + _eyear == other._eyear && _emon == other._emon && + _emday == other._emday && _ewday == other._ewday && + _ewday_offset == other._ewday_offset && + _skip_interval == other._skip_interval && + _timerange == other._timerange; +} + +/** + * Less-than operator. + * + * @param[in] other Object to compare to. + * + * @return True if this object is less than right. + */ +bool daterange::operator<(daterange const& other) const { + if (_emon != other._emon) + return _emon < other._emon; + else if (_smon != other._smon) + return _smon < other._smon; + else if (_emday != other._emday) + return _emday < other._emday; + else if (_smday != other._smday) + return _smday < other._smday; + else if (_skip_interval != other._skip_interval) + return _skip_interval < other._skip_interval; + else if (_type != other._type) + return _type < other._type; + else if (_ewday != other._ewday) + return _ewday < other._ewday; + else if (_swday != other._swday) + return _swday < other._swday; + else if (_ewday_offset != other._ewday_offset) + return _ewday_offset < other._ewday_offset; + else if (_swday_offset != other._swday_offset) + return _swday_offset < other._swday_offset; + else if (_eyear != other._eyear) + return _eyear < other._eyear; + else if (_syear != other._syear) + return _syear < other._syear; + return _timerange < other._timerange; +} + +namespace com::centreon::engine::configuration { +/** + * Dump timerange content into the stream. + * + * @param[out] os The output stream. + * @param[in] obj The timerange to dump. + * + * @return The output stream. + */ +std::ostream& operator<<(std::ostream& os, const timerange& obj) { + uint32_t start_hours(obj.range_start() / 3600); + uint32_t start_minutes((obj.range_start() % 3600) / 60); + uint32_t end_hours(obj.range_end() / 3600); + uint32_t end_minutes((obj.range_end() % 3600) / 60); + os << std::setfill('0') << std::setw(2) << start_hours << ":" + << std::setfill('0') << std::setw(2) << start_minutes << "-" + << std::setfill('0') << std::setw(2) << end_hours << ":" + << std::setfill('0') << std::setw(2) << end_minutes; + return os; +} + +/** + * Dump timerange_list content into the stream. + * + * @param[out] os The output stream. + * @param[in] obj The timerange_list to dump. + * + * @return The output stream. + */ +std::ostream& operator<<(std::ostream& os, const std::list& obj) { + for (auto it = obj.begin(), end = obj.end(); it != end; ++it) + os << *it << ((next(it) == obj.end()) ? "" : ", "); + return os; +} + +/** + * Dump the daterange value into the calendar date format. + * + * @param[out] os The output stream. + * @param[in] obj The daterange to dump. + * + * @return The output stream. + */ +static std::ostream& _dump_calendar_date(std::ostream& os, + daterange const& obj) { + os << std::setfill('0') << std::setw(2) << obj.get_syear() << "-" + << std::setfill('0') << std::setw(2) << obj.get_smon() + 1 << "-" + << std::setfill('0') << std::setw(2) << obj.get_smday(); + if (obj.get_syear() != obj.get_eyear() || obj.get_smon() != obj.get_emon() || + obj.get_smday() != obj.get_emday()) + os << " - " << std::setfill('0') << std::setw(2) << obj.get_eyear() << "-" + << std::setfill('0') << std::setw(2) << obj.get_emon() + 1 << "-" + << std::setfill('0') << std::setw(2) << obj.get_emday(); + if (obj.get_skip_interval()) + os << " / " << obj.get_skip_interval(); + return os; +} + +static const std::string_view& month_name(uint32_t index) { + static constexpr std::array month_name{ + "january", "february", "march", "april", "may", "june", + "july", "august", "september", "october", "november", "december"}; + return month_name[index]; +} + +static const std::string_view& weekday_name(uint32_t index) { + static constexpr std::array day_name{ + "sunday", "monday", "tuesday", "wednesday", + "thursday", "friday", "saturday"}; + return day_name[index]; +} + +/** + * Dump the daterange value into the month date format. + * + * @param[out] os The output stream. + * @param[in] obj The daterange to stringify. + * + * @return The output stream. + */ +static std::ostream& _dump_month_date(std::ostream& os, daterange const& obj) { + const std::string_view& smon = month_name(obj.get_smon()); + const std::string_view& emon = month_name(obj.get_emon()); + os << smon << " " << obj.get_smday(); + if (smon != emon) + os << " - " << emon << " " << obj.get_emday(); + else if (obj.get_smday() != obj.get_emday()) + os << " - " << obj.get_emday(); + if (obj.get_skip_interval()) + os << " / " << obj.get_skip_interval(); + return os; +} + +/** + * Dump the daterange value into the month day format. + * + * @param[out] os The output stream. + * @param[in] obj The daterange to stringify. + * + * @return The output stream. + */ +static std::ostream& _dump_month_day(std::ostream& os, daterange const& obj) { + os << "day " << obj.get_smday(); + if (obj.get_smday() != obj.get_emday()) + os << " - " << obj.get_emday(); + if (obj.get_skip_interval()) + os << " / " << obj.get_skip_interval(); + return os; +} + +/** + * Dump the daterange value into the month week day + * format. + * + * @param[out] os The output stream. + * @param[in] obj The daterange to stringify. + * + * @return The output stream. + */ +static std::ostream& _dump_month_week_day(std::ostream& os, + daterange const& obj) { + os << weekday_name(obj.get_swday()) << " " << obj.get_swday_offset() << " " + << month_name(obj.get_smon()); + if (obj.get_swday() != obj.get_ewday() || + obj.get_swday_offset() != obj.get_ewday_offset() || + obj.get_smon() != obj.get_emon()) + os << " - " << weekday_name(obj.get_ewday()) << " " + << obj.get_ewday_offset() << " " << month_name(obj.get_emon()); + if (obj.get_skip_interval()) + os << " / " << obj.get_skip_interval(); + return os; +} + +/** + * Dump the daterange value into the week day format. + * + * @param[out] os The output stream. + * @param[in] obj The daterange to stringify. + * + * @return The output stream. + */ +static std::ostream& _dump_week_day(std::ostream& os, daterange const& obj) { + os << weekday_name(obj.get_swday()) << " " << obj.get_swday_offset(); + if (obj.get_swday() != obj.get_ewday() || + obj.get_swday_offset() != obj.get_ewday_offset()) + os << " - " << weekday_name(obj.get_ewday()) << " " + << obj.get_ewday_offset(); + if (obj.get_skip_interval()) + os << " / " << obj.get_skip_interval(); + return os; +} + +/** + * Dump daterange content into the stream. + * + * @param[out] os The output stream. + * @param[in] obj The daterange to dump. + * + * @return The output stream. + */ +std::ostream& operator<<(std::ostream& os, const daterange& obj) { + typedef std::ostream& (*func)(std::ostream&, daterange const&); + static func tab[] = { + &_dump_calendar_date, &_dump_month_date, &_dump_month_day, + &_dump_month_week_day, &_dump_week_day, + }; + + if (obj.type() < 0 || obj.type() >= daterange::daterange_types) + os << "unknown type " << obj.type(); + else { + (*(tab[obj.type()]))(os, obj); + os << " " << obj.get_timerange(); + } + return os; +} + +std::ostream& operator<<( + std::ostream& os, + const std::array, daterange::daterange_types>& obj) { + os << '{'; + for (unsigned ii = 0; ii < obj.size(); ++ii) { + switch (ii) { + case daterange::calendar_date: + os << "calendar_date:"; + break; + case daterange::month_date: + os << "month_date:"; + break; + case daterange::month_day: + os << "month_day:"; + break; + case daterange::month_week_day: + os << "month_week_day:"; + break; + case daterange::week_day: + os << "week_day:"; + break; + } + for (const daterange& dr : obj[ii]) { + os << '{' << dr << "},"; + } + os << '['; + os << "],"; + } + os << '}'; + return os; +} +} // namespace com::centreon::engine::configuration diff --git a/engine/src/configuration/service.cc b/engine/src/configuration/service.cc index 73efe5d04e7..fe7b0205bd6 100644 --- a/engine/src/configuration/service.cc +++ b/engine/src/configuration/service.cc @@ -21,8 +21,9 @@ #include #include #include -#include "com/centreon/engine/host.hh" +#include "bbdo/bam_state.pb.h" #include "com/centreon/exceptions/msg_fmt.hh" +#include "bbdo/neb.pb.h" using namespace com::centreon; using namespace com::centreon::engine::configuration; @@ -110,7 +111,7 @@ static unsigned short const default_flap_detection_options(service::ok | service::critical); static unsigned int const default_freshness_threshold(0); static unsigned int const default_high_flap_threshold(0); -static unsigned int const default_initial_state(engine::service::state_ok); +static unsigned int const default_initial_state(broker::Service_State_OK); static bool const default_is_volatile(false); static unsigned int const default_low_flap_threshold(0); static unsigned int const default_max_check_attempts(3); @@ -1598,13 +1599,13 @@ bool service::_set_initial_state(std::string const& value) { std::string_view data(value); data = absl::StripAsciiWhitespace(data); if (data == "o" || data == "ok") - _initial_state = engine::service::state_ok; + _initial_state = broker::Service_State_OK; else if (data == "w" || data == "warning") - _initial_state = engine::service::state_warning; + _initial_state = broker::Service_State_WARNING; else if (data == "u" || data == "unknown") - _initial_state = engine::service::state_unknown; + _initial_state = broker::Service_State_UNKNOWN; else if (data == "c" || data == "critical") - _initial_state = engine::service::state_critical; + _initial_state = broker::Service_State_CRITICAL; else return false; return true; @@ -1909,7 +1910,7 @@ bool service::_set_category_tags(const std::string& value) { for (std::set>::iterator it(_tags.begin()), end(_tags.end()); it != end;) { - if (it->second == tag::servicecategory) + if (it->second == broker::TagType::SERVICECATEGORY) it = _tags.erase(it); else ++it; @@ -1920,7 +1921,7 @@ bool service::_set_category_tags(const std::string& value) { bool parse_ok; parse_ok = absl::SimpleAtoi(tag, &id); if (parse_ok) { - _tags.emplace(id, tag::servicecategory); + _tags.emplace(id, broker::TagType::SERVICECATEGORY); } else { _logger->warn("Warning: service ({}, {}) error for parsing tag {}", _host_id, _service_id, value); @@ -1943,7 +1944,7 @@ bool service::_set_group_tags(const std::string& value) { for (std::set>::iterator it(_tags.begin()), end(_tags.end()); it != end;) { - if (it->second == tag::servicegroup) + if (it->second == broker::TagType::SERVICEGROUP) it = _tags.erase(it); else ++it; @@ -1954,7 +1955,7 @@ bool service::_set_group_tags(const std::string& value) { bool parse_ok; parse_ok = absl::SimpleAtoi(tag, &id); if (parse_ok) { - _tags.emplace(id, tag::servicegroup); + _tags.emplace(id, broker::TagType::SERVICEGROUP); } else { _logger->warn("Warning: service ({}, {}) error for parsing tag {}", _host_id, _service_id, value); diff --git a/engine/src/configuration/state.cc b/engine/src/configuration/state.cc index 2ee1415a225..e70b1b18b17 100644 --- a/engine/src/configuration/state.cc +++ b/engine/src/configuration/state.cc @@ -18,9 +18,7 @@ */ #include "com/centreon/engine/configuration/state.hh" #include "com/centreon/common/rapidjson_helper.hh" -#include "com/centreon/engine/broker.hh" #include "com/centreon/exceptions/msg_fmt.hh" -#include "com/centreon/io/file_entry.hh" #include "common/log_v2/log_v2.hh" using namespace com::centreon; @@ -1150,9 +1148,9 @@ void state::broker_module_directory(const std::string& value) { if (value.empty() || value[0] == '/') _broker_module_directory = value; else { - io::file_entry fe(_cfg_main); - std::string base_name(fe.directory_name()); - _broker_module_directory = base_name + "/" + value; + std::filesystem::path fe{_cfg_main}; + std::string base_name(fe.parent_path()); + _broker_module_directory = fmt::format("{}/{}", base_name, value); } } @@ -3562,9 +3560,9 @@ void state::state_retention_file(const std::string& value) { if (value.empty() || value[0] == '/') _state_retention_file = value; else { - io::file_entry fe(_cfg_main); - std::string base_name(fe.directory_name()); - _state_retention_file = base_name + "/" + value; + std::filesystem::path fe{_cfg_main}; + std::string base_name{fe.parent_path()}; + _state_retention_file = fmt::format("{}/{}", base_name, value); } } @@ -4279,9 +4277,9 @@ void state::_set_cfg_dir(const std::string& value) { if (value.empty() || value[0] == '/') _cfg_dir.push_back(value); else { - io::file_entry fe(_cfg_main); - std::string base_name(fe.directory_name()); - _cfg_dir.push_back(base_name + "/" + value); + std::filesystem::path fe{_cfg_main}; + std::string base_name{fe.parent_path()}; + _cfg_dir.emplace_back(fmt::format("{}/{}", base_name, value)); } } @@ -4294,9 +4292,9 @@ void state::_set_cfg_file(const std::string& value) { if (value.empty() || value[0] == '/') _cfg_file.push_back(value); else { - io::file_entry fe(_cfg_main); - std::string base_name(fe.directory_name()); - _cfg_file.push_back(base_name + "/" + value); + std::filesystem::path fe{_cfg_main}; + std::string base_name{fe.parent_path()}; + _cfg_file.emplace_back(fmt::format("{}/{}", base_name, value)); } } @@ -4344,7 +4342,7 @@ void state::_set_event_broker_options(const std::string& value) { detail::setter("") .apply_from_cfg(*this, value.c_str()); else { - _event_broker_options = BROKER_EVERYTHING; + _event_broker_options = std::numeric_limits::max(); } } @@ -4395,9 +4393,9 @@ void state::_set_resource_file(const std::string& value) { if (value.empty() || value[0] == '/') _resource_file.push_back(value); else { - io::file_entry fe(_cfg_main); - std::string base_name(fe.directory_name()); - _resource_file.push_back(base_name + "/" + value); + std::filesystem::path fe{_cfg_main}; + std::string base_name{fe.parent_path()}; + _resource_file.emplace_back(fmt::format("{}/{}", base_name, value)); } } diff --git a/engine/src/configuration/timeperiod.cc b/engine/src/configuration/timeperiod.cc index c4eb591f57f..4bb281be9f7 100644 --- a/engine/src/configuration/timeperiod.cc +++ b/engine/src/configuration/timeperiod.cc @@ -19,7 +19,7 @@ */ #include "com/centreon/engine/configuration/timeperiod.hh" -#include "com/centreon/engine/timerange.hh" +#include "com/centreon/engine/configuration/daterange.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon; @@ -157,7 +157,7 @@ void timeperiod::merge(object const& obj) { MRG_TAB(_timeranges); // Merge exceptions. - for (unsigned int i(0); i < DATERANGE_TYPES; ++i) { + for (uint32_t i = 0; i < daterange::daterange_types; ++i) { for (std::list::const_iterator it(tmpl._exceptions[i].begin()), end(tmpl._exceptions[i].end()); it != end; ++it) { @@ -219,7 +219,9 @@ std::string const& timeperiod::alias() const noexcept { * * @return The exceptions value. */ -exception_array const& timeperiod::exceptions() const noexcept { +std::array, + configuration::daterange::daterange_types> const& +timeperiod::exceptions() const noexcept { return _exceptions; } @@ -246,7 +248,8 @@ std::string const& timeperiod::timeperiod_name() const noexcept { * * @return The timeranges list. */ -days_array const& timeperiod::timeranges() const { +const std::array, 7>& +timeperiod::timeranges() const { return _timeranges; } @@ -258,8 +261,9 @@ days_array const& timeperiod::timeranges() const { * * @return True on success, otherwise false. */ -bool timeperiod::_build_timeranges(std::string const& line, - timerange_list& timeranges) { +bool timeperiod::_build_timeranges( + std::string const& line, + std::list& timeranges) { auto timeranges_str = absl::StrSplit(line, ','); for (auto tr : timeranges_str) { tr = absl::StripAsciiWhitespace(tr); @@ -308,11 +312,11 @@ bool timeperiod::_build_time_t(std::string_view time_str, unsigned long& ret) { * * @return True on success, otherwise false. */ -bool timeperiod::_has_similar_daterange(std::list const& lst, - daterange const& range) noexcept { - for (std::list::const_iterator it(lst.begin()), end(lst.end()); - it != end; ++it) - if (it->is_date_data_equal(range)) +bool timeperiod::_has_similar_daterange( + const std::list& lst, + const configuration::daterange& range) noexcept { + for (auto& l : lst) + if (l.is_date_data_equal(range)) return true; return false; } @@ -359,11 +363,11 @@ bool timeperiod::_add_calendar_date(std::string const& line) { month_day_end = month_day_start; } - timerange_list timeranges; + std::list timeranges; if (!_build_timeranges(line.substr(pos), timeranges)) return false; - daterange range(daterange::calendar_date); + configuration::daterange range(daterange::calendar_date); range.set_syear(year_start); range.set_smon(month_start - 1); range.set_smday(month_day_start); @@ -546,7 +550,7 @@ bool timeperiod::_add_other_date(std::string const& line) { } range.set_skip_interval(skip_interval); - timerange_list timeranges; + std::list timeranges; if (!_build_timeranges(line.substr(pos), timeranges)) return false; diff --git a/engine/src/daterange.cc b/engine/src/daterange.cc index b3cf5bccda7..6404f230a73 100644 --- a/engine/src/daterange.cc +++ b/engine/src/daterange.cc @@ -20,6 +20,7 @@ #include "com/centreon/engine/daterange.hh" #include "com/centreon/engine/common.hh" +#include "com/centreon/engine/configuration/daterange.hh" #include "com/centreon/engine/string.hh" #include "com/centreon/engine/timeperiod.hh" #include "com/centreon/engine/timerange.hh" @@ -42,10 +43,21 @@ using namespace com::centreon::engine; * @param[in] ewday * @param[in] ewday_offset * @param[in] skip_interval + * @param[in] a list of timeranges. */ -daterange::daterange(type_range type, int syear, int smon, int smday, int swday, - int swday_offset, int eyear, int emon, int emday, - int ewday, int ewday_offset, int skip_interval) +daterange::daterange(type_range type, + int syear, + int smon, + int smday, + int swday, + int swday_offset, + int eyear, + int emon, + int emday, + int ewday, + int ewday_offset, + int skip_interval, + const std::list& timeranges) : _type{type}, _syear{syear}, _smon{smon}, @@ -57,7 +69,10 @@ daterange::daterange(type_range type, int syear, int smon, int smday, int swday, _emday{emday}, _ewday{ewday}, _ewday_offset{ewday_offset}, - _skip_interval{skip_interval} {} + _skip_interval{skip_interval} { + for (auto& tr : timeranges) + add_timerange({tr.range_start(), tr.range_end()}); +} daterange::daterange(type_range type) : _type(type), @@ -92,16 +107,6 @@ bool daterange::operator==(daterange const& obj) const { _timerange == obj._timerange; } -bool daterange::is_date_data_equal(daterange const& obj) const { - return _type == obj.get_type() && _syear == obj.get_syear() && - _smon == obj.get_smon() && _smday == obj.get_smday() && - _swday == obj.get_swday() && _swday_offset == obj.get_swday_offset() && - _eyear == obj.get_eyear() && _emon == obj.get_emon() && - _emday == obj.get_emday() && _ewday == obj.get_ewday() && - _ewday_offset == obj.get_ewday_offset() && - _skip_interval == obj.get_skip_interval(); -} - /** * Not equal operator. * @@ -114,41 +119,6 @@ bool daterange::operator!=(daterange const& obj) const { return !(*this == obj); } -/** - * Less-than operator. - * - * @param[in] right Object to compare to. - * - * @return True if this object is less than right. - */ -bool daterange::operator<(daterange const& right) const { - if (_emon != right._emon) - return (_emon < right._emon); - else if (_smon != right._smon) - return (_smon < right._smon); - else if (_emday != right._emday) - return (_emday < right._emday); - else if (_smday != right._smday) - return (_smday < right._smday); - else if (_skip_interval != right._skip_interval) - return (_skip_interval < right._skip_interval); - else if (_type != right._type) - return (_type < right._type); - else if (_ewday != right._ewday) - return (_ewday < right._ewday); - else if (_swday != right._swday) - return (_swday < right._swday); - else if (_ewday_offset != right._ewday_offset) - return (_ewday_offset < right._ewday_offset); - else if (_swday_offset != right._swday_offset) - return (_swday_offset < right._swday_offset); - else if (_eyear != right._eyear) - return (_eyear < right._eyear); - else if (_syear != right._syear) - return (_syear < right._syear); - return (_timerange < right._timerange); -} - /** * Dump the daterange value into the calendar date format. * @@ -167,7 +137,8 @@ static std::ostream& _dump_calendar_date(std::ostream& os, os << " - " << std::setfill('0') << std::setw(2) << obj.get_eyear() << "-" << std::setfill('0') << std::setw(2) << obj.get_emon() + 1 << "-" << std::setfill('0') << std::setw(2) << obj.get_emday(); - if (obj.get_skip_interval()) os << " / " << obj.get_skip_interval(); + if (obj.get_skip_interval()) + os << " / " << obj.get_skip_interval(); return (os); } @@ -187,7 +158,8 @@ static std::ostream& _dump_month_date(std::ostream& os, daterange const& obj) { os << " - " << emon << " " << obj.get_emday(); else if (obj.get_smday() != obj.get_emday()) os << " - " << obj.get_emday(); - if (obj.get_skip_interval()) os << " / " << obj.get_skip_interval(); + if (obj.get_skip_interval()) + os << " / " << obj.get_skip_interval(); return (os); } @@ -201,8 +173,10 @@ static std::ostream& _dump_month_date(std::ostream& os, daterange const& obj) { */ static std::ostream& _dump_month_day(std::ostream& os, daterange const& obj) { os << "day " << obj.get_smday(); - if (obj.get_smday() != obj.get_emday()) os << " - " << obj.get_emday(); - if (obj.get_skip_interval()) os << " / " << obj.get_skip_interval(); + if (obj.get_smday() != obj.get_emday()) + os << " - " << obj.get_emday(); + if (obj.get_skip_interval()) + os << " / " << obj.get_skip_interval(); return (os); } @@ -226,7 +200,8 @@ static std::ostream& _dump_month_week_day(std::ostream& os, os << " - " << daterange::get_weekday_name(obj.get_ewday()) << " " << obj.get_ewday_offset() << " " << daterange::get_month_name(obj.get_emon()); - if (obj.get_skip_interval()) os << " / " << obj.get_skip_interval(); + if (obj.get_skip_interval()) + os << " / " << obj.get_skip_interval(); return (os); } @@ -245,7 +220,8 @@ static std::ostream& _dump_week_day(std::ostream& os, daterange const& obj) { obj.get_swday_offset() != obj.get_ewday_offset()) os << " - " << daterange::get_weekday_name(obj.get_ewday()) << " " << obj.get_ewday_offset(); - if (obj.get_skip_interval()) os << " / " << obj.get_skip_interval(); + if (obj.get_skip_interval()) + os << " / " << obj.get_skip_interval(); return (os); } @@ -318,7 +294,8 @@ std::string const& daterange::get_month_name(unsigned int index) { static std::string const month[] = { "january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"}; - if (index >= sizeof(month) / sizeof(*month)) return (unknown); + if (index >= sizeof(month) / sizeof(*month)) + return (unknown); return (month[index]); } @@ -334,6 +311,7 @@ std::string const& daterange::get_weekday_name(unsigned int index) { static std::string const days[] = {"sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"}; - if (index >= sizeof(days) / sizeof(*days)) return (unknown); + if (index >= sizeof(days) / sizeof(*days)) + return (unknown); return (days[index]); } diff --git a/engine/src/timeperiod.cc b/engine/src/timeperiod.cc index c95bd84957c..8f40a90edba 100644 --- a/engine/src/timeperiod.cc +++ b/engine/src/timeperiod.cc @@ -109,41 +109,6 @@ bool timeperiod::operator!=(timeperiod const& obj) noexcept { return !(*this == obj); } -/** - * Dump timeperiod content into the stream. - * - * @param[out] os The output stream. - * @param[in] obj The timeperiod to dump. - * - * @return The output stream. - */ -std::ostream& operator<<(std::ostream& os, timeperiod const& obj) { - os << "timeperiod {\n" - << " name: " << obj.get_name() << "\n" - << " alias: " << obj.get_alias() << "\n" - << " exclusions: " << obj.get_exclusions() << "\n"; - - for (uint32_t i = 0; i < obj.days.size(); ++i) - if (!obj.days[i].empty()) - os << " " << daterange::get_weekday_name(i) << ": " << obj.days[i] - << "\n"; - - for (uint32_t i = 0; i < obj.exceptions.size(); ++i) - for (daterange_list::const_iterator it(obj.exceptions[i].begin()), - end(obj.exceptions[i].end()); - it != end; ++it) - os << " " << *it << "\n"; - os << "}\n"; - return os; -} - -std::ostream& operator<<(std::ostream& os, timeperiodexclusion const& obj) { - for (timeperiodexclusion::const_iterator it(obj.begin()), end(obj.end()); - it != end; ++it) - os << it->first << (std::next(it) != obj.end() ? ", " : ""); - return os; -} - /** * Add a round number of days (expressed in seconds) to a date. * diff --git a/engine/tests/configuration/applier/applier-state.cc b/engine/tests/configuration/applier/applier-state.cc index 38177e7f6c6..7eb09f57a42 100644 --- a/engine/tests/configuration/applier/applier-state.cc +++ b/engine/tests/configuration/applier/applier-state.cc @@ -776,15 +776,15 @@ TEST_F(ApplierState, StateLegacyParsing) { EXPECT_EQ(tit->alias(), std::string("24_Hours_A_Day,_7_Days_A_Week")); EXPECT_EQ(tit->timeranges()[0].size(), 1u); // std::string("00:00-24:00")); - EXPECT_EQ(tit->timeranges()[0].begin()->get_range_start(), 0); - EXPECT_EQ(tit->timeranges()[0].begin()->get_range_end(), 3600 * 24); + EXPECT_EQ(tit->timeranges()[0].begin()->range_start(), 0); + EXPECT_EQ(tit->timeranges()[0].begin()->range_end(), 3600 * 24); EXPECT_EQ(tit->timeranges()[1].size(), 2u); auto itt = tit->timeranges()[1].begin(); - EXPECT_EQ(itt->get_range_start(), 0); // 00:00-08:00 - EXPECT_EQ(itt->get_range_end(), 3600 * 8); + EXPECT_EQ(itt->range_start(), 0); // 00:00-08:00 + EXPECT_EQ(itt->range_end(), 3600 * 8); ++itt; - EXPECT_EQ(itt->get_range_start(), 3600 * 18); // 18:00-24:00 - ASSERT_EQ(itt->get_range_end(), 3600 * 24); + EXPECT_EQ(itt->range_start(), 3600 * 18); // 18:00-24:00 + ASSERT_EQ(itt->range_end(), 3600 * 24); EXPECT_EQ(tit->timeranges()[2].size(), 1u); // tuesday EXPECT_EQ(tit->timeranges()[3].size(), 1u); // wednesday EXPECT_EQ(tit->timeranges()[4].size(), 1u); // thursday diff --git a/engine/tests/configuration/timeperiod-test.cc b/engine/tests/configuration/timeperiod-test.cc index 838e84f00fd..5073a024362 100644 --- a/engine/tests/configuration/timeperiod-test.cc +++ b/engine/tests/configuration/timeperiod-test.cc @@ -25,6 +25,7 @@ #include "com/centreon/engine/common.hh" #include "com/centreon/engine/configuration/applier/timeperiod.hh" +#include "com/centreon/engine/configuration/daterange.hh" #include "com/centreon/engine/globals.hh" using namespace com::centreon::engine::configuration; @@ -47,13 +48,17 @@ class time_period_comparator { const configuration::timeperiod& _parser; std::shared_ptr _result; - static timerange_list extract_timerange(const std::string& line_content, - unsigned offset, - const std::smatch& datas); + static std::list extract_timerange( + const std::string& line_content, + uint32_t offset, + const std::smatch& datas); std::string name, alias; - std::array _timeranges; - std::array _exceptions; + /* days_array */ + std::array, 7> _timeranges; + std::array, + configuration::daterange::daterange_types> + _exceptions; group _exclude; @@ -183,7 +188,7 @@ time_period_comparator::time_period_comparator( std::smatch line_extract; if (std::regex_search(line, line_extract, day_extractor)) { unsigned day_index = day_to_index.find(line_extract[1].str())->second; - timerange_list time_intervals = + std::list time_intervals = extract_timerange(line, 2, line_extract); _timeranges[day_index] = time_intervals; continue; @@ -192,7 +197,7 @@ time_period_comparator::time_period_comparator( { // exception "january 1 08:00-12:00" std::smatch line_extract; if (std::regex_search(line, line_extract, date_extractor)) { - timerange_list time_intervals = + std::list time_intervals = extract_timerange(line, 3, line_extract); int day_of_month = atoi(line_extract[2].str().c_str()); unsigned month_index = @@ -211,7 +216,7 @@ time_period_comparator::time_period_comparator( { // exception july 10 - 15 / 2 00:00-24:00 std::smatch line_extract; if (std::regex_search(line, line_extract, date_range1_extractor)) { - timerange_list time_intervals = + std::list time_intervals = extract_timerange(line, 5, line_extract); int day_of_month_start = atoi(line_extract[2].str().c_str()); int day_of_month_end = atoi(line_extract[3].str().c_str()); @@ -232,7 +237,7 @@ time_period_comparator::time_period_comparator( { // exception april 10 - may 15 /2 00:00-24:00 std::smatch line_extract; if (std::regex_search(line, line_extract, date_range2_extractor)) { - timerange_list time_intervals = + std::list time_intervals = extract_timerange(line, 6, line_extract); int day_of_month_start = atoi(line_extract[2].str().c_str()); unsigned month_index_start = @@ -260,7 +265,7 @@ time_period_comparator::time_period_comparator( unsigned day_of_month = atoi(line_extract[3].str().c_str()); daterange toadd(daterange::calendar_date); extract_skip(line_extract, 4, toadd); - timerange_list time_intervals = + std::list time_intervals = extract_timerange(line, 5, line_extract); toadd.set_syear(year); toadd.set_eyear(year); @@ -277,7 +282,7 @@ time_period_comparator::time_period_comparator( { // exception "2007-01-01 - 2008-02-01 /3 00:00-24:00" std::smatch line_extract; if (std::regex_search(line, line_extract, full_date_range_extractor)) { - timerange_list time_intervals = + std::list time_intervals = extract_timerange(line, 8, line_extract); unsigned year_start = atoi(line_extract[1].str().c_str()); unsigned month_start = atoi(line_extract[2].str().c_str()) - 1; @@ -302,7 +307,7 @@ time_period_comparator::time_period_comparator( { // exception day -1 std::smatch line_extract; if (std::regex_search(line, line_extract, n_th_day_of_month_extractor)) { - timerange_list time_intervals = + std::list time_intervals = extract_timerange(line, 2, line_extract); unsigned day_of_month = atoi(line_extract[1].str().c_str()); daterange toadd(daterange::month_day); @@ -318,7 +323,7 @@ time_period_comparator::time_period_comparator( std::smatch line_extract; if (std::regex_search(line, line_extract, n_th_day_of_month_range_extractor)) { - timerange_list time_intervals = + std::list time_intervals = extract_timerange(line, 4, line_extract); unsigned day_of_month_start = atoi(line_extract[1].str().c_str()); unsigned day_of_month_end = atoi(line_extract[2].str().c_str()); @@ -335,7 +340,7 @@ time_period_comparator::time_period_comparator( { // exception monday 3 00:00-24:00 std::smatch line_extract; if (std::regex_search(line, line_extract, n_th_day_of_week_extractor)) { - timerange_list time_intervals = + std::list time_intervals = extract_timerange(line, 3, line_extract); daterange toadd(daterange::week_day); unsigned week_day_index = @@ -355,7 +360,7 @@ time_period_comparator::time_period_comparator( std::smatch line_extract; if (std::regex_search(line, line_extract, n_th_day_of_week_range_extractor)) { - timerange_list time_intervals = + std::list time_intervals = extract_timerange(line, 6, line_extract); daterange toadd(daterange::week_day); extract_skip(line_extract, 5, toadd); @@ -379,7 +384,7 @@ time_period_comparator::time_period_comparator( std::smatch line_extract; if (std::regex_search(line, line_extract, n_th_day_of_week_of_month_extractor)) { - timerange_list time_intervals = + std::list time_intervals = extract_timerange(line, 4, line_extract); daterange toadd(daterange::month_week_day); unsigned month_index = @@ -403,7 +408,7 @@ time_period_comparator::time_period_comparator( std::smatch line_extract; if (std::regex_search(line, line_extract, n_th_day_of_week_of_month_range_extractor)) { - timerange_list time_intervals = + std::list time_intervals = extract_timerange(line, 8, line_extract); daterange toadd(daterange::month_week_day); unsigned month_index_start = @@ -463,10 +468,13 @@ std::ostream& operator<<(std::ostream& s, const set_string& to_dump) { return s; } -static const char* day_label[] = {"sunday", "monday", "tuesday", "wednesday", - "thursday", "friday", "saturday"}; +static const std::array day_label{ + "sunday", "monday", "tuesday", "wednesday", + "thursday", "friday", "saturday"}; -std::ostream& operator<<(std::ostream& s, const days_array& to_dump) { +std::ostream& operator<<( + std::ostream& s, + const std::array, 7>& to_dump) { s << '['; for (unsigned day_ind = 0; day_ind < 7; ++day_ind) { s << '{' << day_label[day_ind] << " , " << to_dump[day_ind] << "},"; @@ -583,6 +591,60 @@ bool operator==(const set_string& left, return left_to_cmp == right_to_cmp; } +static bool operator==( + const days_array& da, + const std::array, 7>& cda) { + for (uint32_t i = 0; i < da.size(); i++) { + auto it = da[i].begin(); + auto end = da[i].end(); + auto cit = cda[i].begin(); + auto cend = cda[i].end(); + while (it != end && cit != cend) { + if (it->get_range_end() != cit->range_end() || + it->get_range_start() != cit->range_start()) + return false; + ++it; + ++cit; + } + if (it != end || cit != cend) + return false; + } + return true; +} + +static bool operator==( + const exception_array& ea, + const std::array, + configuration::daterange::daterange_types>& cea) { + for (uint32_t i = 0; i < ea.size(); i++) { + auto it = ea[i].begin(); + auto end = ea[i].end(); + auto cit = cea[i].begin(); + auto cend = cea[i].end(); + while (it != end && cit != cend) { + if (static_cast(cit->type()) != + static_cast(it->get_type()) || + cit->get_syear() != it->get_syear() || + cit->get_smon() != it->get_smon() || + cit->get_smday() != it->get_smday() || + cit->get_swday() != it->get_swday() || + cit->get_swday_offset() != it->get_swday_offset() || + cit->get_eyear() != it->get_eyear() || + cit->get_emon() != it->get_emon() || + cit->get_emday() != it->get_emday() || + cit->get_ewday() != it->get_ewday() || + cit->get_ewday_offset() != it->get_ewday_offset() || + cit->get_skip_interval() != it->get_skip_interval()) + return false; + ++it; + ++cit; + } + if (it != end || cit != cend) + return false; + } + return true; +} + bool time_period_comparator::is_result_equal() const { if (name != _result->get_name()) { std::cerr << "different name: " << name << " <> " << _result->get_name() @@ -619,11 +681,11 @@ bool time_period_comparator::is_result_equal() const { return true; } -timerange_list time_period_comparator::extract_timerange( +std::list time_period_comparator::extract_timerange( const std::string& line_content, unsigned offset, const std::smatch& datas) { - timerange_list ret; + std::list ret; for (; offset < datas.size(); ++offset) { std::smatch range; std::string ranges = datas[offset].str(); diff --git a/engine/tests/timeperiod/utils.cc b/engine/tests/timeperiod/utils.cc index 06b4dbdf1ef..ffd10cd5b91 100644 --- a/engine/tests/timeperiod/utils.cc +++ b/engine/tests/timeperiod/utils.cc @@ -1,21 +1,21 @@ /** -* Copyright 2016 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2016 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include #include @@ -106,7 +106,8 @@ daterange* timeperiod_creator::new_calendar_date(int start_year, target->exceptions[daterange::calendar_date].emplace_back( daterange::calendar_date, start_year, start_month, start_day, 0, 0, - end_year, end_month, end_day, 0, 0, 0); + end_year, end_month, end_day, 0, 0, 0, + std::list()); return &*target->exceptions[daterange::calendar_date].rbegin(); } @@ -131,7 +132,7 @@ daterange* timeperiod_creator::new_specific_month_date(int start_month, target->exceptions[daterange::month_date].emplace_back( daterange::month_date, 0, start_month, start_day, 0, 0, 0, end_month, - end_day, 0, 0, 0); + end_day, 0, 0, 0, std::list()); return &*target->exceptions[daterange::month_date].rbegin(); } @@ -151,10 +152,11 @@ daterange* timeperiod_creator::new_generic_month_date(int start_day, target = _timeperiods.begin()->get(); std::shared_ptr dr{new daterange( - daterange::month_day, 0, 0, start_day, 0, 0, 0, 0, end_day, 0, 0, 0)}; + daterange::month_day, 0, 0, start_day, 0, 0, 0, 0, end_day, 0, 0, 0, {})}; target->exceptions[daterange::month_day].emplace_back( - daterange::month_day, 0, 0, start_day, 0, 0, 0, 0, end_day, 0, 0, 0); + daterange::month_day, 0, 0, start_day, 0, 0, 0, 0, end_day, 0, 0, 0, + std::list()); return &*target->exceptions[daterange::month_day].rbegin(); } @@ -184,7 +186,8 @@ daterange* timeperiod_creator::new_offset_weekday_of_specific_month( target->exceptions[daterange::month_week_day].emplace_back( daterange::month_week_day, 0, start_month, 0, start_wday, start_offset, 0, - end_month, 0, end_wday, end_offset, 0); + end_month, 0, end_wday, end_offset, 0, + std::list()); return &*target->exceptions[daterange::month_week_day].rbegin(); } @@ -210,7 +213,7 @@ daterange* timeperiod_creator::new_offset_weekday_of_generic_month( target->exceptions[daterange::week_day].emplace_back( daterange::week_day, 0, 0, 0, start_wday, start_offset, 0, 0, 0, end_wday, - end_offset, 0); + end_offset, 0, std::list()); return &*target->exceptions[daterange::week_day].rbegin(); } diff --git a/tests/broker-engine/services-and-bulk-stmt.robot b/tests/broker-engine/services-and-bulk-stmt.robot index 5662fbdba12..c6d070e8b05 100644 --- a/tests/broker-engine/services-and-bulk-stmt.robot +++ b/tests/broker-engine/services-and-bulk-stmt.robot @@ -30,11 +30,8 @@ EBBPS1 ${start_broker} Get Current Date Ctn Start Broker Ctn Start engine - ${content} Create List INITIAL SERVICE STATE: host_1;service_1000; - ${result} Ctn Find In Log With Timeout ${engineLog0} ${start} ${content} 30 - Should Be True - ... ${result} - ... An Initial service state on host_1:service_1000 should be raised before we can start external commands. + Ctn Wait For Engine To Be Ready ${start} + FOR ${i} IN RANGE ${1000} Ctn Process Service Check Result host_1 service_${i+1} 1 warning${i} END From 60d854f3e64badd4496f32de24373f706308dfd5 Mon Sep 17 00:00:00 2001 From: jean-christophe81 <98889244+jean-christophe81@users.noreply.github.com> Date: Fri, 28 Jun 2024 15:42:11 +0200 Subject: [PATCH 53/60] feature(centagent): first centagent executable part 2 (#1469) * telegraf conf accepts only one host add scheduler, check and check_exec class to agent * otel tests checks resources table --- .gitignore | 1 + agent/CMakeLists.txt | 6 + agent/doc/agent-doc.md | 1 + agent/inc/com/centreon/agent/check.hh | 125 +++++ agent/inc/com/centreon/agent/check_exec.hh | 117 +++++ agent/inc/com/centreon/agent/config.hh | 6 +- agent/inc/com/centreon/agent/scheduler.hh | 209 ++++++++ agent/src/check.cc | 141 +++++ agent/src/check_exec.cc | 266 ++++++++++ agent/src/config.cc | 12 +- agent/src/main.cc | 19 +- agent/src/scheduler.cc | 485 ++++++++++++++++++ agent/test/CMakeLists.txt | 4 + agent/test/check_exec_test.cc | 113 ++++ agent/test/check_test.cc | 141 +++++ agent/test/scheduler_test.cc | 450 ++++++++++++++++ .../modules/opentelemetry/conf_helper.hh | 100 ++++ .../opentelemetry/telegraf/conf_server.hh | 2 +- .../opentelemetry/src/data_point_fifo.cc | 4 +- .../opentelemetry/src/telegraf/conf_server.cc | 24 +- .../telegraf/nagios_check_result_builder.cc | 5 +- tests/broker-engine/opentelemetry.robot | 69 +-- tests/resources/Broker.py | 4 +- tests/resources/Common.py | 88 ++++ tests/resources/opentelemetry/telegraf.conf | 18 - 25 files changed, 2323 insertions(+), 87 deletions(-) create mode 100644 agent/inc/com/centreon/agent/check.hh create mode 100644 agent/inc/com/centreon/agent/check_exec.hh create mode 100644 agent/inc/com/centreon/agent/scheduler.hh create mode 100644 agent/src/check.cc create mode 100644 agent/src/check_exec.cc create mode 100644 agent/src/scheduler.cc create mode 100644 agent/test/check_exec_test.cc create mode 100644 agent/test/check_test.cc create mode 100644 agent/test/scheduler_test.cc create mode 100644 engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/conf_helper.hh diff --git a/.gitignore b/.gitignore index 77cd000405a..e783d4cbb85 100644 --- a/.gitignore +++ b/.gitignore @@ -67,6 +67,7 @@ report.html # agent agent/scripts/centagent.service +agent/conf/centagent.json opentelemetry-proto # bbdo diff --git a/agent/CMakeLists.txt b/agent/CMakeLists.txt index 4d37d055ee2..7a8ec1a1036 100644 --- a/agent/CMakeLists.txt +++ b/agent/CMakeLists.txt @@ -99,12 +99,17 @@ add_custom_command( add_library(centagent_lib STATIC + ${SRC_DIR}/agent.grpc.pb.cc + ${SRC_DIR}/agent.pb.cc + ${SRC_DIR}/check.cc + ${SRC_DIR}/check_exec.cc ${SRC_DIR}/opentelemetry/proto/collector/metrics/v1/metrics_service.grpc.pb.cc ${SRC_DIR}/opentelemetry/proto/collector/metrics/v1/metrics_service.pb.cc ${SRC_DIR}/opentelemetry/proto/metrics/v1/metrics.pb.cc ${SRC_DIR}/opentelemetry/proto/common/v1/common.pb.cc ${SRC_DIR}/opentelemetry/proto/resource/v1/resource.pb.cc ${SRC_DIR}/config.cc + ${SRC_DIR}/scheduler.cc ) include_directories( @@ -127,6 +132,7 @@ target_link_libraries( centagent_lib centreon_common centreon_grpc + centreon_process -L${Boost_LIBRARY_DIR_RELEASE} boost_program_options fmt::fmt) diff --git a/agent/doc/agent-doc.md b/agent/doc/agent-doc.md index ab326f5fbdc..8d92a4b3ee7 100644 --- a/agent/doc/agent-doc.md +++ b/agent/doc/agent-doc.md @@ -21,3 +21,4 @@ In the previous example, the second check for the first service will be schedule In case of check duration is too long, we might exceed maximum of concurrent checks. In that case checks will be executed as soon one will be ended. This means that the second check may start later than the scheduled time point (12:00:10) if the other first checks are too long. The order of checks is always respected even in case of a bottleneck. +For example, a check lambda has a start_expected to 12:00, because of bottleneck, it starts at 12:15. Next start_expected of check lambda will then be 12:15 + check_period. diff --git a/agent/inc/com/centreon/agent/check.hh b/agent/inc/com/centreon/agent/check.hh new file mode 100644 index 00000000000..c2808293e0e --- /dev/null +++ b/agent/inc/com/centreon/agent/check.hh @@ -0,0 +1,125 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#ifndef CENTREON_AGENT_CHECK_HH +#define CENTREON_AGENT_CHECK_HH + +#include "agent.pb.h" +#include "com/centreon/common/perfdata.hh" + +namespace com::centreon::agent { + +using engine_to_agent_request_ptr = + std::shared_ptr; + +using time_point = std::chrono::system_clock::time_point; +using duration = std::chrono::system_clock::duration; + +/** + * @brief base class for check + * start_expected is set by scheduler and increased by check_period on each + * check + * + */ +class check : public std::enable_shared_from_this { + public: + using completion_handler = std::function& caller, + int status, + const std::list& perfdata, + const std::list& outputs)>; + + private: + //_start_expected is set on construction on config receive + // it's updated on check_start and added of check_period on check completion + time_point _start_expected; + const std::string& _service; + const std::string& _command_name; + const std::string& _command_line; + // by owning a reference to the original request, we can get only reference to + // host, service and command_line + // on completion, this pointer is compared to the current config pointer. + // if not equal result is not processed + engine_to_agent_request_ptr _conf; + + asio::system_timer _time_out_timer; + + void _start_timeout_timer(const duration& timeout); + + bool _running_check = false; + // this index is used and incremented by on_completion to insure that + // async on_completion is called by the actual asynchronous check + unsigned _running_check_index = 0; + completion_handler _completion_handler; + + protected: + std::shared_ptr _io_context; + std::shared_ptr _logger; + + unsigned _get_running_check_index() const { return _running_check_index; } + const completion_handler& _get_completion_handler() const { + return _completion_handler; + } + + virtual void _timeout_timer_handler(const boost::system::error_code& err, + unsigned start_check_index); + + public: + using pointer = std::shared_ptr; + + check(const std::shared_ptr& io_context, + const std::shared_ptr& logger, + time_point exp, + const std::string& serv, + const std::string& command_name, + const std::string& cmd_line, + const engine_to_agent_request_ptr& cnf, + completion_handler&& handler); + + virtual ~check() = default; + + struct pointer_start_compare { + bool operator()(const check::pointer& left, + const check::pointer& right) const { + return left->_start_expected < right->_start_expected; + } + }; + + void add_duration_to_start_expected(const duration& to_add); + + time_point get_start_expected() const { return _start_expected; } + + const std::string& get_service() const { return _service; } + + const std::string& get_command_name() const { return _command_name; } + + const std::string& get_command_line() const { return _command_line; } + + const engine_to_agent_request_ptr& get_conf() const { return _conf; } + + void on_completion(unsigned start_check_index, + unsigned status, + const std::list& perfdata, + const std::list& outputs); + + virtual void start_check(const duration& timeout); +}; + +} // namespace com::centreon::agent + +#endif diff --git a/agent/inc/com/centreon/agent/check_exec.hh b/agent/inc/com/centreon/agent/check_exec.hh new file mode 100644 index 00000000000..42107040c4a --- /dev/null +++ b/agent/inc/com/centreon/agent/check_exec.hh @@ -0,0 +1,117 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#ifndef CENTREON_AGENT_CHECK_EXEC_HH +#define CENTREON_AGENT_CHECK_EXEC_HH + +#include "check.hh" +#include "com/centreon/common/process.hh" + +namespace com::centreon::agent { + +class check_exec; + +namespace detail { + +/** + * @brief This class is used by check_exec class to execute plugins + * It calls check_exec::on_completion once process is ended AND we have received + * an eof on stdout pipe + * stderr pipe is not read as plugins should not use it + * As we are in asynchronous world, running index is carried until completion to + * ensure that completion is called for the right process and not for the + * previous one + */ +class process : public common::process { + bool _process_ended; + bool _stdout_eof; + std::string _stdout; + unsigned _running_index; + std::weak_ptr _parent; + + void _on_completion(); + + public: + process(const std::shared_ptr& io_context, + const std::shared_ptr& logger, + const std::string& cmd_line, + const std::shared_ptr& parent); + + void start(unsigned running_index); + + void kill() { common::process::kill(); } + + int get_exit_status() const { return common::process::get_exit_status(); } + + const std::string& get_stdout() const { return _stdout; } + + protected: + void on_stdout_read(const boost::system::error_code& err, + size_t nb_read) override; + void on_stderr_read(const boost::system::error_code& err, + size_t nb_read) override; + + void on_process_end(const boost::system::error_code& err, + int raw_exit_status) override; +}; + +} // namespace detail + +/** + * @brief check that executes a process (plugins) + * + */ +class check_exec : public check { + std::shared_ptr _process; + + protected: + using check::completion_handler; + + void _timeout_timer_handler(const boost::system::error_code& err, + unsigned start_check_index) override; + + void _init(); + + public: + check_exec(const std::shared_ptr& io_context, + const std::shared_ptr& logger, + time_point exp, + const std::string& serv, + const std::string& cmd_name, + const std::string& cmd_line, + const engine_to_agent_request_ptr& cnf, + check::completion_handler&& handler); + + static std::shared_ptr load( + const std::shared_ptr& io_context, + const std::shared_ptr& logger, + time_point exp, + const std::string& serv, + const std::string& cmd_name, + const std::string& cmd_line, + const engine_to_agent_request_ptr& cnf, + check::completion_handler&& handler); + + void start_check(const duration& timeout) override; + + void on_completion(unsigned running_index); +}; + +} // namespace com::centreon::agent + +#endif diff --git a/agent/inc/com/centreon/agent/config.hh b/agent/inc/com/centreon/agent/config.hh index 5df87e87901..d0bd774f97a 100644 --- a/agent/inc/com/centreon/agent/config.hh +++ b/agent/inc/com/centreon/agent/config.hh @@ -26,6 +26,8 @@ class config { public: enum log_type { to_stdout, to_file }; + static const std::string_view config_schema; + private: std::string _endpoint; spdlog::level::level_enum _log_level; @@ -35,7 +37,7 @@ class config { unsigned _log_files_max_number; bool _encryption; - std::string _certificate_file; + std::string _public_cert_file; std::string _private_key_file; std::string _ca_certificate_file; std::string _ca_name; @@ -53,7 +55,7 @@ class config { unsigned get_log_files_max_number() const { return _log_files_max_number; } bool use_encryption() const { return _encryption; } - const std::string& get_certificate_file() const { return _certificate_file; } + const std::string& get_public_cert_file() const { return _public_cert_file; } const std::string& get_private_key_file() const { return _private_key_file; } const std::string& get_ca_certificate_file() const { return _ca_certificate_file; diff --git a/agent/inc/com/centreon/agent/scheduler.hh b/agent/inc/com/centreon/agent/scheduler.hh new file mode 100644 index 00000000000..fcd3d71a6fa --- /dev/null +++ b/agent/inc/com/centreon/agent/scheduler.hh @@ -0,0 +1,209 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#ifndef CENTREON_AGENT_SCHEDULER_HH +#define CENTREON_AGENT_SCHEDULER_HH + +#include "check.hh" + +namespace com::centreon::agent { + +/** + * @brief the core of the agent + * It has to create check object with chck_builder passed in parameter of load + * method It sends metrics to engine and tries to spread checks over check + * period It also limits concurrent checks in order to limit system load + */ +class scheduler : public std::enable_shared_from_this { + public: + using metric_sender = + std::function&)>; + using check_builder = std::function( + const std::shared_ptr&, + const std::shared_ptr& /*logger*/, + time_point /* start expected*/, + const std::string& /*service*/, + const std::string& /*cmd_name*/, + const std::string& /*cmd_line*/, + const engine_to_agent_request_ptr& /*engine to agent request*/, + check::completion_handler&&)>; + + private: + using check_queue = std::set; + + check_queue _check_queue; + // running check counter that must not exceed max_concurrent_check + unsigned _active_check = 0; + bool _alive = true; + + // request that will be sent to engine + std::shared_ptr _current_request; + + // pointers in this struct point to _current_request + struct scope_metric_request { + ::opentelemetry::proto::metrics::v1::ScopeMetrics* scope_metric; + absl::flat_hash_map + metrics; + }; + + // one serv => one scope_metric => several metrics + absl::flat_hash_map _serv_to_scope_metrics; + + std::shared_ptr _io_context; + std::shared_ptr _logger; + // host declared in engine config + std::string _supervised_host; + metric_sender _metric_sender; + asio::system_timer _send_timer; + asio::system_timer _check_timer; + check_builder _check_builder; + // in order to send check_results at regular intervals, we work with absolute + // time points that we increment + time_point _next_send_time_point; + // last received configuration + engine_to_agent_request_ptr _conf; + + void _start(); + void _start_send_timer(); + void _send_timer_handler(const boost::system::error_code& err); + void _start_check_timer(); + void _check_timer_handler(const boost::system::error_code& err); + + void _init_export_request(); + void _start_check(const check::pointer& check); + void _check_handler( + const check::pointer& check, + unsigned status, + const std::list& perfdata, + const std::list& outputs); + void _store_result_in_metrics( + const check::pointer& check, + unsigned status, + const std::list& perfdata, + const std::list& outputs); + void _store_result_in_metrics_and_exemplars( + const check::pointer& check, + unsigned status, + const std::list& perfdata, + const std::list& outputs); + + scope_metric_request& _get_scope_metrics(const std::string& service); + + ::opentelemetry::proto::metrics::v1::Metric* _get_metric( + scope_metric_request& scope_metric, + const std::string& metric_name); + + void _add_metric_to_scope(uint64_t now, + const com::centreon::common::perfdata& perf, + scope_metric_request& scope_metric); + + void _add_exemplar( + const char* label, + double value, + ::opentelemetry::proto::metrics::v1::NumberDataPoint& data_point); + void _add_exemplar( + const char* label, + bool value, + ::opentelemetry::proto::metrics::v1::NumberDataPoint& data_point); + + void _start_waiting_check(); + + public: + template + scheduler(const std::shared_ptr& io_context, + const std::shared_ptr& logger, + const std::string& supervised_host, + const std::shared_ptr& config, + sender&& met_sender, + chck_builder&& builder); + + scheduler(const scheduler&) = delete; + scheduler operator=(const scheduler&) = delete; + + void update(const engine_to_agent_request_ptr& conf); + + static std::shared_ptr default_config(); + + template + static std::shared_ptr load( + const std::shared_ptr& io_context, + const std::shared_ptr& logger, + const std::string& supervised_host, + const std::shared_ptr& config, + sender&& met_sender, + chck_builder&& chk_builder); + + void stop(); + + engine_to_agent_request_ptr get_last_message_to_agent() const { + return _conf; + } +}; + +/** + * @brief Construct a new scheduler::scheduler object + * + * @tparam sender + * @param met_sender void(const export_metric_request_ptr&) called each time + * scheduler wants to send metrics to engine + * @param io_context + */ +template +scheduler::scheduler( + const std::shared_ptr& io_context, + const std::shared_ptr& logger, + const std::string& supervised_host, + const std::shared_ptr& config, + sender&& met_sender, + chck_builder&& builder) + : _metric_sender(met_sender), + _io_context(io_context), + _logger(logger), + _supervised_host(supervised_host), + _send_timer(*io_context), + _check_timer(*io_context), + _check_builder(builder), + _conf(config) {} + +/** + * @brief create and start a new scheduler + * + * @tparam sender + * @param met_sender void(const export_metric_request_ptr&) called each time + * scheduler wants to send metrics to engine + * @return std::shared_ptr + */ +template +std::shared_ptr scheduler::load( + const std::shared_ptr& io_context, + const std::shared_ptr& logger, + const std::string& supervised_host, + const std::shared_ptr& config, + sender&& met_sender, + chck_builder&& chk_builder) { + std::shared_ptr to_start = std::make_shared( + io_context, logger, supervised_host, config, std::move(met_sender), + std::move(chk_builder)); + to_start->_start(); + return to_start; +} + +} // namespace com::centreon::agent + +#endif diff --git a/agent/src/check.cc b/agent/src/check.cc new file mode 100644 index 00000000000..562fd0329b2 --- /dev/null +++ b/agent/src/check.cc @@ -0,0 +1,141 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#include "check.hh" + +using namespace com::centreon::agent; + +/** + * @brief Construct a new check::check object + * + * @param io_context + * @param logger + * @param exp + * @param serv + * @param command_name + * @param cmd_line + * @param cnf + * @param handler + */ +check::check(const std::shared_ptr& io_context, + const std::shared_ptr& logger, + time_point exp, + const std::string& serv, + const std::string& command_name, + const std::string& cmd_line, + const engine_to_agent_request_ptr& cnf, + completion_handler&& handler) + : _start_expected(exp), + _service(serv), + _command_name(command_name), + _command_line(cmd_line), + _conf(cnf), + _io_context(io_context), + _logger(logger), + _time_out_timer(*io_context), + _completion_handler(handler) {} + +/** + * @brief scheduler uses this method to increase start_expected + * + * @param to_add + */ +void check::add_duration_to_start_expected(const duration& to_add) { + _start_expected += to_add; +} + +/** + * @brief start a asynchronous check + * + * @param timeout + */ +void check::start_check(const duration& timeout) { + if (_running_check) { + SPDLOG_LOGGER_ERROR(_logger, "check for service {} is already running", + _service); + _io_context->post( + [me = shared_from_this(), to_call = _completion_handler]() { + to_call(me, 3, std::list(), + {"a check is already running"}); + }); + return; + } + // we refresh start expected in order that next call will occur at now + check + // period + _start_expected = std::chrono::system_clock::now(); + _running_check = true; + _start_timeout_timer(timeout); + SPDLOG_LOGGER_TRACE(_logger, "start check for service {}", _service); +} + +/** + * @brief start check timeout timer + * + * @param timeout + */ +void check::_start_timeout_timer(const duration& timeout) { + _time_out_timer.expires_from_now(timeout); + _time_out_timer.async_wait( + [me = shared_from_this(), start_check_index = _running_check_index]( + const boost::system::error_code& err) { + me->_timeout_timer_handler(err, start_check_index); + }); +} + +/** + * @brief timeout timer handler + * + * @param err + * @param start_check_index + */ +void check::_timeout_timer_handler(const boost::system::error_code& err, + unsigned start_check_index) { + if (err) { + return; + } + if (start_check_index == _running_check_index) { + SPDLOG_LOGGER_ERROR(_logger, "check timeout for service {}", _service); + on_completion(start_check_index, 3 /*unknown*/, + std::list(), + {"Timeout at execution of " + _command_line}); + } +} + +/** + * @brief called when check is ended + * _running_check is increased so that next check will be identified by this new + * id. We also cancel timeout timer + * + * @param start_check_index + * @param status + * @param perfdata + * @param outputs + */ +void check::on_completion( + unsigned start_check_index, + unsigned status, + const std::list& perfdata, + const std::list& outputs) { + if (start_check_index == _running_check_index) { + SPDLOG_LOGGER_TRACE(_logger, "end check for service {}", _service); + _time_out_timer.cancel(); + _running_check = false; + ++_running_check_index; + _completion_handler(shared_from_this(), status, perfdata, outputs); + } +} diff --git a/agent/src/check_exec.cc b/agent/src/check_exec.cc new file mode 100644 index 00000000000..d38d0deeac9 --- /dev/null +++ b/agent/src/check_exec.cc @@ -0,0 +1,266 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#include "check_exec.hh" + +using namespace com::centreon::agent; + +/** + * @brief Construct a new detail::process::process object + * + * @param io_context + * @param logger + * @param cmd_line + * @param parent + */ +detail::process::process(const std::shared_ptr& io_context, + const std::shared_ptr& logger, + const std::string& cmd_line, + const std::shared_ptr& parent) + : common::process(io_context, logger, cmd_line), _parent(parent) {} + +/** + * @brief start a new process, if a previous one is already running, it's killed + * + * @param running_index + */ +void detail::process::start(unsigned running_index) { + _process_ended = false; + _stdout_eof = false; + _running_index = running_index; + _stdout.clear(); + common::process::start_process(); +} + +/** + * @brief son process stdout read handler + * + * @param err + * @param nb_read + */ +void detail::process::on_stdout_read(const boost::system::error_code& err, + size_t nb_read) { + if (!err && nb_read > 0) { + _stdout.append(_stdout_read_buffer, nb_read); + } else if (err == asio::error::eof) { + _stdout_eof = true; + _on_completion(); + } + common::process::on_stdout_read(err, nb_read); +} + +/** + * @brief son process stderr read handler + * + * @param err + * @param nb_read + */ +void detail::process::on_stderr_read(const boost::system::error_code& err, + size_t nb_read) { + if (!err) { + SPDLOG_LOGGER_ERROR(_logger, "process error: {}", + std::string_view(_stderr_read_buffer, nb_read)); + } + common::process::on_stderr_read(err, nb_read); +} + +/** + * @brief called when son process ends + * + * @param err + * @param raw_exit_status + */ +void detail::process::on_process_end(const boost::system::error_code& err, + int raw_exit_status) { + if (err) { + _stdout += fmt::format("fail to execute process {} : {}", get_exe_path(), + err.message()); + } + common::process::on_process_end(err, raw_exit_status); + _process_ended = true; + _on_completion(); +} + +/** + * @brief if both stdout read and process are terminated, we call + * check_exec::on_completion + * + */ +void detail::process::_on_completion() { + if (_stdout_eof && _process_ended) { + std::shared_ptr parent = _parent.lock(); + if (parent) { + parent->on_completion(_running_index); + } + } +} + +/****************************************************************** + * check_exec + ******************************************************************/ + +check_exec::check_exec(const std::shared_ptr& io_context, + const std::shared_ptr& logger, + time_point exp, + const std::string& serv, + const std::string& cmd_name, + const std::string& cmd_line, + const engine_to_agent_request_ptr& cnf, + check::completion_handler&& handler) + : check(io_context, + logger, + exp, + serv, + cmd_name, + cmd_line, + cnf, + std::move(handler)) {} + +/** + * @brief create and initialize a check_exec object (don't use constructor) + * + * @tparam handler_type + * @param io_context + * @param logger + * @param exp start expected + * @param serv + * @param cmd_name + * @param cmd_line + * @param cnf agent configuration + * @param handler completion handler + * @return std::shared_ptr + */ +std::shared_ptr check_exec::load( + const std::shared_ptr& io_context, + const std::shared_ptr& logger, + time_point exp, + const std::string& serv, + const std::string& cmd_name, + const std::string& cmd_line, + const engine_to_agent_request_ptr& cnf, + check::completion_handler&& handler) { + std::shared_ptr ret = + std::make_shared(io_context, logger, exp, serv, cmd_name, + cmd_line, cnf, std::move(handler)); + ret->_init(); + return ret; +} + +/** + * @brief to call after construction + * constructor mustn't be called, use check_exec::load instead + * + */ +void check_exec::_init() { + try { + _process = std::make_shared( + _io_context, _logger, get_command_line(), + std::static_pointer_cast(shared_from_this())); + } catch (const std::exception& e) { + SPDLOG_LOGGER_ERROR(_logger, "fail to create process of cmd_line '{}' : {}", + get_command_line(), e.what()); + } +} + +/** + * @brief start a check, completion handler is always called asynchronously even + * in case of failure + * + * @param timeout + */ +void check_exec::start_check(const duration& timeout) { + check::start_check(timeout); + if (!_process) { + _io_context->post([me = check::shared_from_this(), + start_check_index = _get_running_check_index()]() { + me->on_completion(start_check_index, 3, + std::list(), + {"empty command"}); + }); + } + + try { + _process->start(_get_running_check_index()); + } catch (const boost::system::system_error& e) { + SPDLOG_LOGGER_ERROR(_logger, " serv {} fail to execute {}: {}", + get_service(), get_command_line(), e.code().message()); + _io_context->post([me = check::shared_from_this(), + start_check_index = _get_running_check_index(), e]() { + me->on_completion( + start_check_index, 3, std::list(), + {fmt::format("Fail to execute {} : {}", me->get_command_line(), + e.code().message())}); + }); + } catch (const std::exception& e) { + SPDLOG_LOGGER_ERROR(_logger, " serv {} fail to execute {}: {}", + get_service(), get_command_line(), e.what()); + _io_context->post([me = check::shared_from_this(), + start_check_index = _get_running_check_index(), e]() { + me->on_completion(start_check_index, 3, + std::list(), + {fmt::format("Fail to execute {} : {}", + me->get_command_line(), e.what())}); + }); + } +} + +/** + * @brief process is killed in case of timeout and handler is called + * + * @param err + * @param start_check_index + */ +void check_exec::_timeout_timer_handler(const boost::system::error_code& err, + unsigned start_check_index) { + if (err) { + return; + } + if (start_check_index == _get_running_check_index()) { + check::_timeout_timer_handler(err, start_check_index); + _process->kill(); + } +} + +/** + * @brief called on process completion + * + * @param running_index + */ +void check_exec::on_completion(unsigned running_index) { + if (running_index != _get_running_check_index()) { + return; + } + + std::list outputs; + std::list perfs; + + // split multi line output + outputs = absl::StrSplit(_process->get_stdout(), '\n', absl::SkipEmpty()); + if (!outputs.empty()) { + const std::string& first_line = *outputs.begin(); + size_t pipe_pos = first_line.find('|'); + if (pipe_pos != std::string::npos) { + std::string perfdatas = outputs.begin()->substr(pipe_pos + 1); + boost::trim(perfdatas); + perfs = com::centreon::common::perfdata::parse_perfdata( + 0, 0, perfdatas.c_str(), _logger); + } + } + check::on_completion(running_index, _process->get_exit_status(), perfs, + outputs); +} diff --git a/agent/src/config.cc b/agent/src/config.cc index b47681037b9..cd46ce23742 100644 --- a/agent/src/config.cc +++ b/agent/src/config.cc @@ -26,7 +26,7 @@ using namespace com::centreon::agent; using com::centreon::common::rapidjson_helper; -static constexpr std::string_view _config_schema(R"( +const std::string_view config::config_schema(R"( { "$schema": "http://json-schema.org/draft-04/schema#", "title": "agent config", @@ -100,7 +100,7 @@ static constexpr std::string_view _config_schema(R"( )"); config::config(const std::string& path) { - static common::json_validator validator(_config_schema); + static common::json_validator validator(config_schema); rapidjson::Document file_content_d; try { file_content_d = rapidjson_helper::read_from_file(path); @@ -136,13 +136,13 @@ config::config(const std::string& path) { _log_files_max_size = json_config.get_unsigned("log_files_max_size", 0); _log_files_max_number = json_config.get_unsigned("log_files_max_number", 0); _encryption = json_config.get_bool("encryption", false); - _certificate_file = json_config.get_string("certificate_file", ""); - _private_key_file = json_config.get_string("private_key_file", ""); - _ca_certificate_file = json_config.get_string("ca_certificate_file", ""); + _public_cert_file = json_config.get_string("public_cert", ""); + _private_key_file = json_config.get_string("private_key", ""); + _ca_certificate_file = json_config.get_string("ca_certificate", ""); _ca_name = json_config.get_string("ca_name", ""); _host = json_config.get_string("host", ""); if (_host.empty()) { _host = boost::asio::ip::host_name(); } _reverse_connection = json_config.get_bool("reverse_connection", false); -} \ No newline at end of file +} diff --git a/agent/src/main.cc b/agent/src/main.cc index d78e1dc80ba..562a1f05e46 100644 --- a/agent/src/main.cc +++ b/agent/src/main.cc @@ -71,8 +71,7 @@ static std::string read_file(const std::string& file_path) { return ss.str(); } } catch (const std::exception& e) { - SPDLOG_LOGGER_ERROR(g_logger, "{} fail to read {}: {}", file_path, - e.what()); + SPDLOG_LOGGER_ERROR(g_logger, "fail to read {}: {}", file_path, e.what()); } return ""; } @@ -85,6 +84,14 @@ int main(int argc, char* argv[]) { return 1; } + if (!strcmp(argv[1], "--help")) { + SPDLOG_INFO( + "Usage: {} \nSchema of the config " + "file is:\n{}", + argv[0], config::config_schema); + return 1; + } + std::unique_ptr conf; try { conf = std::make_unique(argv[1]); @@ -131,6 +138,10 @@ int main(int argc, char* argv[]) { g_logger->set_level(conf->get_log_level()); + g_logger->flush_on(spdlog::level::warn); + + spdlog::flush_every(std::chrono::seconds(1)); + SPDLOG_LOGGER_INFO(g_logger, "centreon-monitoring-agent start, you can decrease log " "verbosity by kill -USR1 {} or increase by kill -USR2 {}", @@ -145,7 +156,7 @@ int main(int argc, char* argv[]) { grpc_conf = std::make_shared( conf->get_endpoint(), conf->use_encryption(), - read_file(conf->get_certificate_file()), + read_file(conf->get_public_cert_file()), read_file(conf->get_private_key_file()), read_file(conf->get_ca_certificate_file()), conf->get_ca_name(), true, 30); @@ -165,4 +176,4 @@ int main(int argc, char* argv[]) { SPDLOG_LOGGER_INFO(g_logger, "centreon-monitoring-agent end"); return 0; -} \ No newline at end of file +} diff --git a/agent/src/scheduler.cc b/agent/src/scheduler.cc new file mode 100644 index 00000000000..207ef35721e --- /dev/null +++ b/agent/src/scheduler.cc @@ -0,0 +1,485 @@ +/** + * Copyright 2024 Centreon + * + * This file is part of Centreon Agent. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ + +#include "scheduler.hh" + +using namespace com::centreon::agent; + +/** + * @brief to call after creation + * it create a default configuration with no check and start send timer + */ +void scheduler::_start() { + _init_export_request(); + _next_send_time_point = std::chrono::system_clock::now(); + update(_conf); + _start_send_timer(); + _start_check_timer(); +} + +/** + * @brief start periodic metric sent to engine + * + */ +void scheduler::_start_send_timer() { + _next_send_time_point += + std::chrono::seconds(_conf->config().export_period()); + _send_timer.expires_at(_next_send_time_point); + _send_timer.async_wait( + [me = shared_from_this()](const boost::system::error_code& err) { + me->_send_timer_handler(err); + }); +} + +/** + * @brief send all check results to engine + * + * @param err + */ +void scheduler::_send_timer_handler(const boost::system::error_code& err) { + if (err) { + return; + } + if (_current_request->mutable_otel_request()->resource_metrics_size() > 0) { + _metric_sender(_current_request); + _init_export_request(); + } + _start_send_timer(); +} + +/** + * @brief create export request and fill some attributes + * + */ +void scheduler::_init_export_request() { + _current_request = std::make_shared(); + _serv_to_scope_metrics.clear(); +} + +/** + * @brief create a default empty configuration to scheduler + * + */ +std::shared_ptr +scheduler::default_config() { + std::shared_ptr ret = + std::make_shared(); + ret->mutable_config()->set_check_interval(1); + ret->mutable_config()->set_export_period(1); + ret->mutable_config()->set_max_concurrent_checks(10); + return ret; +} + +/** + * @brief start check timer. + * When it will expire, we will call every check whose start_expected is lower + * than the actual time point + * if no check available, we start timer for 100ms + * + */ +void scheduler::_start_check_timer() { + if (_check_queue.empty() || + _active_check >= _conf->config().max_concurrent_checks()) { + _check_timer.expires_from_now(std::chrono::milliseconds(100)); + } else { + _check_timer.expires_at((*_check_queue.begin())->get_start_expected()); + } + _check_timer.async_wait( + [me = shared_from_this()](const boost::system::error_code& err) { + me->_check_timer_handler(err); + }); +} + +/** + * @brief check timer handler + * + * @param err + */ +void scheduler::_check_timer_handler(const boost::system::error_code& err) { + if (err) { + return; + } + _start_waiting_check(); + _start_check_timer(); +} + +/** + * @brief start all waiting checks, no more concurrent checks than + * max_concurrent_checks + * check started are removed from queue and will be inserted once completed + */ +void scheduler::_start_waiting_check() { + time_point now = std::chrono::system_clock::now(); + if (!_check_queue.empty()) { + for (check_queue::iterator to_check = _check_queue.begin(); + !_check_queue.empty() && to_check != _check_queue.end() && + (*to_check)->get_start_expected() <= now && + _active_check < _conf->config().max_concurrent_checks();) { + _start_check(*to_check); + to_check = _check_queue.erase(to_check); + } + } +} + +/** + * @brief called when we receive a new configuration + * It initialize check queue and restart all checks schedule + * running checks stay alive but their completion will not be handled + * We compute start_expected of checks in order to spread checks over + * check_interval + * @param conf + */ +void scheduler::update(const engine_to_agent_request_ptr& conf) { + _check_queue.clear(); + _active_check = 0; + size_t nb_check = conf->config().services().size(); + + if (conf->config().check_interval() <= 0) { + SPDLOG_LOGGER_ERROR( + _logger, "check_interval cannot be null => no configuration update"); + return; + } + + SPDLOG_LOGGER_INFO(_logger, "schedule {} checks to execute in {}s", nb_check, + conf->config().check_interval()); + + if (nb_check > 0) { + duration check_interval = + std::chrono::microseconds(conf->config().check_interval() * 1000000) / + nb_check; + + time_point next = std::chrono::system_clock::now(); + for (const auto& serv : conf->config().services()) { + if (_logger->level() == spdlog::level::trace) { + SPDLOG_LOGGER_TRACE( + _logger, "check expected to start at {} for service {} command {}", + next, serv.service_description(), serv.command_line()); + } else { + SPDLOG_LOGGER_TRACE(_logger, + "check expected to start at {} for service {}", + next, serv.service_description()); + } + _check_queue.emplace(_check_builder( + _io_context, _logger, next, serv.service_description(), + serv.command_name(), serv.command_line(), conf, + [me = shared_from_this()]( + const std::shared_ptr& check, unsigned status, + const std::list& perfdata, + const std::list& outputs) { + me->_check_handler(check, status, perfdata, outputs); + })); + next += check_interval; + } + } + + _conf = conf; +} + +/** + * @brief start a check + * + * @param check + */ +void scheduler::_start_check(const check::pointer& check) { + ++_active_check; + if (_logger->level() <= spdlog::level::trace) { + SPDLOG_LOGGER_TRACE(_logger, "start check for service {} command {}", + check->get_service(), check->get_command_line()); + } else { + SPDLOG_LOGGER_DEBUG(_logger, "start check for service {}", + check->get_service()); + } + check->start_check(std::chrono::seconds(_conf->config().check_timeout())); +} + +/** + * @brief completion check handler + * if conf has been updated during check, it does nothing + * + * @param check + * @param status + * @param perfdata + * @param outputs + */ +void scheduler::_check_handler( + const check::pointer& check, + unsigned status, + const std::list& perfdata, + const std::list& outputs) { + SPDLOG_LOGGER_TRACE(_logger, "end check for service {} command {}", + check->get_service(), check->get_command_line()); + + // conf has changed => no repush for next check + if (check->get_conf() != _conf) { + return; + } + + if (_conf->config().use_exemplar()) { + _store_result_in_metrics_and_exemplars(check, status, perfdata, outputs); + } else { + _store_result_in_metrics(check, status, perfdata, outputs); + } + + --_active_check; + + if (_alive) { + // repush for next check + check->add_duration_to_start_expected( + std::chrono::seconds(_conf->config().check_interval())); + + _check_queue.insert(check); + // we have decreased _active_check, so we can launch another check + _start_waiting_check(); + } +} + +/** + * @brief to call on process termination or accepted connection error + * + */ +void scheduler::stop() { + if (_alive) { + _alive = false; + _send_timer.cancel(); + _check_timer.cancel(); + } +} + +/** + * @brief stores results in telegraf manner + * + * @param check + * @param status + * @param perfdata + * @param outputs + */ +void scheduler::_store_result_in_metrics( + const check::pointer& check, + unsigned status, + const std::list& perfdata, + const std::list& outputs) { + // auto scope_metrics = + // get_scope_metrics(check->get_host(), check->get_service()); + // unsigned now = std::chrono::duration_cast( + // std::chrono::system_clock::now().time_since_epoch()) + // .count(); + + // auto state_metrics = scope_metrics->add_metrics(); + // state_metrics->set_name(check->get_command_name() + "_state"); + // if (!outputs.empty()) { + // const std::string& first_line = *outputs.begin(); + // size_t pipe_pos = first_line.find('|'); + // state_metrics->set_description(pipe_pos != std::string::npos + // ? first_line.substr(0, pipe_pos) + // : first_line); + // } + // auto data_point = state_metrics->mutable_gauge()->add_data_points(); + // data_point->set_time_unix_nano(now); + // data_point->set_as_int(status); + + // we aggregate perfdata results by type (min, max, ) +} + +/** + * @brief store results with centreon sauce + * + * @param check + * @param status + * @param perfdata + * @param outputs + */ +void scheduler::_store_result_in_metrics_and_exemplars( + const check::pointer& check, + unsigned status, + const std::list& perfdata, + const std::list& outputs) { + auto& scope_metrics = _get_scope_metrics(check->get_service()); + uint64_t now = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()) + .count(); + + auto state_metrics = _get_metric(scope_metrics, "status"); + if (!outputs.empty()) { + const std::string& first_line = *outputs.begin(); + size_t pipe_pos = first_line.find('|'); + state_metrics->set_description(pipe_pos != std::string::npos + ? first_line.substr(0, pipe_pos) + : first_line); + } + auto data_point = state_metrics->mutable_gauge()->add_data_points(); + data_point->set_time_unix_nano(now); + data_point->set_as_int(status); + + for (const com::centreon::common::perfdata& perf : perfdata) { + _add_metric_to_scope(now, perf, scope_metrics); + } +} + +/** + * @brief metrics are grouped by host service + * (one resource_metrics by host serv pair) + * + * @param service + * @return scheduler::scope_metric_request& + */ +scheduler::scope_metric_request& scheduler::_get_scope_metrics( + const std::string& service) { + auto exist = _serv_to_scope_metrics.find(service); + if (exist != _serv_to_scope_metrics.end()) { + return exist->second; + } + ::opentelemetry::proto::metrics::v1::ResourceMetrics* new_res = + _current_request->mutable_otel_request()->add_resource_metrics(); + + auto* host_attrib = new_res->mutable_resource()->add_attributes(); + host_attrib->set_key("host.name"); + host_attrib->mutable_value()->set_string_value(_supervised_host); + auto* serv_attrib = new_res->mutable_resource()->add_attributes(); + serv_attrib->set_key("service.name"); + serv_attrib->mutable_value()->set_string_value(service); + + ::opentelemetry::proto::metrics::v1::ScopeMetrics* new_scope = + new_res->add_scope_metrics(); + + scope_metric_request to_insert; + to_insert.scope_metric = new_scope; + + return _serv_to_scope_metrics.emplace(service, to_insert).first->second; +} + +/** + * @brief one metric by metric name (can contains several datapoints in case of + * multiple checks during send period ) + * + * @param scope_metric + * @param metric_name + * @return ::opentelemetry::proto::metrics::v1::Metric* + */ +::opentelemetry::proto::metrics::v1::Metric* scheduler::_get_metric( + scope_metric_request& scope_metric, + const std::string& metric_name) { + auto exist = scope_metric.metrics.find(metric_name); + if (exist != scope_metric.metrics.end()) { + return exist->second; + } + + ::opentelemetry::proto::metrics::v1::Metric* new_metric = + scope_metric.scope_metric->add_metrics(); + new_metric->set_name(metric_name); + + scope_metric.metrics.emplace(metric_name, new_metric); + + return new_metric; +} + +/** + * @brief add a perfdata to metric + * + * @param now + * @param perf + * @param scope_metric + */ +void scheduler::_add_metric_to_scope( + uint64_t now, + const com::centreon::common::perfdata& perf, + scope_metric_request& scope_metric) { + auto metric = _get_metric(scope_metric, perf.name()); + metric->set_unit(perf.unit()); + auto data_point = metric->mutable_gauge()->add_data_points(); + data_point->set_as_int(perf.value()); + data_point->set_time_unix_nano(now); + switch (perf.value_type()) { + case com::centreon::common::perfdata::counter: { + auto attrib_type = data_point->add_attributes(); + attrib_type->set_key("counter"); + break; + } + case com::centreon::common::perfdata::derive: { + auto attrib_type = data_point->add_attributes(); + attrib_type->set_key("derive"); + break; + } + case com::centreon::common::perfdata::absolute: { + auto attrib_type = data_point->add_attributes(); + attrib_type->set_key("absolute"); + break; + } + case com::centreon::common::perfdata::automatic: { + auto attrib_type = data_point->add_attributes(); + attrib_type->set_key("auto"); + break; + } + } + if (perf.critical() <= std::numeric_limits::max()) { + _add_exemplar(perf.critical_mode() ? "crit_ge" : "crit_gt", perf.critical(), + *data_point); + } + if (perf.critical_low() <= std::numeric_limits::max()) { + _add_exemplar(perf.critical_mode() ? "crit_le" : "crit_lt", + perf.critical_low(), *data_point); + } + if (perf.warning() <= std::numeric_limits::max()) { + _add_exemplar(perf.warning_mode() ? "warn_ge" : "warn_gt", perf.warning(), + *data_point); + } + if (perf.warning_low() <= std::numeric_limits::max()) { + _add_exemplar(perf.critical_mode() ? "warn_le" : "warn_lt", + perf.warning_low(), *data_point); + } + if (perf.min() <= std::numeric_limits::max()) { + _add_exemplar("min", perf.min(), *data_point); + } + if (perf.max() <= std::numeric_limits::max()) { + _add_exemplar("max", perf.max(), *data_point); + } +} + +/** + * @brief add an exemplar to metric such as crit_le, min, max.. + * + * @param label + * @param value + * @param data_point + */ +void scheduler::_add_exemplar( + const char* label, + double value, + ::opentelemetry::proto::metrics::v1::NumberDataPoint& data_point) { + auto exemplar = data_point.add_exemplars(); + auto attrib = exemplar->add_filtered_attributes(); + attrib->set_key(label); + exemplar->set_as_double(value); +} + +/** + * @brief add an exemplar to metric such as crit_le, min, max.. + * + * @param label + * @param value + * @param data_point + */ +void scheduler::_add_exemplar( + const char* label, + bool value, + ::opentelemetry::proto::metrics::v1::NumberDataPoint& data_point) { + auto exemplar = data_point.add_exemplars(); + auto attrib = exemplar->add_filtered_attributes(); + attrib->set_key(label); + exemplar->set_as_int(value); +} diff --git a/agent/test/CMakeLists.txt b/agent/test/CMakeLists.txt index c66ffde4ece..c677ecc9c93 100644 --- a/agent/test/CMakeLists.txt +++ b/agent/test/CMakeLists.txt @@ -20,6 +20,9 @@ add_executable(ut_agent config_test.cc + check_test.cc + check_exec_test.cc + scheduler_test.cc test_main.cc ${TESTS_SOURCES}) @@ -37,6 +40,7 @@ set_target_properties( target_link_libraries(ut_agent PRIVATE centagent_lib centreon_common + centreon_process GTest::gtest GTest::gtest_main GTest::gmock diff --git a/agent/test/check_exec_test.cc b/agent/test/check_exec_test.cc new file mode 100644 index 00000000000..34c050f48e0 --- /dev/null +++ b/agent/test/check_exec_test.cc @@ -0,0 +1,113 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#include + +#include "check_exec.hh" + +using namespace com::centreon::agent; + +extern std::shared_ptr g_io_context; + +static const std::string serv("serv"); +static const std::string cmd_name("command"); +static std::string command_line; + +TEST(check_exec_test, echo) { + command_line = "/bin/echo hello toto"; + int status; + std::list outputs; + std::condition_variable cond; + std::shared_ptr check = check_exec::load( + g_io_context, spdlog::default_logger(), time_point(), serv, cmd_name, + command_line, engine_to_agent_request_ptr(), + [&](const std::shared_ptr& caller, + int statuss, + const std::list& perfdata, + const std::list& output) { + status = statuss; + outputs = output; + cond.notify_one(); + }); + check->start_check(std::chrono::seconds(1)); + + std::mutex mut; + std::unique_lock l(mut); + cond.wait(l); + ASSERT_EQ(status, 0); + ASSERT_EQ(outputs.size(), 1); + ASSERT_EQ(*outputs.begin(), "hello toto"); +} + +TEST(check_exec_test, timeout) { + command_line = "/bin/sleep 5"; + int status; + std::list outputs; + std::condition_variable cond; + std::shared_ptr check = check_exec::load( + g_io_context, spdlog::default_logger(), time_point(), serv, cmd_name, + command_line, engine_to_agent_request_ptr(), + [&](const std::shared_ptr& caller, + int statuss, + const std::list& perfdata, + const std::list& output) { + status = statuss; + outputs = output; + cond.notify_one(); + }); + check->start_check(std::chrono::seconds(1)); + + std::mutex mut; + std::unique_lock l(mut); + cond.wait(l); + ASSERT_EQ(status, 3); + ASSERT_EQ(outputs.size(), 1); + ASSERT_EQ(*outputs.begin(), "Timeout at execution of /bin/sleep 5"); +} + +TEST(check_exec_test, bad_command) { + command_line = "/usr/bad_path/turlututu titi toto"; + int status; + std::list outputs; + std::condition_variable cond; + std::mutex mut; + std::shared_ptr check = check_exec::load( + g_io_context, spdlog::default_logger(), time_point(), serv, cmd_name, + command_line, engine_to_agent_request_ptr(), + [&](const std::shared_ptr& caller, + int statuss, + const std::list& perfdata, + const std::list& output) { + { + std::lock_guard l(mut); + status = statuss; + outputs = output; + } + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + cond.notify_one(); + }); + check->start_check(std::chrono::seconds(1)); + + std::unique_lock l(mut); + cond.wait(l); + ASSERT_EQ(status, 3); + ASSERT_EQ(outputs.size(), 1); + ASSERT_EQ(*outputs.begin(), + "Fail to execute /usr/bad_path/turlututu titi toto : No such file " + "or directory"); +} diff --git a/agent/test/check_test.cc b/agent/test/check_test.cc new file mode 100644 index 00000000000..1a09b0761cf --- /dev/null +++ b/agent/test/check_test.cc @@ -0,0 +1,141 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#include + +#include "check.hh" + +using namespace com::centreon::agent; + +extern std::shared_ptr g_io_context; + +class dummy_check : public check { + duration _command_duration; + asio::system_timer _command_timer; + + public: + void start_check(const duration& timeout) override { + check::start_check(timeout); + _command_timer.expires_from_now(_command_duration); + _command_timer.async_wait([me = shared_from_this(), this, + running_index = _get_running_check_index()]( + const boost::system::error_code& err) { + if (err) { + return; + } + on_completion(running_index, 1, + std::list(), + {"output dummy_check of " + get_command_line()}); + }); + } + + template + dummy_check(const std::string& serv, + const std::string& command_name, + const std::string& command_line, + const duration& command_duration, + handler_type&& handler) + : check(g_io_context, + spdlog::default_logger(), + std::chrono::system_clock::now(), + serv, + command_name, + command_line, + nullptr, + handler), + _command_duration(command_duration), + _command_timer(*g_io_context) {} +}; + +static std::string serv("my_serv"); +static std::string cmd_name("my_command_name"); +static std::string cmd_line("my_command_line"); + +TEST(check_test, timeout) { + unsigned status = 0; + std::string output; + std::mutex cond_m; + std::condition_variable cond; + unsigned handler_call_cpt = 0; + + std::shared_ptr checker = std::make_shared( + serv, cmd_name, cmd_line, std::chrono::milliseconds(500), + [&status, &output, &handler_call_cpt, &cond]( + const std::shared_ptr&, unsigned statuss, + const std::list& perfdata, + const std::list& outputs) { + status = statuss; + if (outputs.size() == 1) { + output = *outputs.begin(); + } + ++handler_call_cpt; + cond.notify_all(); + }); + + checker->start_check(std::chrono::milliseconds(100)); + + std::unique_lock l(cond_m); + cond.wait(l); + + ASSERT_EQ(status, 3); + ASSERT_EQ(handler_call_cpt, 1); + ASSERT_EQ(output, "Timeout at execution of my_command_line"); + + // completion handler not called twice + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + ASSERT_EQ(status, 3); + ASSERT_EQ(handler_call_cpt, 1); + ASSERT_EQ(output, "Timeout at execution of my_command_line"); +} + +TEST(check_test, no_timeout) { + unsigned status = 0; + std::string output; + std::mutex cond_m; + std::condition_variable cond; + unsigned handler_call_cpt = 0; + + std::shared_ptr checker = std::make_shared( + serv, cmd_name, cmd_line, std::chrono::milliseconds(100), + [&status, &output, &handler_call_cpt, &cond]( + const std::shared_ptr&, unsigned statuss, + const std::list& perfdata, + const std::list& outputs) { + status = statuss; + if (outputs.size() == 1) { + output = *outputs.begin(); + } + ++handler_call_cpt; + cond.notify_all(); + }); + + checker->start_check(std::chrono::milliseconds(200)); + + std::unique_lock l(cond_m); + cond.wait(l); + + ASSERT_EQ(status, 1); + ASSERT_EQ(handler_call_cpt, 1); + ASSERT_EQ(output, "output dummy_check of my_command_line"); + + // completion handler not called twice + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + ASSERT_EQ(status, 1); + ASSERT_EQ(handler_call_cpt, 1); + ASSERT_EQ(output, "output dummy_check of my_command_line"); +} \ No newline at end of file diff --git a/agent/test/scheduler_test.cc b/agent/test/scheduler_test.cc new file mode 100644 index 00000000000..ccd9f47a7fc --- /dev/null +++ b/agent/test/scheduler_test.cc @@ -0,0 +1,450 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#include + +#include "scheduler.hh" + +extern std::shared_ptr g_io_context; +using namespace com::centreon::agent; + +class tempo_check : public check { + asio::system_timer _completion_timer; + int _command_exit_status; + duration _completion_delay; + + public: + static std::vector> check_starts; + static std::mutex check_starts_m; + + static uint64_t completion_time; + + tempo_check(const std::shared_ptr& io_context, + const std::shared_ptr& logger, + time_point exp, + const std::string& serv, + const std::string& cmd_name, + const std::string& cmd_line, + const engine_to_agent_request_ptr& cnf, + int command_exit_status, + duration completion_delay, + check::completion_handler&& handler) + : check(io_context, + logger, + exp, + serv, + cmd_name, + cmd_line, + cnf, + std::move(handler)), + _completion_timer(*io_context), + _command_exit_status(command_exit_status), + _completion_delay(completion_delay) {} + + void start_check(const duration& timeout) override { + { + std::lock_guard l(check_starts_m); + check_starts.emplace_back(this, std::chrono::system_clock::now()); + } + check::start_check(timeout); + _completion_timer.expires_from_now(_completion_delay); + _completion_timer.async_wait([me = shared_from_this(), this, + check_running_index = + _get_running_check_index()]( + const boost::system::error_code& err) { + SPDLOG_TRACE("end of completion timer for serv {}", get_service()); + me->on_completion( + check_running_index, _command_exit_status, + com::centreon::common::perfdata::parse_perfdata( + 0, 0, + "rta=0,031ms;200,000;500,000;0; pl=0%;40;80;; rtmax=0,109ms;;;; " + "rtmin=0,011ms;;;;", + _logger), + {fmt::format("Command OK: {}", me->get_command_line())}); + completion_time = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()) + .count(); + }); + } +}; + +std::vector> tempo_check::check_starts; +std::mutex tempo_check::check_starts_m; +uint64_t tempo_check::completion_time; + +class scheduler_test : public ::testing::Test { + public: + static void SetUpTestSuite() { + spdlog::default_logger()->set_level(spdlog::level::trace); + } + + std::shared_ptr create_conf( + unsigned nb_serv, + unsigned second_check_period, + unsigned export_period, + unsigned max_concurent_check, + unsigned check_timeout); +}; + +std::shared_ptr +scheduler_test::create_conf(unsigned nb_serv, + unsigned second_check_period, + unsigned export_period, + unsigned max_concurent_check, + unsigned check_timeout) { + std::shared_ptr conf = + std::make_shared(); + auto cnf = conf->mutable_config(); + cnf->set_check_interval(second_check_period); + cnf->set_export_period(export_period); + cnf->set_max_concurrent_checks(max_concurent_check); + cnf->set_check_timeout(check_timeout); + cnf->set_use_exemplar(true); + for (unsigned serv_index = 0; serv_index < nb_serv; ++serv_index) { + auto serv = cnf->add_services(); + serv->set_service_description(fmt::format("serv{}", serv_index + 1)); + serv->set_command_name(fmt::format("command{}", serv_index + 1)); + serv->set_command_line("/usr/bin/ls"); + } + return conf; +} + +TEST_F(scheduler_test, no_config) { + std::shared_ptr sched = scheduler::load( + g_io_context, spdlog::default_logger(), "my_host", + scheduler::default_config(), + [](const std::shared_ptr&) {}, + [](const std::shared_ptr&, + const std::shared_ptr&, time_point /* start expected*/, + const std::string& /*service*/, const std::string& /*cmd_name*/, + const std::string& /*cmd_line*/, + const engine_to_agent_request_ptr& /*engine to agent request*/, + check::completion_handler&&) { return std::shared_ptr(); }); + + std::weak_ptr weak_shed(sched); + sched.reset(); + + // scheduler must be owned by asio + ASSERT_TRUE(weak_shed.lock()); + + weak_shed.lock()->stop(); + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + + ASSERT_FALSE(weak_shed.lock()); +} + +TEST_F(scheduler_test, correct_schedule) { + std::shared_ptr sched = scheduler::load( + g_io_context, spdlog::default_logger(), "my_host", + create_conf(20, 1, 1, 50, 1), + [](const std::shared_ptr&) {}, + [](const std::shared_ptr& io_context, + const std::shared_ptr& logger, + time_point start_expected, const std::string& service, + const std::string& cmd_name, const std::string& cmd_line, + const engine_to_agent_request_ptr& engine_to_agent_request, + check::completion_handler&& handler) { + return std::make_shared( + io_context, logger, start_expected, service, cmd_name, cmd_line, + engine_to_agent_request, 0, std::chrono::milliseconds(50), + std::move(handler)); + }); + + { + std::lock_guard l(tempo_check::check_starts_m); + tempo_check::check_starts.clear(); + } + + std::this_thread::sleep_for(std::chrono::milliseconds(1100)); + + // we have 2 * 10 = 20 checks spread over 1 second + duration expected_interval = std::chrono::milliseconds(50); + + { + std::lock_guard l(tempo_check::check_starts_m); + ASSERT_GE(tempo_check::check_starts.size(), 20); + bool first = true; + std::pair previous; + for (const auto& check_time : tempo_check::check_starts) { + if (first) { + first = false; + } else { + ASSERT_NE(previous.first, check_time.first); + ASSERT_GT((check_time.second - previous.second), + expected_interval - std::chrono::milliseconds(1)); + ASSERT_LT((check_time.second - previous.second), + expected_interval + std::chrono::milliseconds(1)); + } + previous = check_time; + } + } + + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); + + { + std::lock_guard l(tempo_check::check_starts_m); + ASSERT_GE(tempo_check::check_starts.size(), 40); + bool first = true; + std::pair previous; + for (const auto& check_time : tempo_check::check_starts) { + if (first) { + first = false; + } else { + ASSERT_NE(previous.first, check_time.first); + ASSERT_TRUE((check_time.second - previous.second) > + expected_interval - std::chrono::milliseconds(1)); + ASSERT_TRUE((check_time.second - previous.second) < + expected_interval + std::chrono::milliseconds(1)); + } + previous = check_time; + } + } + + sched->stop(); +} + +TEST_F(scheduler_test, time_out) { + std::shared_ptr exported_request; + std::condition_variable export_cond; + uint64_t expected_completion_time = + std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()) + .count(); + std::mutex m; + std::shared_ptr sched = scheduler::load( + g_io_context, spdlog::default_logger(), "my_host", + create_conf(1, 1, 1, 1, 1), + [&](const std::shared_ptr& req) { + { + std::lock_guard l(m); + exported_request = req; + } + export_cond.notify_all(); + }, + [](const std::shared_ptr& io_context, + const std::shared_ptr& logger, + time_point start_expected, const std::string& service, + const std::string& cmd_name, const std::string& cmd_line, + const engine_to_agent_request_ptr& engine_to_agent_request, + check::completion_handler&& handler) { + return std::make_shared( + io_context, logger, start_expected, service, cmd_name, cmd_line, + engine_to_agent_request, 0, std::chrono::milliseconds(1500), + std::move(handler)); + }); + std::unique_lock l(m); + export_cond.wait(l); + + ASSERT_TRUE(exported_request); + ASSERT_EQ(exported_request->otel_request().resource_metrics_size(), 1); + const ::opentelemetry::proto::metrics::v1::ResourceMetrics& res = + exported_request->otel_request().resource_metrics()[0]; + const auto& res_attrib = res.resource().attributes(); + ASSERT_EQ(res_attrib.size(), 2); + ASSERT_EQ(res_attrib.at(0).key(), "host.name"); + ASSERT_EQ(res_attrib.at(0).value().string_value(), "my_host"); + ASSERT_EQ(res_attrib.at(1).key(), "service.name"); + ASSERT_EQ(res_attrib.at(1).value().string_value(), "serv1"); + ASSERT_EQ(res.scope_metrics_size(), 1); + const ::opentelemetry::proto::metrics::v1::ScopeMetrics& scope_metrics = + res.scope_metrics()[0]; + ASSERT_EQ(scope_metrics.metrics_size(), 1); + const ::opentelemetry::proto::metrics::v1::Metric metric = + scope_metrics.metrics()[0]; + ASSERT_EQ(metric.name(), "status"); + ASSERT_EQ(metric.description(), "Timeout at execution of /usr/bin/ls"); + ASSERT_EQ(metric.gauge().data_points_size(), 1); + const auto& data_point = metric.gauge().data_points()[0]; + ASSERT_EQ(data_point.as_int(), 3); + // timeout 1s + ASSERT_GE(data_point.time_unix_nano(), expected_completion_time + 1000000000); + ASSERT_LE(data_point.time_unix_nano(), expected_completion_time + 1500000000); + + sched->stop(); +} + +TEST_F(scheduler_test, correct_output_examplar) { + std::shared_ptr exported_request; + std::condition_variable export_cond; + time_point now = std::chrono::system_clock::now(); + std::shared_ptr sched = scheduler::load( + g_io_context, spdlog::default_logger(), "my_host", + create_conf(2, 1, 2, 10, 1), + [&](const std::shared_ptr& req) { + exported_request = req; + export_cond.notify_all(); + }, + [](const std::shared_ptr& io_context, + const std::shared_ptr& logger, + time_point start_expected, const std::string& service, + const std::string& cmd_name, const std::string& cmd_line, + const engine_to_agent_request_ptr& engine_to_agent_request, + check::completion_handler&& handler) { + return std::make_shared( + io_context, logger, start_expected, service, cmd_name, cmd_line, + engine_to_agent_request, 0, std::chrono::milliseconds(10), + std::move(handler)); + }); + std::mutex m; + std::unique_lock l(m); + export_cond.wait(l); + + ASSERT_TRUE(exported_request); + + SPDLOG_INFO("export:{}", exported_request->otel_request().DebugString()); + + ASSERT_EQ(exported_request->otel_request().resource_metrics_size(), 2); + const ::opentelemetry::proto::metrics::v1::ResourceMetrics& res = + exported_request->otel_request().resource_metrics()[0]; + const auto& res_attrib = res.resource().attributes(); + ASSERT_EQ(res_attrib.size(), 2); + ASSERT_EQ(res_attrib.at(0).key(), "host.name"); + ASSERT_EQ(res_attrib.at(0).value().string_value(), "my_host"); + ASSERT_EQ(res_attrib.at(1).key(), "service.name"); + ASSERT_EQ(res_attrib.at(1).value().string_value(), "serv1"); + ASSERT_EQ(res.scope_metrics_size(), 1); + const ::opentelemetry::proto::metrics::v1::ScopeMetrics& scope_metrics = + res.scope_metrics()[0]; + ASSERT_GE(scope_metrics.metrics_size(), 5); + const ::opentelemetry::proto::metrics::v1::Metric metric = + scope_metrics.metrics()[0]; + ASSERT_EQ(metric.name(), "status"); + ASSERT_EQ(metric.description(), "Command OK: /usr/bin/ls"); + ASSERT_GE(metric.gauge().data_points_size(), 1); + const auto& data_point_state = metric.gauge().data_points()[0]; + ASSERT_EQ(data_point_state.as_int(), 0); + uint64_t first_time_point = data_point_state.time_unix_nano(); + + const ::opentelemetry::proto::metrics::v1::ResourceMetrics& res2 = + exported_request->otel_request().resource_metrics()[1]; + const auto& res_attrib2 = res2.resource().attributes(); + ASSERT_EQ(res_attrib2.size(), 2); + ASSERT_EQ(res_attrib2.at(0).key(), "host.name"); + ASSERT_EQ(res_attrib2.at(0).value().string_value(), "my_host"); + ASSERT_EQ(res_attrib2.at(1).key(), "service.name"); + ASSERT_EQ(res_attrib2.at(1).value().string_value(), "serv2"); + ASSERT_EQ(res2.scope_metrics_size(), 1); + + const ::opentelemetry::proto::metrics::v1::ScopeMetrics& scope_metrics2 = + res2.scope_metrics()[0]; + ASSERT_EQ(scope_metrics2.metrics_size(), 5); + const ::opentelemetry::proto::metrics::v1::Metric metric2 = + scope_metrics2.metrics()[0]; + ASSERT_EQ(metric2.name(), "status"); + ASSERT_EQ(metric2.description(), "Command OK: /usr/bin/ls"); + ASSERT_GE(metric2.gauge().data_points_size(), 1); + const auto& data_point_state2 = metric2.gauge().data_points()[0]; + ASSERT_EQ(data_point_state2.as_int(), 0); + + ASSERT_LE(first_time_point + 400000000, data_point_state2.time_unix_nano()); + ASSERT_GE(first_time_point + 600000000, data_point_state2.time_unix_nano()); + + sched->stop(); +} + +class concurent_check : public check { + asio::system_timer _completion_timer; + int _command_exit_status; + duration _completion_delay; + + public: + static std::set checked; + static std::set active_checks; + static unsigned max_active_check; + + concurent_check(const std::shared_ptr& io_context, + const std::shared_ptr& logger, + time_point exp, + const std::string& serv, + const std::string& cmd_name, + const std::string& cmd_line, + const engine_to_agent_request_ptr& cnf, + int command_exit_status, + duration completion_delay, + check::completion_handler&& handler) + : check(io_context, + logger, + exp, + serv, + cmd_name, + cmd_line, + cnf, + std::move(handler)), + _completion_timer(*io_context), + _command_exit_status(command_exit_status), + _completion_delay(completion_delay) {} + + void start_check(const duration& timeout) override { + check::start_check(timeout); + active_checks.insert(this); + if (active_checks.size() > max_active_check) { + max_active_check = active_checks.size(); + } + _completion_timer.expires_from_now(_completion_delay); + _completion_timer.async_wait([me = shared_from_this(), this, + check_running_index = + _get_running_check_index()]( + const boost::system::error_code& err) { + active_checks.erase(this); + checked.insert(this); + SPDLOG_TRACE("end of completion timer for serv {}", get_service()); + me->on_completion( + check_running_index, _command_exit_status, + com::centreon::common::perfdata::parse_perfdata( + 0, 0, + "rta=0,031ms;200,000;500,000;0; pl=0%;40;80;; rtmax=0,109ms;;;; " + "rtmin=0,011ms;;;;", + _logger), + {fmt::format("Command OK: {}", me->get_command_line())}); + }); + } +}; + +std::set concurent_check::checked; +std::set concurent_check::active_checks; +unsigned concurent_check::max_active_check; + +TEST_F(scheduler_test, max_concurent) { + std::shared_ptr sched = scheduler::load( + g_io_context, spdlog::default_logger(), "my_host", + create_conf(200, 1, 1, 10, 1), + [&](const std::shared_ptr& req) {}, + [](const std::shared_ptr& io_context, + const std::shared_ptr& logger, + time_point start_expected, const std::string& service, + const std::string& cmd_name, const std::string& cmd_line, + const engine_to_agent_request_ptr& engine_to_agent_request, + check::completion_handler&& handler) { + return std::make_shared( + io_context, logger, start_expected, service, cmd_name, cmd_line, + engine_to_agent_request, 0, std::chrono::milliseconds(75), + std::move(handler)); + }); + + // to many tests to be completed in one second + std::this_thread::sleep_for(std::chrono::milliseconds(1100)); + ASSERT_LT(concurent_check::checked.size(), 200); + ASSERT_EQ(concurent_check::max_active_check, 10); + + // all tests must be completed in 1.5s + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + ASSERT_EQ(concurent_check::max_active_check, 10); + ASSERT_EQ(concurent_check::checked.size(), 200); + + sched->stop(); +} \ No newline at end of file diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/conf_helper.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/conf_helper.hh new file mode 100644 index 00000000000..c3a0456eeae --- /dev/null +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/conf_helper.hh @@ -0,0 +1,100 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ +#ifndef CCE_MOD_CONF_HELPER_OPENTELEMETRY_HH +#define CCE_MOD_CONF_HELPER_OPENTELEMETRY_HH + +#include "com/centreon/engine/host.hh" +#include "com/centreon/engine/macros.hh" +#include "com/centreon/engine/service.hh" + +#include "com/centreon/engine/commands/forward.hh" + +namespace com::centreon::engine::modules::opentelemetry { + +/** + * @brief extract opentelemetry commands from an host list + * This function must be called from engine main thread, not grpc ones + * + * @tparam command_handler callback called on every opentelemetry command found + * @param host_name name of the host supervised by the agent or telegraf + * @param handler + * @return true at least one opentelemetry command was found + * @return false + */ +template +bool get_otel_commands(const std::string& host_name, + command_handler&& handler, + const std::shared_ptr& logger) { + auto use_otl_command = [](const checkable& to_test) -> bool { + if (to_test.get_check_command_ptr()->get_type() == + commands::command::e_type::otel) + return true; + if (to_test.get_check_command_ptr()->get_type() == + commands::command::e_type::forward) { + return std::static_pointer_cast( + to_test.get_check_command_ptr()) + ->get_sub_command() + ->get_type() == commands::command::e_type::otel; + } + return false; + }; + + bool ret = false; + + auto hst_iter = host::hosts.find(host_name); + if (hst_iter == host::hosts.end()) { + SPDLOG_LOGGER_ERROR(logger, "unknown host:{}", host_name); + return false; + } + std::shared_ptr hst = hst_iter->second; + std::string cmd_line; + // host check use otl? + if (use_otl_command(*hst)) { + nagios_macros* macros(get_global_macros()); + + ret |= handler(hst->check_command(), hst->get_check_command_line(macros), + "", logger); + clear_volatile_macros_r(macros); + } else { + SPDLOG_LOGGER_DEBUG( + logger, "host {} doesn't use opentelemetry to do his check", host_name); + } + // services of host + auto serv_iter = service::services_by_id.lower_bound({hst->host_id(), 0}); + for (; serv_iter != service::services_by_id.end() && + serv_iter->first.first == hst->host_id(); + ++serv_iter) { + std::shared_ptr serv = serv_iter->second; + if (use_otl_command(*serv)) { + nagios_macros* macros(get_global_macros()); + ret |= + handler(serv->check_command(), serv->get_check_command_line(macros), + serv->name(), logger); + clear_volatile_macros_r(macros); + } else { + SPDLOG_LOGGER_DEBUG( + logger, + "host {} service {} doesn't use opentelemetry to do his check", + host_name, serv->name()); + } + } + return ret; +} + +} // namespace com::centreon::engine::modules::opentelemetry +#endif diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/telegraf/conf_server.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/telegraf/conf_server.hh index 1e6a94b9f6b..989af594b33 100644 --- a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/telegraf/conf_server.hh +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/telegraf/conf_server.hh @@ -75,7 +75,7 @@ class conf_session : public connection_class { void on_receive_request(const std::shared_ptr& request); void answer_to_request(const std::shared_ptr& request, - std::vector&& host_list); + const std::string& host); bool _get_commands(const std::string& host_name, std::string& request_body); diff --git a/engine/modules/opentelemetry/src/data_point_fifo.cc b/engine/modules/opentelemetry/src/data_point_fifo.cc index 3082d0644c5..00e4bec9d58 100644 --- a/engine/modules/opentelemetry/src/data_point_fifo.cc +++ b/engine/modules/opentelemetry/src/data_point_fifo.cc @@ -72,10 +72,10 @@ void data_point_fifo::clean() { /** * @brief erase oldest element * - * @param expiry data points oldest than this nano timestamp are erased + * @param expiry data points older than this nano timestamp are erased */ void data_point_fifo::clean_oldest(uint64_t expiry) { - while (!_fifo.empty() && _fifo.begin()->get_nano_timestamp() <= expiry) { + while (!_fifo.empty() && _fifo.begin()->get_nano_timestamp() < expiry) { _fifo.erase(_fifo.begin()); } } diff --git a/engine/modules/opentelemetry/src/telegraf/conf_server.cc b/engine/modules/opentelemetry/src/telegraf/conf_server.cc index b7b53fa2ec8..d6e4d720571 100644 --- a/engine/modules/opentelemetry/src/telegraf/conf_server.cc +++ b/engine/modules/opentelemetry/src/telegraf/conf_server.cc @@ -18,6 +18,7 @@ #include +#include "conf_helper.hh" #include "telegraf/conf_server.hh" #include "com/centreon/engine/globals.hh" @@ -37,7 +38,7 @@ using namespace com::centreon::engine; static constexpr std::string_view _config_schema(R"( { "$schema": "http://json-schema.org/draft-04/schema#", - "title": "grpc config", + "title": "telegraf config", "properties": { "http_server" : { "listen_address": { @@ -240,19 +241,18 @@ template void conf_session::on_receive_request( const std::shared_ptr& request) { boost::url_view parsed(request->target()); - std::vector host_list; + std::string host; for (const auto& get_param : parsed.params()) { if (get_param.key == "host") { - host_list.emplace_back(get_param.value); + host = get_param.value; } } auto to_call = std::packaged_task( - [me = shared_from_this(), request, - hosts = std::move(host_list)]() mutable -> int32_t { + [me = shared_from_this(), request, host]() mutable -> int32_t { // then we are in the main thread // services, hosts and commands are stable - me->answer_to_request(request, std::move(hosts)); + me->answer_to_request(request, host); return 0; }); command_manager::instance().enqueue(std::move(to_call)); @@ -386,15 +386,10 @@ bool conf_session::_get_commands(const std::string& host_name, template void conf_session::answer_to_request( const std::shared_ptr& request, - std::vector&& host_list) { + const std::string& host) { http::response_ptr resp(std::make_shared()); resp->version(request->version()); - if (host_list.empty()) { - SPDLOG_LOGGER_ERROR(this->_logger, "no host found in target argument {}", - *request); - } - resp->body() = fmt::format(R"(# Centreon telegraf configuration # This telegraf configuration is generated by centreon centengine [agent] @@ -407,10 +402,7 @@ void conf_session::answer_to_request( )", _telegraf_conf->get_check_interval(), _telegraf_conf->get_engine_otl_endpoint()); - bool at_least_one_found = false; - for (const std::string& host : host_list) { - at_least_one_found |= _get_commands(host, resp->body()); - } + bool at_least_one_found = _get_commands(host, resp->body()); if (at_least_one_found) { resp->result(boost::beast::http::status::ok); resp->insert(boost::beast::http::field::content_type, "text/plain"); diff --git a/engine/modules/opentelemetry/src/telegraf/nagios_check_result_builder.cc b/engine/modules/opentelemetry/src/telegraf/nagios_check_result_builder.cc index 7c96fb57d25..e8515b2e217 100644 --- a/engine/modules/opentelemetry/src/telegraf/nagios_check_result_builder.cc +++ b/engine/modules/opentelemetry/src/telegraf/nagios_check_result_builder.cc @@ -141,8 +141,9 @@ static std::string_view get_nagios_telegraf_suffix( return ""; } std::string_view last_word = metric_name.substr(sep_pos + 1); - if (last_word == "lt" || last_word == "gt" || last_word == "le" || - last_word == "ge" && sep_pos > 0) { // critical_lt or warning_le + if ((last_word == "lt" || last_word == "gt" || last_word == "le" || + last_word == "ge") && + sep_pos > 0) { // critical_lt or warning_le sep_pos = metric_name.rfind('_', sep_pos - 1); if (sep_pos != std::string_view::npos) { return metric_name.substr(sep_pos + 1); diff --git a/tests/broker-engine/opentelemetry.robot b/tests/broker-engine/opentelemetry.robot index b9050880ad3..728e624a924 100644 --- a/tests/broker-engine/opentelemetry.robot +++ b/tests/broker-engine/opentelemetry.robot @@ -116,28 +116,30 @@ BEOTEL_TELEGRAF_CHECK_HOST ${resources_list} Ctn Create Otl Request ${0} host_1 + # check without feed + ${start} Ctn Get Round Current Date + Ctn Schedule Forced Host Check host_1 + ${result} Ctn Check Host Output Resource Status With Timeout + ... host_1 + ... 35 + ... ${start} + ... 0 + ... HARD + ... (No output returned from host check) + Should Be True ${result} hosts table not updated + + Log To Console export metrics Ctn Send Otl To Engine 4317 ${resources_list} Sleep 5 + # feed and check ${start} Ctn Get Round Current Date Ctn Schedule Forced Host Check host_1 - ${result} Ctn Check Host Check Status With Timeout host_1 30 ${start} 0 OK - Should Be True ${result} hosts table not updated - - # check without feed - - ${start} Ctn Get Round Current Date - Ctn Schedule Forced Host Check host_1 - ${result} Ctn Check Host Check Status With Timeout - ... host_1 - ... 35 - ... ${start} - ... 0 - ... (No output returned from host check) + ${result} Ctn Check Host Output Resource Status With Timeout host_1 30 ${start} 0 HARD OK Should Be True ${result} hosts table not updated # check then feed, three times to modify hard state @@ -196,46 +198,47 @@ BEOTEL_TELEGRAF_CHECK_SERVICE ${resources_list} Ctn Create Otl Request ${0} host_1 service_1 - Log To Console export metrics - Ctn Send Otl To Engine 4317 ${resources_list} - - Sleep 5 - - # feed and check - ${start} Ctn Get Round Current Date - Ctn Schedule Forced Svc Check host_1 service_1 - - ${result} Ctn Check Service Check Status With Timeout host_1 service_1 30 ${start} 0 OK - Should Be True ${result} services table not updated - # check without feed ${start} Ctn Get Round Current Date Ctn Schedule Forced Svc Check host_1 service_1 - ${result} Ctn Check Service Check Status With Timeout + ${result} Ctn Check Service Output Resource Status With Timeout ... host_1 ... service_1 ... 35 ... ${start} ... 0 + ... HARD ... (No output returned from plugin) Should Be True ${result} services table not updated - # check then feed, three times to modify hard state + Log To Console export metrics + Ctn Send Otl To Engine 4317 ${resources_list} + + Sleep 5 + + # feed and check ${start} Ctn Get Round Current Date Ctn Schedule Forced Svc Check host_1 service_1 - Sleep 2 + + ${result} Ctn Check Service Output Resource Status With Timeout host_1 service_1 30 ${start} 0 HARD OK + Should Be True ${result} services table not updated + + # check then feed, three times to modify hard state + ${start} Ctn Get Round Current Date ${resources_list} Ctn Create Otl Request ${2} host_1 service_1 Ctn Send Otl To Engine 4317 ${resources_list} - Ctn Schedule Forced Svc Check host_1 service_1 Sleep 2 + Ctn Schedule Forced Svc Check host_1 service_1 ${resources_list} Ctn Create Otl Request ${2} host_1 service_1 Ctn Send Otl To Engine 4317 ${resources_list} - Ctn Schedule Forced Svc Check host_1 service_1 Sleep 2 + Ctn Schedule Forced Svc Check host_1 service_1 ${resources_list} Ctn Create Otl Request ${2} host_1 service_1 Ctn Send Otl To Engine 4317 ${resources_list} - ${result} Ctn Check Service Check Status With Timeout host_1 service_1 30 ${start} 2 CRITICAL + Sleep 2 + Ctn Schedule Forced Svc Check host_1 service_1 + ${result} Ctn Check Service Output Resource Status With Timeout host_1 service_1 30 ${start} 2 HARD CRITICAL Should Be True ${result} services table not updated @@ -302,7 +305,7 @@ BEOTEL_SERVE_TELEGRAF_CONFIGURATION_CRYPTED Sleep 1 ${telegraf_conf_response} GET ... verify=${False} - ... url=https://localhost:1443/engine?host=host_1&host=host_2&host=host_3 + ... url=https://localhost:1443/engine?host=host_1 Should Be Equal As Strings ${telegraf_conf_response.reason} OK no response received or error response ${content_compare_result} Ctn Compare String With File @@ -375,7 +378,7 @@ BEOTEL_SERVE_TELEGRAF_CONFIGURATION_NO_CRYPTED Should Be True ${result} "server listen on 0.0.0.0:1443" should be available. Sleep 1 ${telegraf_conf_response} GET - ... url=http://localhost:1443/engine?host=host_1&host=host_2&host=host_3 + ... url=http://localhost:1443/engine?host=host_1 Should Be Equal As Strings ${telegraf_conf_response.reason} OK no response received or error response diff --git a/tests/resources/Broker.py b/tests/resources/Broker.py index e9e629c335e..fe65675d4eb 100755 --- a/tests/resources/Broker.py +++ b/tests/resources/Broker.py @@ -16,9 +16,7 @@ # # For more information : contact@centreon.com # -# This script is a little tcp server working on port 5669. It can simulate -# a cbd instance. It is useful to test the validity of BBDO packets sent by -# centengine. + import signal from os import setsid from os import makedirs diff --git a/tests/resources/Common.py b/tests/resources/Common.py index 20fa11819bf..3978dd95604 100644 --- a/tests/resources/Common.py +++ b/tests/resources/Common.py @@ -1026,6 +1026,51 @@ def ctn_check_service_check_status_with_timeout(hostname: str, service_desc: str return False +def ctn_check_service_output_resource_status_with_timeout(hostname: str, service_desc: str, timeout: int, min_last_check: int, status: int, status_type: str, output:str): + """ + ctn_check_host_output_resource_status_with_timeout + + check if resource checks infos of an host have been updated + + Args: + hostname: + service_desc: + timeout: time to wait expected check in seconds + min_last_check: time point after last_check will be accepted + status: expected host state + status_type: HARD or SOFT + output: expected output + """ + + limit = time.time() + timeout + while time.time() < limit: + connection = pymysql.connect(host=DB_HOST, + user=DB_USER, + password=DB_PASS, + autocommit=True, + database=DB_NAME_STORAGE, + charset='utf8mb4', + cursorclass=pymysql.cursors.DictCursor) + + with connection: + with connection.cursor() as cursor: + cursor.execute( + f"SELECT r.status, r.status_confirmed, r.output FROM resources r LEFT JOIN services s ON r.id=s.service_id AND r.parent_id=s.host_id JOIN hosts h ON s.host_id=h.host_id WHERE h.name='{hostname}' AND s.description='{service_desc}' AND r.last_check >= {min_last_check}" ) + result = cursor.fetchall() + if len(result) > 0: + logger.console(f"result: {result}") + if len(result) > 0 and result[0]['status'] is not None and int(result[0]['status']) == int(status): + logger.console( + f"status={result[0]['status']} and status_confirmed={result[0]['status_confirmed']}") + if status_type == 'HARD' and int(result[0]['status_confirmed']) == 1 and output in result[0]['output']: + return True + elif status_type == 'SOFT' and int(result[0]['status_confirmed']) == 0 and output in result[0]['output']: + return True + time.sleep(1) + return False + + + def ctn_check_host_check_with_timeout(hostname: str, timeout: int, command_line: str): limit = time.time() + timeout while time.time() < limit: @@ -1087,6 +1132,49 @@ def ctn_check_host_check_status_with_timeout(hostname: str, timeout: int, min_la return False +def ctn_check_host_output_resource_status_with_timeout(hostname: str, timeout: int, min_last_check: int, status: int, status_type: str, output:str): + """ + ctn_check_host_output_resource_status_with_timeout + + check if resource checks infos of an host have been updated + + Args: + hostname: + timeout: time to wait expected check in seconds + min_last_check: time point after last_check will be accepted + status: expected host state + status_type: HARD or SOFT + output: expected output + """ + + limit = time.time() + timeout + while time.time() < limit: + connection = pymysql.connect(host=DB_HOST, + user=DB_USER, + password=DB_PASS, + autocommit=True, + database=DB_NAME_STORAGE, + charset='utf8mb4', + cursorclass=pymysql.cursors.DictCursor) + + with connection: + with connection.cursor() as cursor: + cursor.execute( + f"SELECT r.status, r.status_confirmed, r.output FROM resources r JOIN hosts h ON r.id=h.host_id WHERE h.name='{hostname}' AND r.parent_id=0 AND r.last_check >= {min_last_check}" ) + result = cursor.fetchall() + if len(result) > 0: + logger.console(f"result: {result}") + if len(result) > 0 and result[0]['status'] is not None and int(result[0]['status']) == int(status): + logger.console( + f"status={result[0]['status']} and status_confirmed={result[0]['status_confirmed']}") + if status_type == 'HARD' and int(result[0]['status_confirmed']) == 1 and output in result[0]['output']: + return True + elif status_type == 'SOFT' and int(result[0]['status_confirmed']) == 0 and output in result[0]['output']: + return True + time.sleep(1) + return False + + def ctn_show_downtimes(): connection = pymysql.connect(host=DB_HOST, user=DB_USER, diff --git a/tests/resources/opentelemetry/telegraf.conf b/tests/resources/opentelemetry/telegraf.conf index 2282ce60fab..3841a19baca 100644 --- a/tests/resources/opentelemetry/telegraf.conf +++ b/tests/resources/opentelemetry/telegraf.conf @@ -34,21 +34,3 @@ host = "host_1" service = "service_2" - -[[inputs.exec]] - name_override = "otel_check_icmp_host_2" - commands = ["/usr/lib/nagios/plugins/check_icmp 127.0.0.20"] - data_format = "nagios" - [inputs.exec.tags] - host = "host_2" - service = "" - - -[[inputs.exec]] - name_override = "otel_check_icmp_serv_5" - commands = ["/usr/lib/nagios/plugins/check_icmp 127.0.0.5"] - data_format = "nagios" - [inputs.exec.tags] - host = "host_3" - service = "service_5" - From 6c2f98f805c18961c2c49e5020238faf9112ef5a Mon Sep 17 00:00:00 2001 From: tuntoja Date: Fri, 28 Jun 2024 22:25:33 +0200 Subject: [PATCH 54/60] chore(release): bump version to 24.07.0 --- .version | 2 +- CMakeLists.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.version b/.version index 78a9e5287bd..4cb5b94d8d2 100644 --- a/.version +++ b/.version @@ -1,2 +1,2 @@ -MAJOR=24.05 +MAJOR=24.07 MINOR=0 diff --git a/CMakeLists.txt b/CMakeLists.txt index f8f21ebd513..8a96bfda104 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -137,7 +137,7 @@ endif() # Version. set(COLLECT_MAJOR 24) -set(COLLECT_MINOR 05) +set(COLLECT_MINOR 07) set(COLLECT_PATCH 0) set(COLLECT_VERSION "${COLLECT_MAJOR}.${COLLECT_MINOR}.${COLLECT_PATCH}") add_definitions(-DCENTREON_CONNECTOR_VERSION=\"${COLLECT_VERSION}\") From 6493c2d88bb006224351be360116ea591ca40de8 Mon Sep 17 00:00:00 2001 From: tuntoja Date: Fri, 28 Jun 2024 22:26:48 +0200 Subject: [PATCH 55/60] enh(get-version): handle prepare-release-cloud branches --- .github/workflows/get-version.yml | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/.github/workflows/get-version.yml b/.github/workflows/get-version.yml index d18322ecd67..eff58cd5573 100644 --- a/.github/workflows/get-version.yml +++ b/.github/workflows/get-version.yml @@ -128,6 +128,17 @@ jobs: echo "release_type=$GITHUB_RELEASE_TYPE" >> $GITHUB_OUTPUT fi ;; + prepare-release-cloud*) + # Set release cloud to 1 (0=not-cloud, 1=cloud) + GITHUB_RELEASE_CLOUD=1 + # Debug + echo "GITHUB_RELEASE_TYPE is: $GITHUB_RELEASE_TYPE" + echo "GITHUB_RELEASE_CLOUD is: $GITHUB_RELEASE_CLOUD" + # Github ouputs + echo "release=`date +%s`.`echo ${{ github.sha }} | cut -c -7`" >> $GITHUB_OUTPUT + echo "release_type=$GITHUB_RELEASE_TYPE" >> $GITHUB_OUTPUT + echo "release_cloud=$GITHUB_RELEASE_CLOUD" >> $GITHUB_OUTPUT + ;; *) echo "release=`date +%s`.`echo ${{ github.sha }} | cut -c -7`" >> $GITHUB_OUTPUT echo "release_cloud=$GITHUB_RELEASE_CLOUD" >> $GITHUB_OUTPUT From 5b3899ab3d31fc3d2abbda405c5f5c74ec68e23c Mon Sep 17 00:00:00 2001 From: David Boucher Date: Mon, 1 Jul 2024 09:36:08 +0200 Subject: [PATCH 56/60] enh(engine/configuration): engine configuration moved to common (#1479) * enh(engine/common): Engine configuration engine is moved to common in engine_legacy_conf directory * fix(cmake): dependency added --- CMakeLists.txt | 75 +++++++++++-------- common/CMakeLists.txt | 1 + common/engine_legacy_conf/CMakeLists.txt | 52 +++++++++++++ .../engine_legacy_conf}/anomalydetection.cc | 2 +- .../engine_legacy_conf}/anomalydetection.hh | 6 +- .../engine_legacy_conf}/command.cc | 2 +- .../engine_legacy_conf}/command.hh | 2 +- .../engine_legacy_conf}/connector.cc | 2 +- .../engine_legacy_conf}/connector.hh | 2 +- .../engine_legacy_conf}/contact.cc | 6 +- .../engine_legacy_conf}/contact.hh | 6 +- .../engine_legacy_conf}/contactgroup.cc | 2 +- .../engine_legacy_conf}/contactgroup.hh | 4 +- .../engine_legacy_conf}/customvariable.cc | 2 +- .../engine_legacy_conf}/customvariable.hh | 0 .../engine_legacy_conf}/daterange.cc | 18 ++--- .../engine_legacy_conf}/daterange.hh | 0 .../engine_legacy_conf}/file_info.hh | 0 .../engine_legacy_conf}/group.cc | 3 +- .../engine_legacy_conf}/group.hh | 0 .../engine_legacy_conf}/host.cc | 7 +- .../engine_legacy_conf}/host.hh | 10 +-- .../engine_legacy_conf}/hostdependency.cc | 2 +- .../engine_legacy_conf}/hostdependency.hh | 4 +- .../engine_legacy_conf}/hostescalation.cc | 2 +- .../engine_legacy_conf}/hostescalation.hh | 4 +- .../engine_legacy_conf}/hostgroup.cc | 2 +- .../engine_legacy_conf}/hostgroup.hh | 4 +- .../engine_legacy_conf}/object.cc | 37 ++++----- .../engine_legacy_conf}/object.hh | 0 .../engine_legacy_conf}/parser.cc | 2 +- .../engine_legacy_conf}/parser.hh | 4 +- .../engine_legacy_conf}/point_2d.cc | 2 +- .../engine_legacy_conf}/point_2d.hh | 0 .../engine_legacy_conf}/point_3d.cc | 2 +- .../engine_legacy_conf}/point_3d.hh | 0 .../engine_legacy_conf}/service.cc | 4 +- .../engine_legacy_conf}/service.hh | 6 +- .../engine_legacy_conf}/servicedependency.cc | 2 +- .../engine_legacy_conf}/servicedependency.hh | 4 +- .../engine_legacy_conf}/serviceescalation.cc | 2 +- .../engine_legacy_conf}/serviceescalation.hh | 4 +- .../engine_legacy_conf}/servicegroup.cc | 2 +- .../engine_legacy_conf}/servicegroup.hh | 4 +- .../engine_legacy_conf}/severity.cc | 2 +- .../engine_legacy_conf}/severity.hh | 2 +- .../engine_legacy_conf}/state.cc | 3 +- .../engine_legacy_conf}/state.hh | 34 +++++---- .../engine_legacy_conf}/tag.cc | 2 +- .../engine_legacy_conf}/tag.hh | 2 +- .../engine_legacy_conf}/timeperiod.cc | 4 +- .../engine_legacy_conf}/timeperiod.hh | 6 +- common/grpc/src/grpc_server.cc | 2 +- common/precomp_inc/precomp.hh | 1 + engine/CMakeLists.txt | 7 +- .../configuration/applier/contactgroup.hh | 2 +- .../engine/configuration/applier/globals.hh | 24 +++--- .../engine/configuration/applier/hostgroup.hh | 2 +- .../engine/configuration/applier/logging.hh | 2 +- .../engine/configuration/applier/macros.hh | 41 +++++----- .../engine/configuration/applier/scheduler.hh | 38 +++++----- .../configuration/applier/servicegroup.hh | 2 +- .../engine/configuration/applier/state.hh | 2 +- engine/inc/com/centreon/engine/globals.hh | 2 +- .../inc/com/centreon/engine/hostdependency.hh | 2 +- .../com/centreon/engine/servicedependency.hh | 2 +- engine/inc/com/centreon/engine/timerange.hh | 38 +++++----- engine/src/config.cc | 2 +- engine/src/configuration/CMakeLists.txt | 26 +------ engine/src/configuration/applier/command.cc | 2 +- engine/src/configuration/applier/connector.cc | 7 +- .../applier/servicedependency.cc | 4 +- .../applier/serviceescalation.cc | 2 +- engine/src/configuration/applier/severity.cc | 2 +- engine/src/configuration/applier/state.cc | 2 +- engine/src/configuration/applier/tag.cc | 2 +- engine/src/configuration/extended_conf.cc | 2 +- engine/src/configuration/whitelist.cc | 2 +- engine/src/contactgroup.cc | 2 +- engine/src/daterange.cc | 2 +- engine/src/diagnostic.cc | 4 +- engine/src/events/loop.cc | 2 +- engine/src/main.cc | 4 +- engine/tests/checks/anomalydetection.cc | 4 +- engine/tests/checks/service_check.cc | 6 +- engine/tests/checks/service_retention.cc | 6 +- .../applier/applier-anomalydetection.cc | 2 +- .../configuration/applier/applier-command.cc | 4 +- .../applier/applier-connector.cc | 2 +- .../configuration/applier/applier-contact.cc | 2 +- .../applier/applier-contactgroup.cc | 2 +- .../configuration/applier/applier-global.cc | 6 +- .../configuration/applier/applier-host.cc | 4 +- .../applier/applier-hostdependency.cc | 6 +- .../applier/applier-hostescalation.cc | 8 +- .../applier/applier-hostgroup.cc | 2 +- .../configuration/applier/applier-log.cc | 6 +- .../configuration/applier/applier-service.cc | 6 +- .../applier/applier-servicegroup.cc | 2 +- .../configuration/applier/applier-state.cc | 4 +- engine/tests/configuration/contact.cc | 2 +- engine/tests/configuration/host.cc | 36 ++++----- engine/tests/configuration/object.cc | 38 +++++----- engine/tests/configuration/service.cc | 36 +++++---- engine/tests/configuration/severity.cc | 2 +- engine/tests/configuration/tag.cc | 4 +- engine/tests/configuration/timeperiod-test.cc | 2 +- engine/tests/custom_vars/extcmd.cc | 2 +- engine/tests/downtimes/downtime_finder.cc | 6 +- engine/tests/enginerpc/enginerpc.cc | 4 +- .../external_commands/anomalydetection.cc | 4 +- engine/tests/external_commands/service.cc | 2 +- engine/tests/helper.hh | 2 +- engine/tests/loop/loop.cc | 4 +- engine/tests/macros/macro.cc | 4 +- engine/tests/macros/macro_hostname.cc | 28 +++---- engine/tests/macros/macro_service.cc | 4 +- .../host_downtime_notification.cc | 2 +- .../host_flapping_notification.cc | 4 +- .../notifications/host_normal_notification.cc | 6 +- .../host_recovery_notification.cc | 2 +- .../service_downtime_notification_test.cc | 4 +- .../service_flapping_notification.cc | 4 +- .../service_normal_notification.cc | 4 +- .../service_timeperiod_notification.cc | 6 +- .../opentelemetry/open_telemetry_test.cc | 4 +- .../tests/opentelemetry/opentelemetry_test.cc | 4 +- .../tests/opentelemetry/otl_converter_test.cc | 4 +- engine/tests/test_engine.cc | 2 +- engine/tests/test_engine.hh | 18 ++--- .../get_next_valid_time/exceptions_test.cc | 2 +- 131 files changed, 466 insertions(+), 436 deletions(-) create mode 100644 common/engine_legacy_conf/CMakeLists.txt rename {engine/src/configuration => common/engine_legacy_conf}/anomalydetection.cc (99%) rename {engine/inc/com/centreon/engine/configuration => common/engine_legacy_conf}/anomalydetection.hh (98%) rename {engine/src/configuration => common/engine_legacy_conf}/command.cc (98%) rename {engine/inc/com/centreon/engine/configuration => common/engine_legacy_conf}/command.hh (97%) rename {engine/src/configuration => common/engine_legacy_conf}/connector.cc (98%) rename {engine/inc/com/centreon/engine/configuration => common/engine_legacy_conf}/connector.hh (97%) rename {engine/src/configuration => common/engine_legacy_conf}/contact.cc (99%) rename {engine/inc/com/centreon/engine/configuration => common/engine_legacy_conf}/contact.hh (96%) rename {engine/src/configuration => common/engine_legacy_conf}/contactgroup.cc (99%) rename {engine/inc/com/centreon/engine/configuration => common/engine_legacy_conf}/contactgroup.hh (95%) rename {engine/src/configuration => common/engine_legacy_conf}/customvariable.cc (96%) rename {engine/inc/com/centreon/engine/configuration => common/engine_legacy_conf}/customvariable.hh (100%) rename {engine/src/configuration => common/engine_legacy_conf}/daterange.cc (94%) rename {engine/inc/com/centreon/engine/configuration => common/engine_legacy_conf}/daterange.hh (100%) rename {engine/inc/com/centreon/engine/configuration => common/engine_legacy_conf}/file_info.hh (100%) rename {engine/src/configuration => common/engine_legacy_conf}/group.cc (99%) rename {engine/inc/com/centreon/engine/configuration => common/engine_legacy_conf}/group.hh (100%) rename {engine/src/configuration => common/engine_legacy_conf}/host.cc (99%) rename {engine/inc/com/centreon/engine/configuration => common/engine_legacy_conf}/host.hh (96%) rename {engine/src/configuration => common/engine_legacy_conf}/hostdependency.cc (99%) rename {engine/inc/com/centreon/engine/configuration => common/engine_legacy_conf}/hostdependency.hh (97%) rename {engine/src/configuration => common/engine_legacy_conf}/hostescalation.cc (99%) rename {engine/inc/com/centreon/engine/configuration => common/engine_legacy_conf}/hostescalation.hh (97%) rename {engine/src/configuration => common/engine_legacy_conf}/hostgroup.cc (99%) rename {engine/inc/com/centreon/engine/configuration => common/engine_legacy_conf}/hostgroup.hh (96%) rename {engine/src/configuration => common/engine_legacy_conf}/object.cc (88%) rename {engine/inc/com/centreon/engine/configuration => common/engine_legacy_conf}/object.hh (100%) rename {engine/src/configuration => common/engine_legacy_conf}/parser.cc (99%) rename {engine/inc/com/centreon/engine/configuration => common/engine_legacy_conf}/parser.hh (96%) rename {engine/src/configuration => common/engine_legacy_conf}/point_2d.cc (97%) rename {engine/inc/com/centreon/engine/configuration => common/engine_legacy_conf}/point_2d.hh (100%) rename {engine/src/configuration => common/engine_legacy_conf}/point_3d.cc (97%) rename {engine/inc/com/centreon/engine/configuration => common/engine_legacy_conf}/point_3d.hh (100%) rename {engine/src/configuration => common/engine_legacy_conf}/service.cc (99%) rename {engine/inc/com/centreon/engine/configuration => common/engine_legacy_conf}/service.hh (98%) rename {engine/src/configuration => common/engine_legacy_conf}/servicedependency.cc (99%) rename {engine/inc/com/centreon/engine/configuration => common/engine_legacy_conf}/servicedependency.hh (97%) rename {engine/src/configuration => common/engine_legacy_conf}/serviceescalation.cc (99%) rename {engine/inc/com/centreon/engine/configuration => common/engine_legacy_conf}/serviceescalation.hh (97%) rename {engine/src/configuration => common/engine_legacy_conf}/servicegroup.cc (99%) rename {engine/inc/com/centreon/engine/configuration => common/engine_legacy_conf}/servicegroup.hh (96%) rename {engine/src/configuration => common/engine_legacy_conf}/severity.cc (99%) rename {engine/inc/com/centreon/engine/configuration => common/engine_legacy_conf}/severity.hh (97%) rename {engine/src/configuration => common/engine_legacy_conf}/state.cc (99%) rename {engine/inc/com/centreon/engine/configuration => common/engine_legacy_conf}/state.hh (96%) rename {engine/src/configuration => common/engine_legacy_conf}/tag.cc (98%) rename {engine/inc/com/centreon/engine/configuration => common/engine_legacy_conf}/tag.hh (97%) rename {engine/src/configuration => common/engine_legacy_conf}/timeperiod.cc (99%) rename {engine/inc/com/centreon/engine/configuration => common/engine_legacy_conf}/timeperiod.hh (95%) mode change 100755 => 100644 engine/tests/configuration/applier/applier-command.cc mode change 100755 => 100644 engine/tests/custom_vars/extcmd.cc diff --git a/CMakeLists.txt b/CMakeLists.txt index f8f21ebd513..a50ffd158e9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -32,17 +32,24 @@ add_definitions(-DCENTREON_CURRENT_YEAR="${CENTREON_CURRENT_YEAR}") if(DEFINED ENV{VCPKG_ROOT}) set(VCPKG_ROOT "$ENV{VCPKG_ROOT}") - message(STATUS "TOOLCHAIN set to ${VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake") - set(CMAKE_TOOLCHAIN_FILE "${VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake" - CACHE STRING "Vcpkg toolchain file") + message( + STATUS "TOOLCHAIN set to ${VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake") + set(CMAKE_TOOLCHAIN_FILE + "${VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake" + CACHE STRING "Vcpkg toolchain file") else() - message(STATUS "TOOLCHAIN set to ${CMAKE_CURRENT_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake") - set(CMAKE_TOOLCHAIN_FILE "${CMAKE_CURRENT_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake" - CACHE STRING "Vcpkg toolchain file") + message( + STATUS + "TOOLCHAIN set to ${CMAKE_CURRENT_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake" + ) + set(CMAKE_TOOLCHAIN_FILE + "${CMAKE_CURRENT_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake" + CACHE STRING "Vcpkg toolchain file") endif() -set(CMAKE_TOOLCHAIN_FILE "${CMAKE_CURRENT_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake" - CACHE STRING "Vcpkg toolchain file") +set(CMAKE_TOOLCHAIN_FILE + "${CMAKE_CURRENT_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake" + CACHE STRING "Vcpkg toolchain file") project("Centreon Collect" C CXX) @@ -142,7 +149,7 @@ set(COLLECT_PATCH 0) set(COLLECT_VERSION "${COLLECT_MAJOR}.${COLLECT_MINOR}.${COLLECT_PATCH}") add_definitions(-DCENTREON_CONNECTOR_VERSION=\"${COLLECT_VERSION}\") -if (DEBUG_ROBOT) +if(DEBUG_ROBOT) add_definitions(-DDEBUG_ROBOT) endif() @@ -150,7 +157,6 @@ endif() set(USER_BROKER centreon-broker) set(USER_ENGINE centreon-engine) - find_package(fmt CONFIG REQUIRED) find_package(spdlog CONFIG REQUIRED) find_package(gRPC CONFIG REQUIRED) @@ -168,12 +174,14 @@ pkg_check_modules(LIBSSH2 REQUIRED libssh2) # There is a bug with grpc. It is not put in the triplet directory. So we have # to search for its plugin. -file(GLOB_RECURSE GRPC_CPP_PLUGIN_EXE - RELATIVE ${CMAKE_BINARY_DIR} grpc_cpp_plugin) -find_program(GRPC_CPP_PLUGIN +file( + GLOB_RECURSE GRPC_CPP_PLUGIN_EXE + RELATIVE ${CMAKE_BINARY_DIR} + grpc_cpp_plugin) +find_program( + GRPC_CPP_PLUGIN NAMES ${GRPC_CPP_PLUGIN_EXE} - PATHS ${CMAKE_BINARY_DIR} - REQUIRED + PATHS ${CMAKE_BINARY_DIR} REQUIRED NO_DEFAULT_PATH) set(PROTOBUF_LIB_DIR ${Protobuf_DIR}/../../lib) @@ -181,19 +189,25 @@ set(OTLP_LIB_DIR ${opentelemetry-cpp_DIR}/../../lib) set(VCPKG_INCLUDE_DIR ${Protobuf_INCLUDE_DIR}) include(GNUInstallDirs) -#import opentelemetry-proto +# import opentelemetry-proto add_custom_command( - OUTPUT ${CMAKE_SOURCE_DIR}/opentelemetry-proto/opentelemetry/proto/collector/metrics/v1/metrics_service.proto + OUTPUT + ${CMAKE_SOURCE_DIR}/opentelemetry-proto/opentelemetry/proto/collector/metrics/v1/metrics_service.proto ${CMAKE_SOURCE_DIR}/opentelemetry-proto/opentelemetry/proto/metrics/v1/metrics.proto ${CMAKE_SOURCE_DIR}/opentelemetry-proto/opentelemetry/proto/common/v1/common.proto ${CMAKE_SOURCE_DIR}/opentelemetry-proto/opentelemetry/proto/resource/v1/resource.proto COMMENT "get opentelemetry proto files from git repository" - COMMAND /bin/rm -rf ${CMAKE_SOURCE_DIR}/opentelemetry-proto - COMMAND git ARGS clone --depth=1 --single-branch https://github.com/open-telemetry/opentelemetry-proto.git ${CMAKE_SOURCE_DIR}/opentelemetry-proto - WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} -) - -add_custom_target(opentelemetry-proto-files DEPENDS ${CMAKE_SOURCE_DIR}/opentelemetry-proto/opentelemetry/proto/collector/metrics/v1/metrics_service.proto + COMMAND /bin/rm -rf ${CMAKE_SOURCE_DIR}/opentelemetry-proto + COMMAND + git ARGS clone --depth=1 --single-branch + https://github.com/open-telemetry/opentelemetry-proto.git + ${CMAKE_SOURCE_DIR}/opentelemetry-proto + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}) + +add_custom_target( + opentelemetry-proto-files + DEPENDS + ${CMAKE_SOURCE_DIR}/opentelemetry-proto/opentelemetry/proto/collector/metrics/v1/metrics_service.proto ${CMAKE_SOURCE_DIR}/opentelemetry-proto/opentelemetry/proto/metrics/v1/metrics.proto ${CMAKE_SOURCE_DIR}/opentelemetry-proto/opentelemetry/proto/common/v1/common.proto ${CMAKE_SOURCE_DIR}/opentelemetry-proto/opentelemetry/proto/resource/v1/resource.proto @@ -210,6 +224,11 @@ set(ENGINE_VAR_LOG_ARCHIVE_DIR "${CMAKE_INSTALL_FULL_LOCALSTATEDIR}/log/centreon-engine/archives") set(ENGINE_VAR_LIB_DIR "${CMAKE_INSTALL_FULL_LOCALSTATEDIR}/lib/centreon-engine") +add_definitions(-DDEFAULT_COMMAND_FILE="${ENGINE_VAR_LIB_DIR}/rw/centengine.cmd" + -DDEFAULT_DEBUG_FILE="${ENGINE_VAR_LOG_DIR}/centengine.debug" + -DDEFAULT_LOG_FILE="${ENGINE_VAR_LOG_DIR}/centengine.log" + -DDEFAULT_RETENTION_FILE="${ENGINE_VAR_LOG_DIR}/retention.dat" + -DDEFAULT_STATUS_FILE="${ENGINE_VAR_LOG_DIR}/status.dat") set(CMAKE_INSTALL_PREFIX "/usr") option(WITH_TESTING "Build unit tests." OFF) @@ -227,11 +246,8 @@ endif() set(protobuf_MODULE_COMPATIBLE True) -include_directories(${CMAKE_SOURCE_DIR} - ${VCPKG_INCLUDE_DIR} - fmt::fmt - spdlog::spdlog - ${CMAKE_SOURCE_DIR}/clib/inc) +include_directories(${CMAKE_SOURCE_DIR} ${VCPKG_INCLUDE_DIR} fmt::fmt + spdlog::spdlog ${CMAKE_SOURCE_DIR}/clib/inc) add_subdirectory(clib) add_subdirectory(common) @@ -242,11 +258,10 @@ add_subdirectory(connectors) add_subdirectory(ccc) add_subdirectory(agent) -if (WITH_MALLOC_TRACE) +if(WITH_MALLOC_TRACE) add_subdirectory(malloc-trace) endif() - add_custom_target(test-broker COMMAND tests/ut_broker) add_custom_target(test-engine COMMAND tests/ut_engine) add_custom_target(test-clib COMMAND tests/ut_clib) diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt index 0f67c0116e9..03b0488d216 100644 --- a/common/CMakeLists.txt +++ b/common/CMakeLists.txt @@ -20,6 +20,7 @@ project("Centreon common" C CXX) add_subdirectory(log_v2) +add_subdirectory(engine_legacy_conf) # Set directories. set(INCLUDE_DIR "${PROJECT_SOURCE_DIR}/inc/com/centreon/common") diff --git a/common/engine_legacy_conf/CMakeLists.txt b/common/engine_legacy_conf/CMakeLists.txt new file mode 100644 index 00000000000..843412b0fcb --- /dev/null +++ b/common/engine_legacy_conf/CMakeLists.txt @@ -0,0 +1,52 @@ +# +# Copyright 2024 Centreon +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may not +# use this file except in compliance with the License. You may obtain a copy of +# the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations under +# the License. +# +# For more information : contact@centreon.com +# + +add_library( + engine_legacy_conf STATIC + anomalydetection.cc + command.cc + connector.cc + contact.cc + contactgroup.cc + customvariable.cc + daterange.cc + group.cc + host.cc + hostdependency.cc + hostescalation.cc + hostgroup.cc + object.cc + parser.cc + point_2d.cc + point_3d.cc + service.cc + servicedependency.cc + serviceescalation.cc + servicegroup.cc + severity.cc + state.cc + tag.cc + timeperiod.cc +) + +add_dependencies(engine_legacy_conf pb_neb_lib) +include_directories(${CMAKE_SOURCE_DIR}/common/inc) + +target_precompile_headers(engine_legacy_conf PRIVATE ${CMAKE_SOURCE_DIR}/common/precomp_inc/precomp.hh) +target_link_libraries(engine_legacy_conf log_v2 absl::any absl::log absl::base + absl::bits) diff --git a/engine/src/configuration/anomalydetection.cc b/common/engine_legacy_conf/anomalydetection.cc similarity index 99% rename from engine/src/configuration/anomalydetection.cc rename to common/engine_legacy_conf/anomalydetection.cc index 30ba75b5a32..b6e1ef13322 100644 --- a/engine/src/configuration/anomalydetection.cc +++ b/common/engine_legacy_conf/anomalydetection.cc @@ -17,7 +17,7 @@ * */ -#include "com/centreon/engine/configuration/anomalydetection.hh" +#include "anomalydetection.hh" #include #include #include diff --git a/engine/inc/com/centreon/engine/configuration/anomalydetection.hh b/common/engine_legacy_conf/anomalydetection.hh similarity index 98% rename from engine/inc/com/centreon/engine/configuration/anomalydetection.hh rename to common/engine_legacy_conf/anomalydetection.hh index fb331007c8e..988768cc699 100644 --- a/engine/inc/com/centreon/engine/configuration/anomalydetection.hh +++ b/common/engine_legacy_conf/anomalydetection.hh @@ -21,9 +21,9 @@ #include "bbdo/neb.pb.h" #include "com/centreon/common/opt.hh" -#include "com/centreon/engine/configuration/customvariable.hh" -#include "com/centreon/engine/configuration/group.hh" -#include "com/centreon/engine/configuration/object.hh" +#include "customvariable.hh" +#include "group.hh" +#include "object.hh" using com::centreon::common::opt; diff --git a/engine/src/configuration/command.cc b/common/engine_legacy_conf/command.cc similarity index 98% rename from engine/src/configuration/command.cc rename to common/engine_legacy_conf/command.cc index 9be403106ba..77a1f0bb75c 100644 --- a/engine/src/configuration/command.cc +++ b/common/engine_legacy_conf/command.cc @@ -17,7 +17,7 @@ * For more information : contact@centreon.com * */ -#include "com/centreon/engine/configuration/command.hh" +#include "command.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon; diff --git a/engine/inc/com/centreon/engine/configuration/command.hh b/common/engine_legacy_conf/command.hh similarity index 97% rename from engine/inc/com/centreon/engine/configuration/command.hh rename to common/engine_legacy_conf/command.hh index 2ad5e998983..96f056a894b 100644 --- a/engine/inc/com/centreon/engine/configuration/command.hh +++ b/common/engine_legacy_conf/command.hh @@ -19,7 +19,7 @@ #ifndef CCE_CONFIGURATION_COMMAND_HH #define CCE_CONFIGURATION_COMMAND_HH -#include "com/centreon/engine/configuration/object.hh" +#include "object.hh" namespace com::centreon::engine { diff --git a/engine/src/configuration/connector.cc b/common/engine_legacy_conf/connector.cc similarity index 98% rename from engine/src/configuration/connector.cc rename to common/engine_legacy_conf/connector.cc index 3a26096f0da..95ed88ce3aa 100644 --- a/engine/src/configuration/connector.cc +++ b/common/engine_legacy_conf/connector.cc @@ -17,7 +17,7 @@ * For more information : contact@centreon.com * */ -#include "com/centreon/engine/configuration/connector.hh" +#include "connector.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon; diff --git a/engine/inc/com/centreon/engine/configuration/connector.hh b/common/engine_legacy_conf/connector.hh similarity index 97% rename from engine/inc/com/centreon/engine/configuration/connector.hh rename to common/engine_legacy_conf/connector.hh index adc1d5601a1..17cdc70aa40 100644 --- a/engine/inc/com/centreon/engine/configuration/connector.hh +++ b/common/engine_legacy_conf/connector.hh @@ -19,7 +19,7 @@ #ifndef CCE_CONFIGURATION_CONNECTOR_HH #define CCE_CONFIGURATION_CONNECTOR_HH -#include "com/centreon/engine/configuration/object.hh" +#include "object.hh" namespace com::centreon::engine { diff --git a/engine/src/configuration/contact.cc b/common/engine_legacy_conf/contact.cc similarity index 99% rename from engine/src/configuration/contact.cc rename to common/engine_legacy_conf/contact.cc index 931d2f02fb4..0f5577669a9 100644 --- a/engine/src/configuration/contact.cc +++ b/common/engine_legacy_conf/contact.cc @@ -16,10 +16,10 @@ * For more information : contact@centreon.com * */ -#include "com/centreon/engine/configuration/contact.hh" -#include "com/centreon/engine/configuration/host.hh" -#include "com/centreon/engine/configuration/service.hh" +#include "contact.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "host.hh" +#include "service.hh" using namespace com::centreon; using namespace com::centreon::engine; diff --git a/engine/inc/com/centreon/engine/configuration/contact.hh b/common/engine_legacy_conf/contact.hh similarity index 96% rename from engine/inc/com/centreon/engine/configuration/contact.hh rename to common/engine_legacy_conf/contact.hh index 324f20c80a5..dda65352c7b 100644 --- a/engine/inc/com/centreon/engine/configuration/contact.hh +++ b/common/engine_legacy_conf/contact.hh @@ -22,9 +22,9 @@ #include #include "com/centreon/common/opt.hh" -#include "com/centreon/engine/configuration/customvariable.hh" -#include "com/centreon/engine/configuration/group.hh" -#include "com/centreon/engine/configuration/object.hh" +#include "customvariable.hh" +#include "group.hh" +#include "object.hh" using com::centreon::common::opt; diff --git a/engine/src/configuration/contactgroup.cc b/common/engine_legacy_conf/contactgroup.cc similarity index 99% rename from engine/src/configuration/contactgroup.cc rename to common/engine_legacy_conf/contactgroup.cc index 178f1ff65ee..04e4fbf9bc6 100644 --- a/engine/src/configuration/contactgroup.cc +++ b/common/engine_legacy_conf/contactgroup.cc @@ -16,7 +16,7 @@ * For more information : contact@centreon.com * */ -#include "com/centreon/engine/configuration/contactgroup.hh" +#include "contactgroup.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon; diff --git a/engine/inc/com/centreon/engine/configuration/contactgroup.hh b/common/engine_legacy_conf/contactgroup.hh similarity index 95% rename from engine/inc/com/centreon/engine/configuration/contactgroup.hh rename to common/engine_legacy_conf/contactgroup.hh index 356731a8c34..8d3e2d14575 100644 --- a/engine/inc/com/centreon/engine/configuration/contactgroup.hh +++ b/common/engine_legacy_conf/contactgroup.hh @@ -20,8 +20,8 @@ #define CCE_CONFIGURATION_CONTACTGROUP_HH #include "com/centreon/common/opt.hh" -#include "com/centreon/engine/configuration/group.hh" -#include "com/centreon/engine/configuration/object.hh" +#include "group.hh" +#include "object.hh" namespace com::centreon::engine::configuration { diff --git a/engine/src/configuration/customvariable.cc b/common/engine_legacy_conf/customvariable.cc similarity index 96% rename from engine/src/configuration/customvariable.cc rename to common/engine_legacy_conf/customvariable.cc index d41dd32df75..6411e9daed3 100644 --- a/engine/src/configuration/customvariable.cc +++ b/common/engine_legacy_conf/customvariable.cc @@ -17,7 +17,7 @@ * */ -#include "com/centreon/engine/configuration/customvariable.hh" +#include "customvariable.hh" using namespace com::centreon::engine::configuration; diff --git a/engine/inc/com/centreon/engine/configuration/customvariable.hh b/common/engine_legacy_conf/customvariable.hh similarity index 100% rename from engine/inc/com/centreon/engine/configuration/customvariable.hh rename to common/engine_legacy_conf/customvariable.hh diff --git a/engine/src/configuration/daterange.cc b/common/engine_legacy_conf/daterange.cc similarity index 94% rename from engine/src/configuration/daterange.cc rename to common/engine_legacy_conf/daterange.cc index 44d536ad13e..b8d51eeb8c1 100644 --- a/engine/src/configuration/daterange.cc +++ b/common/engine_legacy_conf/daterange.cc @@ -16,7 +16,7 @@ * For more information : contact@centreon.com * */ -#include "com/centreon/engine/configuration/daterange.hh" +#include "daterange.hh" using namespace com::centreon::engine::configuration; @@ -218,10 +218,8 @@ std::ostream& operator<<(std::ostream& os, const timerange& obj) { uint32_t start_minutes((obj.range_start() % 3600) / 60); uint32_t end_hours(obj.range_end() / 3600); uint32_t end_minutes((obj.range_end() % 3600) / 60); - os << std::setfill('0') << std::setw(2) << start_hours << ":" - << std::setfill('0') << std::setw(2) << start_minutes << "-" - << std::setfill('0') << std::setw(2) << end_hours << ":" - << std::setfill('0') << std::setw(2) << end_minutes; + os << fmt::format("{:02}:{:02}-{:02}:{:02}", start_hours, start_minutes, + end_hours, end_minutes); return os; } @@ -249,14 +247,12 @@ std::ostream& operator<<(std::ostream& os, const std::list& obj) { */ static std::ostream& _dump_calendar_date(std::ostream& os, daterange const& obj) { - os << std::setfill('0') << std::setw(2) << obj.get_syear() << "-" - << std::setfill('0') << std::setw(2) << obj.get_smon() + 1 << "-" - << std::setfill('0') << std::setw(2) << obj.get_smday(); + os << fmt::format("{:02}-{:02}-{:02}", obj.get_syear(), obj.get_smon() + 1, + obj.get_smday()); if (obj.get_syear() != obj.get_eyear() || obj.get_smon() != obj.get_emon() || obj.get_smday() != obj.get_emday()) - os << " - " << std::setfill('0') << std::setw(2) << obj.get_eyear() << "-" - << std::setfill('0') << std::setw(2) << obj.get_emon() + 1 << "-" - << std::setfill('0') << std::setw(2) << obj.get_emday(); + os << fmt::format(" - {:02}-{:02}-{:02}", obj.get_eyear(), + obj.get_emon() + 1, obj.get_emday()); if (obj.get_skip_interval()) os << " / " << obj.get_skip_interval(); return os; diff --git a/engine/inc/com/centreon/engine/configuration/daterange.hh b/common/engine_legacy_conf/daterange.hh similarity index 100% rename from engine/inc/com/centreon/engine/configuration/daterange.hh rename to common/engine_legacy_conf/daterange.hh diff --git a/engine/inc/com/centreon/engine/configuration/file_info.hh b/common/engine_legacy_conf/file_info.hh similarity index 100% rename from engine/inc/com/centreon/engine/configuration/file_info.hh rename to common/engine_legacy_conf/file_info.hh diff --git a/engine/src/configuration/group.cc b/common/engine_legacy_conf/group.cc similarity index 99% rename from engine/src/configuration/group.cc rename to common/engine_legacy_conf/group.cc index 3f13e1a4f17..0eec05a1a50 100644 --- a/engine/src/configuration/group.cc +++ b/common/engine_legacy_conf/group.cc @@ -16,7 +16,8 @@ * For more information : contact@centreon.com * */ -#include "com/centreon/engine/configuration/group.hh" +#include "group.hh" +#include using namespace com::centreon::engine::configuration; diff --git a/engine/inc/com/centreon/engine/configuration/group.hh b/common/engine_legacy_conf/group.hh similarity index 100% rename from engine/inc/com/centreon/engine/configuration/group.hh rename to common/engine_legacy_conf/group.hh diff --git a/engine/src/configuration/host.cc b/common/engine_legacy_conf/host.cc similarity index 99% rename from engine/src/configuration/host.cc rename to common/engine_legacy_conf/host.cc index 5f3b47c4588..7ceb1bc7a69 100644 --- a/engine/src/configuration/host.cc +++ b/common/engine_legacy_conf/host.cc @@ -18,10 +18,9 @@ * */ -#include "com/centreon/engine/configuration/host.hh" -#include "absl/strings/numbers.h" -#include "absl/strings/str_split.h" -#include "absl/strings/string_view.h" +#include "host.hh" +#include +#include #include "bbdo/neb.pb.h" #include "com/centreon/exceptions/msg_fmt.hh" diff --git a/engine/inc/com/centreon/engine/configuration/host.hh b/common/engine_legacy_conf/host.hh similarity index 96% rename from engine/inc/com/centreon/engine/configuration/host.hh rename to common/engine_legacy_conf/host.hh index c6498e666b2..0c1257443bf 100644 --- a/engine/inc/com/centreon/engine/configuration/host.hh +++ b/common/engine_legacy_conf/host.hh @@ -20,11 +20,11 @@ #define CCE_CONFIGURATION_HOST_HH #include "com/centreon/common/opt.hh" -#include "com/centreon/engine/configuration/customvariable.hh" -#include "com/centreon/engine/configuration/group.hh" -#include "com/centreon/engine/configuration/object.hh" -#include "com/centreon/engine/configuration/point_2d.hh" -#include "com/centreon/engine/configuration/point_3d.hh" +#include "customvariable.hh" +#include "group.hh" +#include "object.hh" +#include "point_2d.hh" +#include "point_3d.hh" using com::centreon::common::opt; diff --git a/engine/src/configuration/hostdependency.cc b/common/engine_legacy_conf/hostdependency.cc similarity index 99% rename from engine/src/configuration/hostdependency.cc rename to common/engine_legacy_conf/hostdependency.cc index 5993c8f0166..347d37d2420 100644 --- a/engine/src/configuration/hostdependency.cc +++ b/common/engine_legacy_conf/hostdependency.cc @@ -18,8 +18,8 @@ * */ -#include "com/centreon/engine/configuration/state.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "state.hh" using namespace com::centreon; using namespace com::centreon::engine::configuration; diff --git a/engine/inc/com/centreon/engine/configuration/hostdependency.hh b/common/engine_legacy_conf/hostdependency.hh similarity index 97% rename from engine/inc/com/centreon/engine/configuration/hostdependency.hh rename to common/engine_legacy_conf/hostdependency.hh index e7862ee2e59..5114372a3b6 100644 --- a/engine/inc/com/centreon/engine/configuration/hostdependency.hh +++ b/common/engine_legacy_conf/hostdependency.hh @@ -20,8 +20,8 @@ #define CCE_CONFIGURATION_HOSTDEPENDENCY_HH #include "com/centreon/common/opt.hh" -#include "com/centreon/engine/configuration/group.hh" -#include "com/centreon/engine/configuration/object.hh" +#include "group.hh" +#include "object.hh" using com::centreon::common::opt; diff --git a/engine/src/configuration/hostescalation.cc b/common/engine_legacy_conf/hostescalation.cc similarity index 99% rename from engine/src/configuration/hostescalation.cc rename to common/engine_legacy_conf/hostescalation.cc index 24df969ace6..882fdf1e560 100644 --- a/engine/src/configuration/hostescalation.cc +++ b/common/engine_legacy_conf/hostescalation.cc @@ -17,7 +17,7 @@ * For more information : contact@centreon.com * */ -#include "com/centreon/engine/configuration/hostescalation.hh" +#include "hostescalation.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon; diff --git a/engine/inc/com/centreon/engine/configuration/hostescalation.hh b/common/engine_legacy_conf/hostescalation.hh similarity index 97% rename from engine/inc/com/centreon/engine/configuration/hostescalation.hh rename to common/engine_legacy_conf/hostescalation.hh index ce8a6ca90ef..7e1ce7a1617 100644 --- a/engine/inc/com/centreon/engine/configuration/hostescalation.hh +++ b/common/engine_legacy_conf/hostescalation.hh @@ -20,8 +20,8 @@ #define CCE_CONFIGURATION_HOSTESCALATION_HH #include "com/centreon/common/opt.hh" -#include "com/centreon/engine/configuration/group.hh" -#include "com/centreon/engine/configuration/object.hh" +#include "group.hh" +#include "object.hh" using com::centreon::common::opt; diff --git a/engine/src/configuration/hostgroup.cc b/common/engine_legacy_conf/hostgroup.cc similarity index 99% rename from engine/src/configuration/hostgroup.cc rename to common/engine_legacy_conf/hostgroup.cc index 7182bb2cdc2..5e6e6d6ed4f 100644 --- a/engine/src/configuration/hostgroup.cc +++ b/common/engine_legacy_conf/hostgroup.cc @@ -16,7 +16,7 @@ * For more information : contact@centreon.com * */ -#include "com/centreon/engine/configuration/hostgroup.hh" +#include "hostgroup.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon; diff --git a/engine/inc/com/centreon/engine/configuration/hostgroup.hh b/common/engine_legacy_conf/hostgroup.hh similarity index 96% rename from engine/inc/com/centreon/engine/configuration/hostgroup.hh rename to common/engine_legacy_conf/hostgroup.hh index 680abb59949..feccce9af95 100644 --- a/engine/inc/com/centreon/engine/configuration/hostgroup.hh +++ b/common/engine_legacy_conf/hostgroup.hh @@ -20,8 +20,8 @@ #define CCE_CONFIGURATION_HOSTGROUP_HH #include "com/centreon/common/opt.hh" -#include "com/centreon/engine/configuration/group.hh" -#include "com/centreon/engine/configuration/object.hh" +#include "group.hh" +#include "object.hh" namespace com::centreon::engine { diff --git a/engine/src/configuration/object.cc b/common/engine_legacy_conf/object.cc similarity index 88% rename from engine/src/configuration/object.cc rename to common/engine_legacy_conf/object.cc index cecce38f068..f732e2d8ecf 100644 --- a/engine/src/configuration/object.cc +++ b/common/engine_legacy_conf/object.cc @@ -17,25 +17,26 @@ * For more information : contact@centreon.com * */ -#include "com/centreon/engine/configuration/object.hh" -#include "com/centreon/engine/configuration/anomalydetection.hh" -#include "com/centreon/engine/configuration/command.hh" -#include "com/centreon/engine/configuration/connector.hh" -#include "com/centreon/engine/configuration/contact.hh" -#include "com/centreon/engine/configuration/contactgroup.hh" -#include "com/centreon/engine/configuration/host.hh" -#include "com/centreon/engine/configuration/hostdependency.hh" -#include "com/centreon/engine/configuration/hostescalation.hh" -#include "com/centreon/engine/configuration/hostgroup.hh" -#include "com/centreon/engine/configuration/service.hh" -#include "com/centreon/engine/configuration/servicedependency.hh" -#include "com/centreon/engine/configuration/serviceescalation.hh" -#include "com/centreon/engine/configuration/servicegroup.hh" -#include "com/centreon/engine/configuration/severity.hh" -#include "com/centreon/engine/configuration/tag.hh" -#include "com/centreon/engine/configuration/timeperiod.hh" +#include "object.hh" +#include +#include "anomalydetection.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "command.hh" #include "common/log_v2/log_v2.hh" +#include "connector.hh" +#include "contact.hh" +#include "contactgroup.hh" +#include "host.hh" +#include "hostdependency.hh" +#include "hostescalation.hh" +#include "hostgroup.hh" +#include "service.hh" +#include "servicedependency.hh" +#include "serviceescalation.hh" +#include "servicegroup.hh" +#include "severity.hh" +#include "tag.hh" +#include "timeperiod.hh" using namespace com::centreon; using namespace com::centreon::engine::configuration; @@ -199,7 +200,7 @@ bool object::parse(std::string const& line) { key.assign(line, 0, pos); value.assign(line, pos + 1, std::string::npos); } - boost::algorithm::trim(value); + value = absl::StripAsciiWhitespace(value); if (!parse(key.c_str(), value.c_str())) return object::parse(key.c_str(), value.c_str()); return true; diff --git a/engine/inc/com/centreon/engine/configuration/object.hh b/common/engine_legacy_conf/object.hh similarity index 100% rename from engine/inc/com/centreon/engine/configuration/object.hh rename to common/engine_legacy_conf/object.hh diff --git a/engine/src/configuration/parser.cc b/common/engine_legacy_conf/parser.cc similarity index 99% rename from engine/src/configuration/parser.cc rename to common/engine_legacy_conf/parser.cc index f5e737873e1..1158ff831e3 100644 --- a/engine/src/configuration/parser.cc +++ b/common/engine_legacy_conf/parser.cc @@ -16,7 +16,7 @@ * For more information : contact@centreon.com * */ -#include "com/centreon/engine/configuration/parser.hh" +#include "parser.hh" #include "com/centreon/exceptions/msg_fmt.hh" #include "com/centreon/io/directory_entry.hh" #include "common/log_v2/log_v2.hh" diff --git a/engine/inc/com/centreon/engine/configuration/parser.hh b/common/engine_legacy_conf/parser.hh similarity index 96% rename from engine/inc/com/centreon/engine/configuration/parser.hh rename to common/engine_legacy_conf/parser.hh index 42d9c052db3..4d1f2d424b9 100644 --- a/engine/inc/com/centreon/engine/configuration/parser.hh +++ b/common/engine_legacy_conf/parser.hh @@ -20,8 +20,8 @@ #define CCE_CONFIGURATION_PARSER_HH #include -#include "com/centreon/engine/configuration/file_info.hh" -#include "com/centreon/engine/configuration/state.hh" +#include "file_info.hh" +#include "state.hh" namespace com::centreon::engine { diff --git a/engine/src/configuration/point_2d.cc b/common/engine_legacy_conf/point_2d.cc similarity index 97% rename from engine/src/configuration/point_2d.cc rename to common/engine_legacy_conf/point_2d.cc index a777933084b..3b36be855be 100644 --- a/engine/src/configuration/point_2d.cc +++ b/common/engine_legacy_conf/point_2d.cc @@ -17,7 +17,7 @@ * For more information : contact@centreon.com * */ -#include "com/centreon/engine/configuration/point_2d.hh" +#include "point_2d.hh" using namespace com::centreon::engine::configuration; diff --git a/engine/inc/com/centreon/engine/configuration/point_2d.hh b/common/engine_legacy_conf/point_2d.hh similarity index 100% rename from engine/inc/com/centreon/engine/configuration/point_2d.hh rename to common/engine_legacy_conf/point_2d.hh diff --git a/engine/src/configuration/point_3d.cc b/common/engine_legacy_conf/point_3d.cc similarity index 97% rename from engine/src/configuration/point_3d.cc rename to common/engine_legacy_conf/point_3d.cc index 102b9183a98..262483451c6 100644 --- a/engine/src/configuration/point_3d.cc +++ b/common/engine_legacy_conf/point_3d.cc @@ -17,7 +17,7 @@ * For more information : contact@centreon.com * */ -#include "com/centreon/engine/configuration/point_3d.hh" +#include "point_3d.hh" using namespace com::centreon::engine::configuration; diff --git a/engine/inc/com/centreon/engine/configuration/point_3d.hh b/common/engine_legacy_conf/point_3d.hh similarity index 100% rename from engine/inc/com/centreon/engine/configuration/point_3d.hh rename to common/engine_legacy_conf/point_3d.hh diff --git a/engine/src/configuration/service.cc b/common/engine_legacy_conf/service.cc similarity index 99% rename from engine/src/configuration/service.cc rename to common/engine_legacy_conf/service.cc index fe7b0205bd6..fa9c55d72e6 100644 --- a/engine/src/configuration/service.cc +++ b/common/engine_legacy_conf/service.cc @@ -17,13 +17,13 @@ * */ -#include "com/centreon/engine/configuration/service.hh" +#include "service.hh" #include #include #include #include "bbdo/bam_state.pb.h" -#include "com/centreon/exceptions/msg_fmt.hh" #include "bbdo/neb.pb.h" +#include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon; using namespace com::centreon::engine::configuration; diff --git a/engine/inc/com/centreon/engine/configuration/service.hh b/common/engine_legacy_conf/service.hh similarity index 98% rename from engine/inc/com/centreon/engine/configuration/service.hh rename to common/engine_legacy_conf/service.hh index 109d6878ef8..b0edf116723 100644 --- a/engine/inc/com/centreon/engine/configuration/service.hh +++ b/common/engine_legacy_conf/service.hh @@ -20,9 +20,9 @@ #define CCE_CONFIGURATION_SERVICE_HH #include "com/centreon/common/opt.hh" -#include "com/centreon/engine/configuration/customvariable.hh" -#include "com/centreon/engine/configuration/group.hh" -#include "com/centreon/engine/configuration/object.hh" +#include "customvariable.hh" +#include "group.hh" +#include "object.hh" using com::centreon::common::opt; diff --git a/engine/src/configuration/servicedependency.cc b/common/engine_legacy_conf/servicedependency.cc similarity index 99% rename from engine/src/configuration/servicedependency.cc rename to common/engine_legacy_conf/servicedependency.cc index 1f70031d1a7..3b590b40cef 100644 --- a/engine/src/configuration/servicedependency.cc +++ b/common/engine_legacy_conf/servicedependency.cc @@ -18,7 +18,7 @@ * */ -#include "com/centreon/engine/configuration/servicedependency.hh" +#include "servicedependency.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon; diff --git a/engine/inc/com/centreon/engine/configuration/servicedependency.hh b/common/engine_legacy_conf/servicedependency.hh similarity index 97% rename from engine/inc/com/centreon/engine/configuration/servicedependency.hh rename to common/engine_legacy_conf/servicedependency.hh index 7cb9c5a1594..2b3a53fa2ac 100644 --- a/engine/inc/com/centreon/engine/configuration/servicedependency.hh +++ b/common/engine_legacy_conf/servicedependency.hh @@ -20,8 +20,8 @@ #define CCE_CONFIGURATION_SERVICEDEPENDENCY_HH #include "com/centreon/common/opt.hh" -#include "com/centreon/engine/configuration/group.hh" -#include "com/centreon/engine/configuration/object.hh" +#include "group.hh" +#include "object.hh" using com::centreon::common::opt; diff --git a/engine/src/configuration/serviceescalation.cc b/common/engine_legacy_conf/serviceescalation.cc similarity index 99% rename from engine/src/configuration/serviceescalation.cc rename to common/engine_legacy_conf/serviceescalation.cc index f41fc9a3571..a4d9951a4ef 100644 --- a/engine/src/configuration/serviceescalation.cc +++ b/common/engine_legacy_conf/serviceescalation.cc @@ -17,7 +17,7 @@ * */ -#include "com/centreon/engine/configuration/serviceescalation.hh" +#include "serviceescalation.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon; diff --git a/engine/inc/com/centreon/engine/configuration/serviceescalation.hh b/common/engine_legacy_conf/serviceescalation.hh similarity index 97% rename from engine/inc/com/centreon/engine/configuration/serviceescalation.hh rename to common/engine_legacy_conf/serviceescalation.hh index 7dcdb838bc5..84d53d093e5 100644 --- a/engine/inc/com/centreon/engine/configuration/serviceescalation.hh +++ b/common/engine_legacy_conf/serviceescalation.hh @@ -20,8 +20,8 @@ #define CCE_CONFIGURATION_SERVICEESCALATION_HH #include "com/centreon/common/opt.hh" -#include "com/centreon/engine/configuration/group.hh" -#include "com/centreon/engine/configuration/object.hh" +#include "group.hh" +#include "object.hh" using com::centreon::common::opt; diff --git a/engine/src/configuration/servicegroup.cc b/common/engine_legacy_conf/servicegroup.cc similarity index 99% rename from engine/src/configuration/servicegroup.cc rename to common/engine_legacy_conf/servicegroup.cc index 39ff98ffe09..57d02023445 100644 --- a/engine/src/configuration/servicegroup.cc +++ b/common/engine_legacy_conf/servicegroup.cc @@ -16,7 +16,7 @@ * For more information : contact@centreon.com * */ -#include "com/centreon/engine/configuration/servicegroup.hh" +#include "servicegroup.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon; diff --git a/engine/inc/com/centreon/engine/configuration/servicegroup.hh b/common/engine_legacy_conf/servicegroup.hh similarity index 96% rename from engine/inc/com/centreon/engine/configuration/servicegroup.hh rename to common/engine_legacy_conf/servicegroup.hh index caa2147f79e..fae2ec2c87d 100644 --- a/engine/inc/com/centreon/engine/configuration/servicegroup.hh +++ b/common/engine_legacy_conf/servicegroup.hh @@ -20,8 +20,8 @@ #define CCE_CONFIGURATION_SERVICEGROUP_HH #include "com/centreon/common/opt.hh" -#include "com/centreon/engine/configuration/group.hh" -#include "com/centreon/engine/configuration/object.hh" +#include "group.hh" +#include "object.hh" typedef std::set > set_pair_string; diff --git a/engine/src/configuration/severity.cc b/common/engine_legacy_conf/severity.cc similarity index 99% rename from engine/src/configuration/severity.cc rename to common/engine_legacy_conf/severity.cc index 6df971be114..8a0d021152e 100644 --- a/engine/src/configuration/severity.cc +++ b/common/engine_legacy_conf/severity.cc @@ -16,7 +16,7 @@ * For more information : contact@centreon.com * */ -#include "com/centreon/engine/configuration/severity.hh" +#include "severity.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon; diff --git a/engine/inc/com/centreon/engine/configuration/severity.hh b/common/engine_legacy_conf/severity.hh similarity index 97% rename from engine/inc/com/centreon/engine/configuration/severity.hh rename to common/engine_legacy_conf/severity.hh index 78f290c5540..ecca8c9ae9c 100644 --- a/engine/inc/com/centreon/engine/configuration/severity.hh +++ b/common/engine_legacy_conf/severity.hh @@ -21,7 +21,7 @@ #include -#include "com/centreon/engine/configuration/object.hh" +#include "object.hh" namespace com::centreon::engine::configuration { diff --git a/engine/src/configuration/state.cc b/common/engine_legacy_conf/state.cc similarity index 99% rename from engine/src/configuration/state.cc rename to common/engine_legacy_conf/state.cc index e70b1b18b17..3b818e522af 100644 --- a/engine/src/configuration/state.cc +++ b/common/engine_legacy_conf/state.cc @@ -16,7 +16,8 @@ * For more information : contact@centreon.com * */ -#include "com/centreon/engine/configuration/state.hh" +#include "state.hh" +#include #include "com/centreon/common/rapidjson_helper.hh" #include "com/centreon/exceptions/msg_fmt.hh" #include "common/log_v2/log_v2.hh" diff --git a/engine/inc/com/centreon/engine/configuration/state.hh b/common/engine_legacy_conf/state.hh similarity index 96% rename from engine/inc/com/centreon/engine/configuration/state.hh rename to common/engine_legacy_conf/state.hh index 33af15d6389..6d5bf435706 100644 --- a/engine/inc/com/centreon/engine/configuration/state.hh +++ b/common/engine_legacy_conf/state.hh @@ -19,22 +19,24 @@ #ifndef CCE_CONFIGURATION_STATE_HH #define CCE_CONFIGURATION_STATE_HH -#include "com/centreon/engine/configuration/anomalydetection.hh" -#include "com/centreon/engine/configuration/command.hh" -#include "com/centreon/engine/configuration/connector.hh" -#include "com/centreon/engine/configuration/contact.hh" -#include "com/centreon/engine/configuration/contactgroup.hh" -#include "com/centreon/engine/configuration/host.hh" -#include "com/centreon/engine/configuration/hostdependency.hh" -#include "com/centreon/engine/configuration/hostescalation.hh" -#include "com/centreon/engine/configuration/hostgroup.hh" -#include "com/centreon/engine/configuration/service.hh" -#include "com/centreon/engine/configuration/servicedependency.hh" -#include "com/centreon/engine/configuration/serviceescalation.hh" -#include "com/centreon/engine/configuration/servicegroup.hh" -#include "com/centreon/engine/configuration/severity.hh" -#include "com/centreon/engine/configuration/tag.hh" -#include "com/centreon/engine/configuration/timeperiod.hh" +#include +#include +#include "anomalydetection.hh" +#include "command.hh" +#include "connector.hh" +#include "contact.hh" +#include "contactgroup.hh" +#include "host.hh" +#include "hostdependency.hh" +#include "hostescalation.hh" +#include "hostgroup.hh" +#include "service.hh" +#include "servicedependency.hh" +#include "serviceescalation.hh" +#include "servicegroup.hh" +#include "severity.hh" +#include "tag.hh" +#include "timeperiod.hh" namespace com::centreon::engine::configuration { diff --git a/engine/src/configuration/tag.cc b/common/engine_legacy_conf/tag.cc similarity index 98% rename from engine/src/configuration/tag.cc rename to common/engine_legacy_conf/tag.cc index f17fd214a78..e3d3a42e3e5 100644 --- a/engine/src/configuration/tag.cc +++ b/common/engine_legacy_conf/tag.cc @@ -16,7 +16,7 @@ * For more information : contact@centreon.com * */ -#include "com/centreon/engine/configuration/tag.hh" +#include "tag.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon; diff --git a/engine/inc/com/centreon/engine/configuration/tag.hh b/common/engine_legacy_conf/tag.hh similarity index 97% rename from engine/inc/com/centreon/engine/configuration/tag.hh rename to common/engine_legacy_conf/tag.hh index d40d9c9a14f..31dd723f0c0 100644 --- a/engine/inc/com/centreon/engine/configuration/tag.hh +++ b/common/engine_legacy_conf/tag.hh @@ -21,7 +21,7 @@ #include -#include "com/centreon/engine/configuration/object.hh" +#include "object.hh" namespace com::centreon::engine { diff --git a/engine/src/configuration/timeperiod.cc b/common/engine_legacy_conf/timeperiod.cc similarity index 99% rename from engine/src/configuration/timeperiod.cc rename to common/engine_legacy_conf/timeperiod.cc index 4bb281be9f7..326437dde34 100644 --- a/engine/src/configuration/timeperiod.cc +++ b/common/engine_legacy_conf/timeperiod.cc @@ -17,10 +17,10 @@ * For more information : contact@centreon.com * */ -#include "com/centreon/engine/configuration/timeperiod.hh" +#include "timeperiod.hh" -#include "com/centreon/engine/configuration/daterange.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "daterange.hh" using namespace com::centreon; using namespace com::centreon::engine; diff --git a/engine/inc/com/centreon/engine/configuration/timeperiod.hh b/common/engine_legacy_conf/timeperiod.hh similarity index 95% rename from engine/inc/com/centreon/engine/configuration/timeperiod.hh rename to common/engine_legacy_conf/timeperiod.hh index dc2486e41d6..1e52df672b9 100644 --- a/engine/inc/com/centreon/engine/configuration/timeperiod.hh +++ b/common/engine_legacy_conf/timeperiod.hh @@ -20,9 +20,9 @@ #define CCE_CONFIGURATION_TIMEPERIOD_HH #include "com/centreon/common/opt.hh" -#include "com/centreon/engine/configuration/daterange.hh" -#include "com/centreon/engine/configuration/group.hh" -#include "com/centreon/engine/configuration/object.hh" +#include "daterange.hh" +#include "group.hh" +#include "object.hh" namespace com::centreon::engine { diff --git a/common/grpc/src/grpc_server.cc b/common/grpc/src/grpc_server.cc index 340cef4272b..22b9203a8d2 100644 --- a/common/grpc/src/grpc_server.cc +++ b/common/grpc/src/grpc_server.cc @@ -84,7 +84,7 @@ void grpc_server_base::_init(const builder_option& options) { builder.SetDefaultCompressionAlgorithm(algo); builder.SetDefaultCompressionLevel(GRPC_COMPRESS_LEVEL_HIGH); } - _server = std::move(builder.BuildAndStart()); + _server = builder.BuildAndStart(); } /** diff --git a/common/precomp_inc/precomp.hh b/common/precomp_inc/precomp.hh index 0b20d35411a..d7b064ec501 100644 --- a/common/precomp_inc/precomp.hh +++ b/common/precomp_inc/precomp.hh @@ -37,6 +37,7 @@ #include #include +#include #include #include #include diff --git a/engine/CMakeLists.txt b/engine/CMakeLists.txt index 053f7b2a0fb..e1855ab5156 100644 --- a/engine/CMakeLists.txt +++ b/engine/CMakeLists.txt @@ -352,13 +352,7 @@ configure_file("${INC_DIR}/compatibility/common.h.in" "${INC_DIR}/compatibility/common.h") # Locations definitions -add_definitions(-DDEFAULT_STATUS_FILE="${ENGINE_VAR_LOG_DIR}/status.dat") -add_definitions(-DDEFAULT_LOG_FILE="${ENGINE_VAR_LOG_DIR}/centengine.log") add_definitions(-DDEFAULT_LOG_ARCHIVE_PATH="${ENGINE_VAR_LOG_ARCHIVE_DIR}") -add_definitions(-DDEFAULT_DEBUG_FILE="${ENGINE_VAR_LOG_DIR}/centengine.debug") -add_definitions(-DDEFAULT_RETENTION_FILE="${ENGINE_VAR_LOG_DIR}/retention.dat") -add_definitions( - -DDEFAULT_COMMAND_FILE="${ENGINE_VAR_LIB_DIR}/rw/centengine.cmd") add_definitions(-DDEFAULT_CONFIG_FILE="${PREFIX_ENGINE_CONF}/centengine.cfg") add_definitions(-DSPDLOG_ACTIVE_LEVEL=SPDLOG_LEVEL_TRACE) @@ -508,6 +502,7 @@ target_link_libraries( ${PTHREAD_LIBRARIES} ${SOCKET_LIBRARIES} centreon_clib + engine_legacy_conf fmt::fmt spdlog::spdlog) diff --git a/engine/inc/com/centreon/engine/configuration/applier/contactgroup.hh b/engine/inc/com/centreon/engine/configuration/applier/contactgroup.hh index 26f3cadcc73..a17825bdb32 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/contactgroup.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/contactgroup.hh @@ -20,7 +20,7 @@ #define CCE_CONFIGURATION_APPLIER_CONTACTGROUP_HH #include "com/centreon/engine/configuration/applier/state.hh" -#include "com/centreon/engine/configuration/contactgroup.hh" +#include "common/engine_legacy_conf/contactgroup.hh" namespace com::centreon::engine { diff --git a/engine/inc/com/centreon/engine/configuration/applier/globals.hh b/engine/inc/com/centreon/engine/configuration/applier/globals.hh index 561ef400403..1ee1d7eb431 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/globals.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/globals.hh @@ -2,26 +2,24 @@ * Copyright 2011-2013 Merethis * Copyright 2014-2024 Centreon * - * This file is part of Centreon Engine. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Centreon Engine is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License version 2 - * as published by the Free Software Foundation. + * http://www.apache.org/licenses/LICENSE-2.0 * - * Centreon Engine is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. * - * You should have received a copy of the GNU General Public License - * along with Centreon Engine. If not, see - * . + * For more information : contact@centreon.com */ - #ifndef CCE_CONFIGURATION_APPLIER_GLOBALS_HH #define CCE_CONFIGURATION_APPLIER_GLOBALS_HH -#include "com/centreon/engine/configuration/state.hh" +#include "common/engine_legacy_conf/state.hh" namespace com::centreon::engine { diff --git a/engine/inc/com/centreon/engine/configuration/applier/hostgroup.hh b/engine/inc/com/centreon/engine/configuration/applier/hostgroup.hh index fed53baec2f..75815f1bff6 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/hostgroup.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/hostgroup.hh @@ -20,7 +20,7 @@ #define CCE_CONFIGURATION_APPLIER_HOSTGROUP_HH #include "com/centreon/engine/configuration/applier/state.hh" -#include "com/centreon/engine/configuration/hostgroup.hh" +#include "common/engine_legacy_conf/hostgroup.hh" namespace com::centreon::engine { diff --git a/engine/inc/com/centreon/engine/configuration/applier/logging.hh b/engine/inc/com/centreon/engine/configuration/applier/logging.hh index bfaf1dd3980..ff0c90a2702 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/logging.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/logging.hh @@ -20,9 +20,9 @@ #ifndef CCE_CONFIGURATION_APPLIER_LOGGING_HH #define CCE_CONFIGURATION_APPLIER_LOGGING_HH -#include "com/centreon/engine/configuration/state.hh" #include "com/centreon/logging/file.hh" #include "com/centreon/logging/syslogger.hh" +#include "common/engine_legacy_conf/state.hh" namespace com::centreon::engine { diff --git a/engine/inc/com/centreon/engine/configuration/applier/macros.hh b/engine/inc/com/centreon/engine/configuration/applier/macros.hh index 6b4b4657808..fb8462b034f 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/macros.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/macros.hh @@ -1,26 +1,25 @@ -/* -** Copyright 2011-2013 Merethis -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2013 Merethis + * Copyright 2014-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCE_CONFIGURATION_APPLIER_MACROS_HH #define CCE_CONFIGURATION_APPLIER_MACROS_HH -#include "com/centreon/engine/configuration/state.hh" +#include "common/engine_legacy_conf/state.hh" // Forward declaration. class nagios_macros; @@ -54,6 +53,6 @@ class macros { } // namespace applier } // namespace configuration -} +} // namespace com::centreon::engine #endif // !CCE_CONFIGURATION_APPLIER_MACROS_HH diff --git a/engine/inc/com/centreon/engine/configuration/applier/scheduler.hh b/engine/inc/com/centreon/engine/configuration/applier/scheduler.hh index 557a36442ef..78d19824499 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/scheduler.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/scheduler.hh @@ -1,28 +1,26 @@ -/* -** Copyright 2011-2016 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2016 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCE_CONFIGURATION_APPLIER_SCHEDULER_HH #define CCE_CONFIGURATION_APPLIER_SCHEDULER_HH #include "com/centreon/engine/configuration/applier/difference.hh" -#include "com/centreon/engine/configuration/state.hh" #include "com/centreon/engine/exceptions/error.hh" +#include "common/engine_legacy_conf/state.hh" // Forward declaration. namespace com::centreon::engine { diff --git a/engine/inc/com/centreon/engine/configuration/applier/servicegroup.hh b/engine/inc/com/centreon/engine/configuration/applier/servicegroup.hh index a4eefe860f0..7e5cb60bd96 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/servicegroup.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/servicegroup.hh @@ -20,7 +20,7 @@ #define CCE_CONFIGURATION_APPLIER_SERVICEGROUP_HH #include "com/centreon/engine/configuration/applier/state.hh" -#include "com/centreon/engine/configuration/servicegroup.hh" +#include "common/engine_legacy_conf/servicegroup.hh" namespace com::centreon::engine { diff --git a/engine/inc/com/centreon/engine/configuration/applier/state.hh b/engine/inc/com/centreon/engine/configuration/applier/state.hh index b680c9db183..62c4296d497 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/state.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/state.hh @@ -19,8 +19,8 @@ #define CCE_CONFIGURATION_APPLIER_STATE_HH #include "com/centreon/engine/configuration/applier/difference.hh" -#include "com/centreon/engine/configuration/state.hh" #include "com/centreon/engine/servicedependency.hh" +#include "common/engine_legacy_conf/state.hh" namespace com::centreon::engine { diff --git a/engine/inc/com/centreon/engine/globals.hh b/engine/inc/com/centreon/engine/globals.hh index d4c88d6cb65..bbe3ea115b5 100644 --- a/engine/inc/com/centreon/engine/globals.hh +++ b/engine/inc/com/centreon/engine/globals.hh @@ -24,12 +24,12 @@ #include #include "com/centreon/engine/circular_buffer.hh" -#include "com/centreon/engine/configuration/state.hh" #include "com/centreon/engine/events/sched_info.hh" #include "com/centreon/engine/events/timed_event.hh" #include "com/centreon/engine/nebmods.hh" #include "com/centreon/engine/restart_stats.hh" #include "com/centreon/engine/utils.hh" +#include "common/engine_legacy_conf/state.hh" #include "common/log_v2/log_v2.hh" /* Start/Restart statistics */ diff --git a/engine/inc/com/centreon/engine/hostdependency.hh b/engine/inc/com/centreon/engine/hostdependency.hh index 7ee9b336304..6bef7d90e05 100644 --- a/engine/inc/com/centreon/engine/hostdependency.hh +++ b/engine/inc/com/centreon/engine/hostdependency.hh @@ -19,8 +19,8 @@ #ifndef CCE_OBJECTS_HOSTDEPENDENCY_HH #define CCE_OBJECTS_HOSTDEPENDENCY_HH -#include "com/centreon/engine/configuration/hostdependency.hh" #include "com/centreon/engine/dependency.hh" +#include "common/engine_legacy_conf/hostdependency.hh" /* Forward declaration. */ namespace com::centreon::engine { diff --git a/engine/inc/com/centreon/engine/servicedependency.hh b/engine/inc/com/centreon/engine/servicedependency.hh index de2b2b733a3..9b25112a4c6 100644 --- a/engine/inc/com/centreon/engine/servicedependency.hh +++ b/engine/inc/com/centreon/engine/servicedependency.hh @@ -19,9 +19,9 @@ */ #ifndef CCE_OBJECTS_SERVICEDEPENDENCY_HH #define CCE_OBJECTS_SERVICEDEPENDENCY_HH -#include "com/centreon/engine/configuration/servicedependency.hh" #include "com/centreon/engine/dependency.hh" #include "com/centreon/engine/hash.hh" +#include "common/engine_legacy_conf/servicedependency.hh" /* Forward declaration. */ namespace com::centreon::engine { diff --git a/engine/inc/com/centreon/engine/timerange.hh b/engine/inc/com/centreon/engine/timerange.hh index 3ee0de199af..33e9ec4e56b 100644 --- a/engine/inc/com/centreon/engine/timerange.hh +++ b/engine/inc/com/centreon/engine/timerange.hh @@ -1,25 +1,23 @@ -/* -** Copyright 2011-2019 Centreon -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - +/** + * Copyright 2011-2019 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ #ifndef CCE_OBJECTS_TIMERANGE_HH #define CCE_OBJECTS_TIMERANGE_HH -#include "com/centreon/engine/configuration/daterange.hh" +#include "common/engine_legacy_conf/daterange.hh" namespace com::centreon::engine { class timerange { diff --git a/engine/src/config.cc b/engine/src/config.cc index cdbb2421cb2..f91eb07a218 100644 --- a/engine/src/config.cc +++ b/engine/src/config.cc @@ -21,10 +21,10 @@ #include "com/centreon/engine/config.hh" #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/configuration/applier/state.hh" -#include "com/centreon/engine/configuration/parser.hh" #include "com/centreon/engine/globals.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/string.hh" +#include "common/engine_legacy_conf/parser.hh" using namespace com::centreon::engine; using namespace com::centreon::engine::configuration::applier; diff --git a/engine/src/configuration/CMakeLists.txt b/engine/src/configuration/CMakeLists.txt index 2f936a13623..3a7d9d106d2 100644 --- a/engine/src/configuration/CMakeLists.txt +++ b/engine/src/configuration/CMakeLists.txt @@ -27,30 +27,6 @@ add_subdirectory(applier) set(FILES ${FILES} # Sources. - "${SRC_DIR}/anomalydetection.cc" - "${SRC_DIR}/command.cc" - "${SRC_DIR}/connector.cc" - "${SRC_DIR}/contact.cc" - "${SRC_DIR}/contactgroup.cc" - "${SRC_DIR}/customvariable.cc" - "${SRC_DIR}/daterange.cc" - "${SRC_DIR}/extended_conf.cc" - "${SRC_DIR}/group.cc" - "${SRC_DIR}/host.cc" - "${SRC_DIR}/hostdependency.cc" - "${SRC_DIR}/hostescalation.cc" - "${SRC_DIR}/hostgroup.cc" - "${SRC_DIR}/object.cc" - "${SRC_DIR}/parser.cc" - "${SRC_DIR}/point_2d.cc" - "${SRC_DIR}/point_3d.cc" - "${SRC_DIR}/state.cc" - "${SRC_DIR}/service.cc" - "${SRC_DIR}/servicedependency.cc" - "${SRC_DIR}/serviceescalation.cc" - "${SRC_DIR}/servicegroup.cc" - "${SRC_DIR}/severity.cc" - "${SRC_DIR}/tag.cc" - "${SRC_DIR}/timeperiod.cc" "${SRC_DIR}/whitelist.cc" + "${SRC_DIR}/extended_conf.cc" PARENT_SCOPE) diff --git a/engine/src/configuration/applier/command.cc b/engine/src/configuration/applier/command.cc index d2b0c82c9f2..da25e1189ae 100644 --- a/engine/src/configuration/applier/command.cc +++ b/engine/src/configuration/applier/command.cc @@ -210,7 +210,7 @@ void applier::command::remove_object(configuration::command const& obj) { * @param[in] obj Command object. */ void applier::command::resolve_object(configuration::command const& obj, - error_cnt& err) { + error_cnt& err [[maybe_unused]]) { if (!obj.connector().empty()) { connector_map::iterator found{ commands::connector::connectors.find(obj.connector())}; diff --git a/engine/src/configuration/applier/connector.cc b/engine/src/configuration/applier/connector.cc index 67039caf1ac..f44a12df06c 100644 --- a/engine/src/configuration/applier/connector.cc +++ b/engine/src/configuration/applier/connector.cc @@ -189,7 +189,6 @@ void applier::connector::remove_object(configuration::connector const& obj) { * * @param[in] obj Unused. */ -void applier::connector::resolve_object(configuration::connector const& obj, - error_cnt& err) { - (void)obj; -} +void applier::connector::resolve_object(configuration::connector const& obj + [[maybe_unused]], + error_cnt& err [[maybe_unused]]) {} diff --git a/engine/src/configuration/applier/servicedependency.cc b/engine/src/configuration/applier/servicedependency.cc index 777334486f8..c756237b3bf 100644 --- a/engine/src/configuration/applier/servicedependency.cc +++ b/engine/src/configuration/applier/servicedependency.cc @@ -21,11 +21,11 @@ #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/config.hh" #include "com/centreon/engine/configuration/applier/state.hh" -#include "com/centreon/engine/configuration/object.hh" -#include "com/centreon/engine/configuration/servicedependency.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" #include "com/centreon/engine/logging/logger.hh" +#include "common/engine_legacy_conf/object.hh" +#include "common/engine_legacy_conf/servicedependency.hh" using namespace com::centreon::engine::configuration; diff --git a/engine/src/configuration/applier/serviceescalation.cc b/engine/src/configuration/applier/serviceescalation.cc index fb1eee822c6..92aa9062a5f 100644 --- a/engine/src/configuration/applier/serviceescalation.cc +++ b/engine/src/configuration/applier/serviceescalation.cc @@ -20,10 +20,10 @@ #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/config.hh" #include "com/centreon/engine/configuration/applier/state.hh" -#include "com/centreon/engine/configuration/serviceescalation.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" #include "com/centreon/engine/logging/logger.hh" +#include "common/engine_legacy_conf/serviceescalation.hh" using namespace com::centreon::engine::configuration; diff --git a/engine/src/configuration/applier/severity.cc b/engine/src/configuration/applier/severity.cc index 04be7930374..fd3018fc8c2 100644 --- a/engine/src/configuration/applier/severity.cc +++ b/engine/src/configuration/applier/severity.cc @@ -21,10 +21,10 @@ #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/config.hh" -#include "com/centreon/engine/configuration/severity.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" #include "com/centreon/engine/severity.hh" +#include "common/engine_legacy_conf/severity.hh" using namespace com::centreon; using namespace com::centreon::engine; diff --git a/engine/src/configuration/applier/state.cc b/engine/src/configuration/applier/state.cc index 0fe5e5c5e00..44bd189d5ad 100644 --- a/engine/src/configuration/applier/state.cc +++ b/engine/src/configuration/applier/state.cc @@ -43,7 +43,6 @@ #include "com/centreon/engine/configuration/applier/severity.hh" #include "com/centreon/engine/configuration/applier/tag.hh" #include "com/centreon/engine/configuration/applier/timeperiod.hh" -#include "com/centreon/engine/configuration/command.hh" #include "com/centreon/engine/configuration/whitelist.hh" #include "com/centreon/engine/globals.hh" #include "com/centreon/engine/logging/broker_sink.hh" @@ -52,6 +51,7 @@ #include "com/centreon/engine/version.hh" #include "com/centreon/engine/xpddefault.hh" #include "com/centreon/engine/xsddefault.hh" +#include "common/engine_legacy_conf/command.hh" #include "common/log_v2/log_v2.hh" using namespace com::centreon; diff --git a/engine/src/configuration/applier/tag.cc b/engine/src/configuration/applier/tag.cc index 182515f6a52..3f82237998f 100644 --- a/engine/src/configuration/applier/tag.cc +++ b/engine/src/configuration/applier/tag.cc @@ -21,10 +21,10 @@ #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/config.hh" -#include "com/centreon/engine/configuration/tag.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" #include "com/centreon/engine/tag.hh" +#include "common/engine_legacy_conf/tag.hh" using namespace com::centreon; using namespace com::centreon::engine; diff --git a/engine/src/configuration/extended_conf.cc b/engine/src/configuration/extended_conf.cc index a350cf51764..8042d50cde9 100644 --- a/engine/src/configuration/extended_conf.cc +++ b/engine/src/configuration/extended_conf.cc @@ -17,8 +17,8 @@ */ #include "com/centreon/engine/configuration/extended_conf.hh" -#include "com/centreon/engine/configuration/state.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/engine_legacy_conf/state.hh" #include "common/log_v2/log_v2.hh" using namespace com::centreon::engine::configuration; diff --git a/engine/src/configuration/whitelist.cc b/engine/src/configuration/whitelist.cc index ae2780b75a7..41e4bb6d0f2 100644 --- a/engine/src/configuration/whitelist.cc +++ b/engine/src/configuration/whitelist.cc @@ -53,7 +53,7 @@ const std::string command_blacklist_output( * by default on error rapidyaml call abort so this handler */ void on_rapidyaml_error(const char* buff, - size_t length, + size_t length [[maybe_unused]], ryml::Location loc, void*) { throw msg_fmt("fail to parse {} at line {}: {}", loc.name.data(), loc.line, diff --git a/engine/src/contactgroup.cc b/engine/src/contactgroup.cc index 63e819c0f8c..1118b04e731 100644 --- a/engine/src/contactgroup.cc +++ b/engine/src/contactgroup.cc @@ -16,7 +16,7 @@ * For more information : contact@centreon.com * */ -#include "com/centreon/engine/configuration/contactgroup.hh" +#include "common/engine_legacy_conf/contactgroup.hh" #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/contact.hh" diff --git a/engine/src/daterange.cc b/engine/src/daterange.cc index 6404f230a73..1afa0e99a95 100644 --- a/engine/src/daterange.cc +++ b/engine/src/daterange.cc @@ -20,10 +20,10 @@ #include "com/centreon/engine/daterange.hh" #include "com/centreon/engine/common.hh" -#include "com/centreon/engine/configuration/daterange.hh" #include "com/centreon/engine/string.hh" #include "com/centreon/engine/timeperiod.hh" #include "com/centreon/engine/timerange.hh" +#include "common/engine_legacy_conf/daterange.hh" using namespace com::centreon::engine; diff --git a/engine/src/diagnostic.cc b/engine/src/diagnostic.cc index 0c2d3f443ef..b204e6d57b0 100644 --- a/engine/src/diagnostic.cc +++ b/engine/src/diagnostic.cc @@ -19,13 +19,13 @@ #include "com/centreon/engine/diagnostic.hh" #include -#include "com/centreon/engine/configuration/parser.hh" -#include "com/centreon/engine/configuration/state.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/version.hh" #include "com/centreon/io/file_stream.hh" #include "com/centreon/process.hh" +#include "common/engine_legacy_conf/parser.hh" +#include "common/engine_legacy_conf/state.hh" using namespace com::centreon; using namespace com::centreon::engine; diff --git a/engine/src/events/loop.cc b/engine/src/events/loop.cc index 7a3c981f435..9d65742fe7c 100644 --- a/engine/src/events/loop.cc +++ b/engine/src/events/loop.cc @@ -28,11 +28,11 @@ #include "com/centreon/engine/command_manager.hh" #include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/configuration/extended_conf.hh" -#include "com/centreon/engine/configuration/parser.hh" #include "com/centreon/engine/globals.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/statusdata.hh" #include "com/centreon/logging/engine.hh" +#include "common/engine_legacy_conf/parser.hh" using namespace com::centreon::engine; using namespace com::centreon::engine::events; diff --git a/engine/src/main.cc b/engine/src/main.cc index 7ea59d82e0a..59d9ab6c217 100644 --- a/engine/src/main.cc +++ b/engine/src/main.cc @@ -51,8 +51,6 @@ namespace asio = boost::asio; #include "com/centreon/engine/configuration/applier/logging.hh" #include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/configuration/extended_conf.hh" -#include "com/centreon/engine/configuration/parser.hh" -#include "com/centreon/engine/configuration/state.hh" #include "com/centreon/engine/diagnostic.hh" #include "com/centreon/engine/downtimes/downtime_manager.hh" #include "com/centreon/engine/enginerpc.hh" @@ -71,6 +69,8 @@ namespace asio = boost::asio; #include "com/centreon/engine/version.hh" #include "com/centreon/io/directory_entry.hh" #include "com/centreon/logging/engine.hh" +#include "common/engine_legacy_conf/parser.hh" +#include "common/engine_legacy_conf/state.hh" #include "common/log_v2/log_v2.hh" using namespace com::centreon::engine; diff --git a/engine/tests/checks/anomalydetection.cc b/engine/tests/checks/anomalydetection.cc index cb78afc4717..973241f2cef 100644 --- a/engine/tests/checks/anomalydetection.cc +++ b/engine/tests/checks/anomalydetection.cc @@ -34,10 +34,10 @@ #include "com/centreon/engine/configuration/applier/host.hh" #include "com/centreon/engine/configuration/applier/service.hh" #include "com/centreon/engine/configuration/applier/servicedependency.hh" -#include "com/centreon/engine/configuration/host.hh" -#include "com/centreon/engine/configuration/service.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" +#include "common/engine_legacy_conf/host.hh" +#include "common/engine_legacy_conf/service.hh" #include "helper.hh" using namespace com::centreon; diff --git a/engine/tests/checks/service_check.cc b/engine/tests/checks/service_check.cc index 3046a65960f..c08257ab1e1 100644 --- a/engine/tests/checks/service_check.cc +++ b/engine/tests/checks/service_check.cc @@ -34,12 +34,12 @@ #include "com/centreon/engine/configuration/applier/serviceescalation.hh" #include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/configuration/applier/timeperiod.hh" -#include "com/centreon/engine/configuration/host.hh" -#include "com/centreon/engine/configuration/service.hh" -#include "com/centreon/engine/configuration/state.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/serviceescalation.hh" #include "com/centreon/engine/timezone_manager.hh" +#include "common/engine_legacy_conf/host.hh" +#include "common/engine_legacy_conf/service.hh" +#include "common/engine_legacy_conf/state.hh" #include "helper.hh" using namespace com::centreon; diff --git a/engine/tests/checks/service_retention.cc b/engine/tests/checks/service_retention.cc index 22e1fd35fef..6d9b15ea371 100644 --- a/engine/tests/checks/service_retention.cc +++ b/engine/tests/checks/service_retention.cc @@ -35,13 +35,13 @@ #include "com/centreon/engine/configuration/applier/serviceescalation.hh" #include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/configuration/applier/timeperiod.hh" -#include "com/centreon/engine/configuration/host.hh" -#include "com/centreon/engine/configuration/service.hh" -#include "com/centreon/engine/configuration/state.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/retention/dump.hh" #include "com/centreon/engine/serviceescalation.hh" #include "com/centreon/engine/timezone_manager.hh" +#include "common/engine_legacy_conf/host.hh" +#include "common/engine_legacy_conf/service.hh" +#include "common/engine_legacy_conf/state.hh" #include "helper.hh" using namespace com::centreon; diff --git a/engine/tests/configuration/applier/applier-anomalydetection.cc b/engine/tests/configuration/applier/applier-anomalydetection.cc index 308359e4b12..a30aa2686f0 100644 --- a/engine/tests/configuration/applier/applier-anomalydetection.cc +++ b/engine/tests/configuration/applier/applier-anomalydetection.cc @@ -28,8 +28,8 @@ #include "com/centreon/engine/configuration/applier/contactgroup.hh" #include "com/centreon/engine/configuration/applier/host.hh" #include "com/centreon/engine/configuration/applier/service.hh" -#include "com/centreon/engine/configuration/host.hh" #include "com/centreon/engine/exceptions/error.hh" +#include "common/engine_legacy_conf/host.hh" #include "helper.hh" using namespace com::centreon; diff --git a/engine/tests/configuration/applier/applier-command.cc b/engine/tests/configuration/applier/applier-command.cc old mode 100755 new mode 100644 index 3035c263a09..99dd042d60e --- a/engine/tests/configuration/applier/applier-command.cc +++ b/engine/tests/configuration/applier/applier-command.cc @@ -25,9 +25,9 @@ #include "com/centreon/engine/configuration/applier/connector.hh" #include "com/centreon/engine/configuration/applier/contact.hh" #include "com/centreon/engine/configuration/applier/host.hh" -#include "com/centreon/engine/configuration/command.hh" -#include "com/centreon/engine/configuration/connector.hh" #include "com/centreon/engine/macros/grab_host.hh" +#include "common/engine_legacy_conf/command.hh" +#include "common/engine_legacy_conf/connector.hh" #include "helper.hh" using namespace com::centreon; diff --git a/engine/tests/configuration/applier/applier-connector.cc b/engine/tests/configuration/applier/applier-connector.cc index c0bc411371b..1b304e5373b 100644 --- a/engine/tests/configuration/applier/applier-connector.cc +++ b/engine/tests/configuration/applier/applier-connector.cc @@ -21,7 +21,7 @@ #include "com/centreon/engine/commands/connector.hh" #include "com/centreon/engine/configuration/applier/command.hh" #include "com/centreon/engine/configuration/applier/connector.hh" -#include "com/centreon/engine/configuration/connector.hh" +#include "common/engine_legacy_conf/connector.hh" #include "helper.hh" using namespace com::centreon; diff --git a/engine/tests/configuration/applier/applier-contact.cc b/engine/tests/configuration/applier/applier-contact.cc index bff735f72ab..ba7bcfd65bc 100644 --- a/engine/tests/configuration/applier/applier-contact.cc +++ b/engine/tests/configuration/applier/applier-contact.cc @@ -24,9 +24,9 @@ #include "com/centreon/engine/configuration/applier/contact.hh" #include "com/centreon/engine/configuration/applier/contactgroup.hh" #include "com/centreon/engine/configuration/applier/timeperiod.hh" -#include "com/centreon/engine/configuration/contact.hh" #include "com/centreon/engine/contact.hh" #include "com/centreon/engine/contactgroup.hh" +#include "common/engine_legacy_conf/contact.hh" #include "helper.hh" using namespace com::centreon; diff --git a/engine/tests/configuration/applier/applier-contactgroup.cc b/engine/tests/configuration/applier/applier-contactgroup.cc index ccbef264891..906e0e5e275 100644 --- a/engine/tests/configuration/applier/applier-contactgroup.cc +++ b/engine/tests/configuration/applier/applier-contactgroup.cc @@ -21,8 +21,8 @@ #include "com/centreon/engine/configuration/applier/command.hh" #include "com/centreon/engine/configuration/applier/contact.hh" #include "com/centreon/engine/configuration/applier/contactgroup.hh" -#include "com/centreon/engine/configuration/contact.hh" #include "com/centreon/engine/contactgroup.hh" +#include "common/engine_legacy_conf/contact.hh" #include "helper.hh" using namespace com::centreon; diff --git a/engine/tests/configuration/applier/applier-global.cc b/engine/tests/configuration/applier/applier-global.cc index 107abebe923..5f10347cbd4 100644 --- a/engine/tests/configuration/applier/applier-global.cc +++ b/engine/tests/configuration/applier/applier-global.cc @@ -18,11 +18,11 @@ */ #include -#include -#include #include -#include "com/centreon/engine/configuration/state.hh" +#include "com/centreon/engine/configuration/applier/hostescalation.hh" #include "com/centreon/engine/globals.hh" +#include "common/engine_legacy_conf/parser.hh" +#include "common/engine_legacy_conf/state.hh" #include "helper.hh" using namespace com::centreon; diff --git a/engine/tests/configuration/applier/applier-host.cc b/engine/tests/configuration/applier/applier-host.cc index 7250d45dc3f..ebc1f3cb65c 100644 --- a/engine/tests/configuration/applier/applier-host.cc +++ b/engine/tests/configuration/applier/applier-host.cc @@ -23,10 +23,10 @@ #include "com/centreon/engine/configuration/applier/command.hh" #include "com/centreon/engine/configuration/applier/host.hh" #include "com/centreon/engine/configuration/applier/service.hh" -#include "com/centreon/engine/configuration/host.hh" -#include "com/centreon/engine/configuration/service.hh" #include "com/centreon/engine/host.hh" #include "com/centreon/engine/timezone_manager.hh" +#include "common/engine_legacy_conf/host.hh" +#include "common/engine_legacy_conf/service.hh" #include "helper.hh" using namespace com::centreon; diff --git a/engine/tests/configuration/applier/applier-hostdependency.cc b/engine/tests/configuration/applier/applier-hostdependency.cc index 6429646d270..4cdf0da7565 100644 --- a/engine/tests/configuration/applier/applier-hostdependency.cc +++ b/engine/tests/configuration/applier/applier-hostdependency.cc @@ -34,12 +34,12 @@ #include "com/centreon/engine/configuration/applier/hostdependency.hh" #include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/configuration/applier/timeperiod.hh" -#include "com/centreon/engine/configuration/host.hh" -#include "com/centreon/engine/configuration/service.hh" -#include "com/centreon/engine/configuration/state.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/serviceescalation.hh" #include "com/centreon/engine/timezone_manager.hh" +#include "common/engine_legacy_conf/host.hh" +#include "common/engine_legacy_conf/service.hh" +#include "common/engine_legacy_conf/state.hh" #include "helper.hh" using namespace com::centreon; diff --git a/engine/tests/configuration/applier/applier-hostescalation.cc b/engine/tests/configuration/applier/applier-hostescalation.cc index 8cdee2a6141..4917df88721 100644 --- a/engine/tests/configuration/applier/applier-hostescalation.cc +++ b/engine/tests/configuration/applier/applier-hostescalation.cc @@ -18,13 +18,13 @@ */ #include -#include -#include -#include -#include #include #include #include +#include "com/centreon/engine/configuration/applier/host.hh" +#include "com/centreon/engine/configuration/applier/hostescalation.hh" +#include "com/centreon/engine/configuration/applier/state.hh" +#include "common/engine_legacy_conf/state.hh" using namespace com::centreon; using namespace com::centreon::engine; diff --git a/engine/tests/configuration/applier/applier-hostgroup.cc b/engine/tests/configuration/applier/applier-hostgroup.cc index 3747fac883d..2d62f135f74 100644 --- a/engine/tests/configuration/applier/applier-hostgroup.cc +++ b/engine/tests/configuration/applier/applier-hostgroup.cc @@ -21,9 +21,9 @@ #include "com/centreon/engine/configuration/applier/command.hh" #include "com/centreon/engine/configuration/applier/host.hh" #include "com/centreon/engine/configuration/applier/hostgroup.hh" -#include "com/centreon/engine/configuration/hostgroup.hh" #include "com/centreon/engine/macros/grab_host.hh" #include "com/centreon/engine/timezone_manager.hh" +#include "common/engine_legacy_conf/hostgroup.hh" #include "helper.hh" using namespace com::centreon; diff --git a/engine/tests/configuration/applier/applier-log.cc b/engine/tests/configuration/applier/applier-log.cc index b3b0c707cd7..50b014bd6a3 100644 --- a/engine/tests/configuration/applier/applier-log.cc +++ b/engine/tests/configuration/applier/applier-log.cc @@ -18,11 +18,11 @@ */ #include -#include -#include #include +#include "com/centreon/engine/configuration/applier/hostescalation.hh" +#include "common/engine_legacy_conf/parser.hh" -#include "com/centreon/engine/configuration/state.hh" +#include "common/engine_legacy_conf/state.hh" #include "helper.hh" using namespace com::centreon; diff --git a/engine/tests/configuration/applier/applier-service.cc b/engine/tests/configuration/applier/applier-service.cc index abba80764f3..12a4788ccff 100644 --- a/engine/tests/configuration/applier/applier-service.cc +++ b/engine/tests/configuration/applier/applier-service.cc @@ -27,13 +27,13 @@ #include "com/centreon/engine/configuration/applier/host.hh" #include "com/centreon/engine/configuration/applier/service.hh" #include "com/centreon/engine/configuration/applier/tag.hh" -#include "com/centreon/engine/configuration/host.hh" -#include "com/centreon/engine/configuration/object.hh" -#include "com/centreon/engine/configuration/service.hh" #include "com/centreon/engine/contact.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/host.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "common/engine_legacy_conf/host.hh" +#include "common/engine_legacy_conf/object.hh" +#include "common/engine_legacy_conf/service.hh" #include "helper.hh" using namespace com::centreon; diff --git a/engine/tests/configuration/applier/applier-servicegroup.cc b/engine/tests/configuration/applier/applier-servicegroup.cc index 50c117ac4f7..34aa9bf2b8d 100644 --- a/engine/tests/configuration/applier/applier-servicegroup.cc +++ b/engine/tests/configuration/applier/applier-servicegroup.cc @@ -24,8 +24,8 @@ #include "com/centreon/engine/configuration/applier/host.hh" #include "com/centreon/engine/configuration/applier/service.hh" #include "com/centreon/engine/configuration/applier/servicegroup.hh" -#include "com/centreon/engine/configuration/service.hh" #include "com/centreon/engine/servicegroup.hh" +#include "common/engine_legacy_conf/service.hh" #include "helper.hh" using namespace com::centreon; diff --git a/engine/tests/configuration/applier/applier-state.cc b/engine/tests/configuration/applier/applier-state.cc index 7eb09f57a42..8c3a278f1c7 100644 --- a/engine/tests/configuration/applier/applier-state.cc +++ b/engine/tests/configuration/applier/applier-state.cc @@ -21,9 +21,9 @@ #include #include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/configuration/extended_conf.hh" -#include "com/centreon/engine/configuration/parser.hh" -#include "com/centreon/engine/configuration/state.hh" #include "com/centreon/engine/globals.hh" +#include "common/engine_legacy_conf/parser.hh" +#include "common/engine_legacy_conf/state.hh" using namespace com::centreon::engine; diff --git a/engine/tests/configuration/contact.cc b/engine/tests/configuration/contact.cc index 4d53553e0f7..0a6a1bff83e 100644 --- a/engine/tests/configuration/contact.cc +++ b/engine/tests/configuration/contact.cc @@ -16,7 +16,7 @@ * For more information : contact@centreon.com * */ -#include "com/centreon/engine/configuration/contact.hh" +#include "common/engine_legacy_conf/contact.hh" #include #include "helper.hh" diff --git a/engine/tests/configuration/host.cc b/engine/tests/configuration/host.cc index d90da73c140..a6835f310b0 100644 --- a/engine/tests/configuration/host.cc +++ b/engine/tests/configuration/host.cc @@ -1,23 +1,23 @@ /** -* Copyright 2016 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2016 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ -#include "com/centreon/engine/configuration/host.hh" +#include "common/engine_legacy_conf/host.hh" #include #include "com/centreon/engine/exceptions/error.hh" diff --git a/engine/tests/configuration/object.cc b/engine/tests/configuration/object.cc index 2d3eadef9ef..dbf6de5cffe 100644 --- a/engine/tests/configuration/object.cc +++ b/engine/tests/configuration/object.cc @@ -1,26 +1,26 @@ /** -* Copyright 2016 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ + * Copyright 2016 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ #include -#include "com/centreon/engine/configuration/parser.hh" -#include "com/centreon/engine/configuration/service.hh" +#include "common/engine_legacy_conf/parser.hh" +#include "common/engine_legacy_conf/service.hh" using namespace com::centreon; using namespace com::centreon::engine; diff --git a/engine/tests/configuration/service.cc b/engine/tests/configuration/service.cc index e84bf9892b6..e92b4189bcc 100644 --- a/engine/tests/configuration/service.cc +++ b/engine/tests/configuration/service.cc @@ -1,23 +1,21 @@ /** -* Copyright 2016 Centreon -* -* This file is part of Centreon Engine. -* -* Centreon Engine is free software: you can redistribute it and/or -* modify it under the terms of the GNU General Public License version 2 -* as published by the Free Software Foundation. -* -* Centreon Engine is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Centreon Engine. If not, see -* . -*/ - -#include "com/centreon/engine/configuration/service.hh" + * Copyright 2016-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ +#include "common/engine_legacy_conf/service.hh" #include #include "com/centreon/engine/exceptions/error.hh" diff --git a/engine/tests/configuration/severity.cc b/engine/tests/configuration/severity.cc index fce65fbab87..67a12409684 100644 --- a/engine/tests/configuration/severity.cc +++ b/engine/tests/configuration/severity.cc @@ -17,7 +17,7 @@ * */ -#include "com/centreon/engine/configuration/severity.hh" +#include "common/engine_legacy_conf/severity.hh" #include #include "helper.hh" diff --git a/engine/tests/configuration/tag.cc b/engine/tests/configuration/tag.cc index db4b1c0f5f8..1ac709690e9 100644 --- a/engine/tests/configuration/tag.cc +++ b/engine/tests/configuration/tag.cc @@ -17,10 +17,10 @@ * */ -#include "com/centreon/engine/configuration/tag.hh" +#include "common/engine_legacy_conf/tag.hh" #include -#include "com/centreon/engine/configuration/object.hh" +#include "common/engine_legacy_conf/object.hh" #include "helper.hh" using namespace com::centreon; diff --git a/engine/tests/configuration/timeperiod-test.cc b/engine/tests/configuration/timeperiod-test.cc index 5073a024362..01eb2176c68 100644 --- a/engine/tests/configuration/timeperiod-test.cc +++ b/engine/tests/configuration/timeperiod-test.cc @@ -25,8 +25,8 @@ #include "com/centreon/engine/common.hh" #include "com/centreon/engine/configuration/applier/timeperiod.hh" -#include "com/centreon/engine/configuration/daterange.hh" #include "com/centreon/engine/globals.hh" +#include "common/engine_legacy_conf/daterange.hh" using namespace com::centreon::engine::configuration; using namespace com::centreon::engine; diff --git a/engine/tests/custom_vars/extcmd.cc b/engine/tests/custom_vars/extcmd.cc old mode 100755 new mode 100644 index 5833fd7584e..c742ee56287 --- a/engine/tests/custom_vars/extcmd.cc +++ b/engine/tests/custom_vars/extcmd.cc @@ -25,8 +25,8 @@ #include "com/centreon/engine/configuration/applier/command.hh" #include "com/centreon/engine/configuration/applier/contact.hh" #include "com/centreon/engine/configuration/applier/host.hh" -#include "com/centreon/engine/configuration/state.hh" #include "com/centreon/engine/macros/grab_host.hh" +#include "common/engine_legacy_conf/state.hh" #include "helper.hh" using namespace com::centreon; diff --git a/engine/tests/downtimes/downtime_finder.cc b/engine/tests/downtimes/downtime_finder.cc index 423aeed7630..ae334733b28 100644 --- a/engine/tests/downtimes/downtime_finder.cc +++ b/engine/tests/downtimes/downtime_finder.cc @@ -24,12 +24,12 @@ #include "com/centreon/engine/configuration/applier/contact.hh" #include "com/centreon/engine/configuration/applier/host.hh" #include "com/centreon/engine/configuration/applier/service.hh" -#include "com/centreon/engine/configuration/contact.hh" -#include "com/centreon/engine/configuration/host.hh" -#include "com/centreon/engine/configuration/service.hh" #include "com/centreon/engine/downtimes/downtime.hh" #include "com/centreon/engine/downtimes/downtime_manager.hh" #include "com/centreon/engine/downtimes/service_downtime.hh" +#include "common/engine_legacy_conf/contact.hh" +#include "common/engine_legacy_conf/host.hh" +#include "common/engine_legacy_conf/service.hh" #include "helper.hh" #include "test_engine.hh" diff --git a/engine/tests/enginerpc/enginerpc.cc b/engine/tests/enginerpc/enginerpc.cc index c44963989b1..728b83b682b 100644 --- a/engine/tests/enginerpc/enginerpc.cc +++ b/engine/tests/enginerpc/enginerpc.cc @@ -42,12 +42,12 @@ #include "com/centreon/engine/configuration/applier/hostgroup.hh" #include "com/centreon/engine/configuration/applier/service.hh" #include "com/centreon/engine/configuration/applier/servicegroup.hh" -#include "com/centreon/engine/configuration/contact.hh" -#include "com/centreon/engine/configuration/hostgroup.hh" #include "com/centreon/engine/downtimes/downtime_manager.hh" #include "com/centreon/engine/events/loop.hh" #include "com/centreon/engine/timezone_manager.hh" #include "com/centreon/engine/version.hh" +#include "common/engine_legacy_conf/contact.hh" +#include "common/engine_legacy_conf/hostgroup.hh" #include "helper.hh" using namespace com::centreon; diff --git a/engine/tests/external_commands/anomalydetection.cc b/engine/tests/external_commands/anomalydetection.cc index 96afd9e5d5d..aad292aaeea 100644 --- a/engine/tests/external_commands/anomalydetection.cc +++ b/engine/tests/external_commands/anomalydetection.cc @@ -29,11 +29,11 @@ #include "com/centreon/engine/configuration/applier/contact.hh" #include "com/centreon/engine/configuration/applier/host.hh" #include "com/centreon/engine/configuration/applier/service.hh" -#include "com/centreon/engine/configuration/contact.hh" -#include "com/centreon/engine/configuration/state.hh" #include "com/centreon/engine/events/loop.hh" #include "com/centreon/engine/timezone_manager.hh" #include "com/centreon/engine/version.hh" +#include "common/engine_legacy_conf/contact.hh" +#include "common/engine_legacy_conf/state.hh" #include "helper.hh" using namespace com::centreon; diff --git a/engine/tests/external_commands/service.cc b/engine/tests/external_commands/service.cc index e9f55852974..84345cf9fb7 100644 --- a/engine/tests/external_commands/service.cc +++ b/engine/tests/external_commands/service.cc @@ -24,9 +24,9 @@ #include "com/centreon/engine/commands/commands.hh" #include "com/centreon/engine/configuration/applier/command.hh" #include "com/centreon/engine/configuration/applier/host.hh" -#include "com/centreon/engine/configuration/state.hh" #include "com/centreon/engine/events/loop.hh" #include "com/centreon/process_manager.hh" +#include "common/engine_legacy_conf/state.hh" #include "helper.hh" using namespace com::centreon; diff --git a/engine/tests/helper.hh b/engine/tests/helper.hh index d2b485c10cc..208531351ab 100644 --- a/engine/tests/helper.hh +++ b/engine/tests/helper.hh @@ -19,7 +19,7 @@ #ifndef CENTREON_ENGINE_TESTS_HELPER_HH_ #define CENTREON_ENGINE_TESTS_HELPER_HH_ -#include +#include extern com::centreon::engine::configuration::state* config; diff --git a/engine/tests/loop/loop.cc b/engine/tests/loop/loop.cc index 2d9988dbed8..6b455818173 100644 --- a/engine/tests/loop/loop.cc +++ b/engine/tests/loop/loop.cc @@ -27,10 +27,10 @@ #include "com/centreon/engine/configuration/applier/contact.hh" #include "com/centreon/engine/configuration/applier/host.hh" #include "com/centreon/engine/configuration/applier/service.hh" -#include "com/centreon/engine/configuration/host.hh" -#include "com/centreon/engine/configuration/service.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/serviceescalation.hh" +#include "common/engine_legacy_conf/host.hh" +#include "common/engine_legacy_conf/service.hh" #include "helper.hh" using namespace com::centreon; diff --git a/engine/tests/macros/macro.cc b/engine/tests/macros/macro.cc index fff4d22da81..9663a39a47b 100644 --- a/engine/tests/macros/macro.cc +++ b/engine/tests/macros/macro.cc @@ -19,8 +19,8 @@ #include #include -#include "com/centreon/engine/configuration/state.hh" #include "com/centreon/engine/globals.hh" +#include "common/engine_legacy_conf/state.hh" #include #include @@ -30,11 +30,11 @@ #include #include #include -#include #include #include #include #include +#include #include "../helper.hh" #include "../test_engine.hh" #include "../timeperiod/utils.hh" diff --git a/engine/tests/macros/macro_hostname.cc b/engine/tests/macros/macro_hostname.cc index 4a57cec5449..feac8d44c7c 100644 --- a/engine/tests/macros/macro_hostname.cc +++ b/engine/tests/macros/macro_hostname.cc @@ -19,30 +19,30 @@ #include #include -#include "com/centreon/engine/configuration/state.hh" #include "com/centreon/engine/globals.hh" +#include "common/engine_legacy_conf/state.hh" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include "../helper.hh" #include "../test_engine.hh" #include "../timeperiod/utils.hh" #include "com/centreon/engine/checks/checker.hh" #include "com/centreon/engine/commands/commands.hh" +#include "com/centreon/engine/configuration/applier/command.hh" +#include "com/centreon/engine/configuration/applier/contact.hh" #include "com/centreon/engine/configuration/applier/contactgroup.hh" +#include "com/centreon/engine/configuration/applier/host.hh" +#include "com/centreon/engine/configuration/applier/hostgroup.hh" +#include "com/centreon/engine/configuration/applier/service.hh" #include "com/centreon/engine/configuration/applier/serviceescalation.hh" +#include "com/centreon/engine/configuration/applier/servicegroup.hh" +#include "com/centreon/engine/configuration/applier/state.hh" +#include "com/centreon/engine/configuration/applier/timeperiod.hh" +#include "com/centreon/engine/hostescalation.hh" +#include "com/centreon/engine/macros.hh" +#include "com/centreon/engine/macros/grab_host.hh" +#include "com/centreon/engine/macros/process.hh" #include "com/centreon/engine/timeperiod.hh" +#include "common/engine_legacy_conf/parser.hh" using namespace com::centreon; using namespace com::centreon::engine; diff --git a/engine/tests/macros/macro_service.cc b/engine/tests/macros/macro_service.cc index 01be150cfc9..eca9965f227 100644 --- a/engine/tests/macros/macro_service.cc +++ b/engine/tests/macros/macro_service.cc @@ -19,8 +19,8 @@ #include #include -#include "com/centreon/engine/configuration/state.hh" #include "com/centreon/engine/globals.hh" +#include "common/engine_legacy_conf/state.hh" #include #include @@ -30,11 +30,11 @@ #include #include #include -#include #include #include #include #include +#include #include "../helper.hh" #include "../test_engine.hh" #include "../timeperiod/utils.hh" diff --git a/engine/tests/notifications/host_downtime_notification.cc b/engine/tests/notifications/host_downtime_notification.cc index a4f2a32a4c9..b0d5ab373dd 100644 --- a/engine/tests/notifications/host_downtime_notification.cc +++ b/engine/tests/notifications/host_downtime_notification.cc @@ -28,10 +28,10 @@ #include "com/centreon/engine/configuration/applier/contactgroup.hh" #include "com/centreon/engine/configuration/applier/host.hh" #include "com/centreon/engine/configuration/applier/hostescalation.hh" -#include "com/centreon/engine/configuration/host.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/hostescalation.hh" #include "com/centreon/engine/timeperiod.hh" +#include "common/engine_legacy_conf/host.hh" #include "helper.hh" using namespace com::centreon; diff --git a/engine/tests/notifications/host_flapping_notification.cc b/engine/tests/notifications/host_flapping_notification.cc index f670d0bb46c..b9b98014e8c 100644 --- a/engine/tests/notifications/host_flapping_notification.cc +++ b/engine/tests/notifications/host_flapping_notification.cc @@ -25,12 +25,12 @@ #include "../timeperiod/utils.hh" #include "com/centreon/engine/configuration/applier/contact.hh" #include "com/centreon/engine/configuration/applier/host.hh" -#include "com/centreon/engine/configuration/host.hh" -#include "com/centreon/engine/configuration/state.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/host.hh" #include "com/centreon/engine/hostescalation.hh" #include "com/centreon/engine/timezone_manager.hh" +#include "common/engine_legacy_conf/host.hh" +#include "common/engine_legacy_conf/state.hh" #include "helper.hh" using namespace com::centreon; diff --git a/engine/tests/notifications/host_normal_notification.cc b/engine/tests/notifications/host_normal_notification.cc index 67b513bd6dc..661c41d943a 100644 --- a/engine/tests/notifications/host_normal_notification.cc +++ b/engine/tests/notifications/host_normal_notification.cc @@ -33,14 +33,14 @@ #include "com/centreon/engine/configuration/applier/host.hh" #include "com/centreon/engine/configuration/applier/hostdependency.hh" #include "com/centreon/engine/configuration/applier/hostescalation.hh" -#include "com/centreon/engine/configuration/host.hh" -#include "com/centreon/engine/configuration/hostescalation.hh" -#include "com/centreon/engine/configuration/state.hh" #include "com/centreon/engine/downtimes/downtime_manager.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" #include "com/centreon/engine/retention/dump.hh" #include "com/centreon/engine/timezone_manager.hh" +#include "common/engine_legacy_conf/host.hh" +#include "common/engine_legacy_conf/hostescalation.hh" +#include "common/engine_legacy_conf/state.hh" using namespace com::centreon; using namespace com::centreon::engine; diff --git a/engine/tests/notifications/host_recovery_notification.cc b/engine/tests/notifications/host_recovery_notification.cc index 5bffa4bf1ad..eb9663bc564 100644 --- a/engine/tests/notifications/host_recovery_notification.cc +++ b/engine/tests/notifications/host_recovery_notification.cc @@ -24,10 +24,10 @@ #include "../helper.hh" #include "../timeperiod/utils.hh" #include "com/centreon/engine/configuration/applier/host.hh" -#include "com/centreon/engine/configuration/host.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/host.hh" #include "com/centreon/engine/hostescalation.hh" +#include "common/engine_legacy_conf/host.hh" using namespace com::centreon; using namespace com::centreon::engine; diff --git a/engine/tests/notifications/service_downtime_notification_test.cc b/engine/tests/notifications/service_downtime_notification_test.cc index 003b497d863..5c90fe68c7a 100644 --- a/engine/tests/notifications/service_downtime_notification_test.cc +++ b/engine/tests/notifications/service_downtime_notification_test.cc @@ -35,10 +35,10 @@ #include "com/centreon/engine/configuration/applier/service.hh" #include "com/centreon/engine/configuration/applier/servicedependency.hh" #include "com/centreon/engine/configuration/applier/serviceescalation.hh" -#include "com/centreon/engine/configuration/host.hh" -#include "com/centreon/engine/configuration/service.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/serviceescalation.hh" +#include "common/engine_legacy_conf/host.hh" +#include "common/engine_legacy_conf/service.hh" #include "helper.hh" using namespace com::centreon; diff --git a/engine/tests/notifications/service_flapping_notification.cc b/engine/tests/notifications/service_flapping_notification.cc index 3d3f5563af0..0a3d97838d4 100644 --- a/engine/tests/notifications/service_flapping_notification.cc +++ b/engine/tests/notifications/service_flapping_notification.cc @@ -28,12 +28,12 @@ #include "com/centreon/engine/configuration/applier/contact.hh" #include "com/centreon/engine/configuration/applier/host.hh" #include "com/centreon/engine/configuration/applier/service.hh" -#include "com/centreon/engine/configuration/host.hh" -#include "com/centreon/engine/configuration/service.hh" #include "com/centreon/engine/retention/dump.hh" #include "com/centreon/engine/serviceescalation.hh" #include "com/centreon/engine/timezone_manager.hh" #include "com/centreon/process_manager.hh" +#include "common/engine_legacy_conf/host.hh" +#include "common/engine_legacy_conf/service.hh" #include "helper.hh" using namespace com::centreon; diff --git a/engine/tests/notifications/service_normal_notification.cc b/engine/tests/notifications/service_normal_notification.cc index d56a713cde6..a0fe779eb99 100644 --- a/engine/tests/notifications/service_normal_notification.cc +++ b/engine/tests/notifications/service_normal_notification.cc @@ -35,10 +35,10 @@ #include "com/centreon/engine/configuration/applier/service.hh" #include "com/centreon/engine/configuration/applier/servicedependency.hh" #include "com/centreon/engine/configuration/applier/serviceescalation.hh" -#include "com/centreon/engine/configuration/host.hh" -#include "com/centreon/engine/configuration/service.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/serviceescalation.hh" +#include "common/engine_legacy_conf/host.hh" +#include "common/engine_legacy_conf/service.hh" #include "helper.hh" using namespace com::centreon; diff --git a/engine/tests/notifications/service_timeperiod_notification.cc b/engine/tests/notifications/service_timeperiod_notification.cc index 86b9a0376f3..ce4ffa184c9 100644 --- a/engine/tests/notifications/service_timeperiod_notification.cc +++ b/engine/tests/notifications/service_timeperiod_notification.cc @@ -36,12 +36,12 @@ #include "com/centreon/engine/configuration/applier/servicedependency.hh" #include "com/centreon/engine/configuration/applier/serviceescalation.hh" #include "com/centreon/engine/configuration/applier/state.hh" -#include "com/centreon/engine/configuration/host.hh" -#include "com/centreon/engine/configuration/service.hh" -#include "com/centreon/engine/configuration/state.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/serviceescalation.hh" #include "com/centreon/engine/timeperiod.hh" +#include "common/engine_legacy_conf/host.hh" +#include "common/engine_legacy_conf/service.hh" +#include "common/engine_legacy_conf/state.hh" #include "helper.hh" using namespace com::centreon; diff --git a/engine/tests/opentelemetry/open_telemetry_test.cc b/engine/tests/opentelemetry/open_telemetry_test.cc index 14e2ec38470..2286fe34964 100644 --- a/engine/tests/opentelemetry/open_telemetry_test.cc +++ b/engine/tests/opentelemetry/open_telemetry_test.cc @@ -38,8 +38,8 @@ #include "com/centreon/engine/configuration/applier/contact.hh" #include "com/centreon/engine/configuration/applier/host.hh" #include "com/centreon/engine/configuration/applier/service.hh" -#include "com/centreon/engine/configuration/host.hh" -#include "com/centreon/engine/configuration/service.hh" +#include "common/engine_legacy_conf/host.hh" +#include "common/engine_legacy_conf/service.hh" #include "opentelemetry/proto/collector/metrics/v1/metrics_service.pb.h" #include "opentelemetry/proto/common/v1/common.pb.h" diff --git a/engine/tests/opentelemetry/opentelemetry_test.cc b/engine/tests/opentelemetry/opentelemetry_test.cc index d26d169ff87..19d385c9214 100644 --- a/engine/tests/opentelemetry/opentelemetry_test.cc +++ b/engine/tests/opentelemetry/opentelemetry_test.cc @@ -38,8 +38,8 @@ #include "com/centreon/engine/configuration/applier/contact.hh" #include "com/centreon/engine/configuration/applier/host.hh" #include "com/centreon/engine/configuration/applier/service.hh" -#include "com/centreon/engine/configuration/host.hh" -#include "com/centreon/engine/configuration/service.hh" +#include "common/engine_legacy_conf/host.hh" +#include "common/engine_legacy_conf/service.hh" #include "opentelemetry/proto/collector/metrics/v1/metrics_service.pb.h" #include "opentelemetry/proto/common/v1/common.pb.h" diff --git a/engine/tests/opentelemetry/otl_converter_test.cc b/engine/tests/opentelemetry/otl_converter_test.cc index 558970ad7fe..8f7d8c36df4 100644 --- a/engine/tests/opentelemetry/otl_converter_test.cc +++ b/engine/tests/opentelemetry/otl_converter_test.cc @@ -29,8 +29,8 @@ #include "com/centreon/engine/configuration/applier/contact.hh" #include "com/centreon/engine/configuration/applier/host.hh" #include "com/centreon/engine/configuration/applier/service.hh" -#include "com/centreon/engine/configuration/host.hh" -#include "com/centreon/engine/configuration/service.hh" +#include "common/engine_legacy_conf/host.hh" +#include "common/engine_legacy_conf/service.hh" #include "opentelemetry/proto/collector/metrics/v1/metrics_service.pb.h" #include "opentelemetry/proto/common/v1/common.pb.h" diff --git a/engine/tests/test_engine.cc b/engine/tests/test_engine.cc index 30daa0c6516..1c24630e8b0 100644 --- a/engine/tests/test_engine.cc +++ b/engine/tests/test_engine.cc @@ -22,7 +22,7 @@ #include "com/centreon/engine/commands/commands.hh" #include "com/centreon/engine/configuration/applier/command.hh" #include "com/centreon/engine/configuration/applier/timeperiod.hh" -#include "com/centreon/engine/configuration/state.hh" +#include "common/engine_legacy_conf/state.hh" using namespace com::centreon::engine; using namespace com::centreon::engine::downtimes; diff --git a/engine/tests/test_engine.hh b/engine/tests/test_engine.hh index f20334c7577..843cb87a4ef 100644 --- a/engine/tests/test_engine.hh +++ b/engine/tests/test_engine.hh @@ -23,15 +23,15 @@ #include -#include "com/centreon/engine/configuration/anomalydetection.hh" -#include "com/centreon/engine/configuration/contact.hh" -#include "com/centreon/engine/configuration/contactgroup.hh" -#include "com/centreon/engine/configuration/host.hh" -#include "com/centreon/engine/configuration/hostdependency.hh" -#include "com/centreon/engine/configuration/hostescalation.hh" -#include "com/centreon/engine/configuration/service.hh" -#include "com/centreon/engine/configuration/servicedependency.hh" -#include "com/centreon/engine/configuration/serviceescalation.hh" +#include "common/engine_legacy_conf/anomalydetection.hh" +#include "common/engine_legacy_conf/contact.hh" +#include "common/engine_legacy_conf/contactgroup.hh" +#include "common/engine_legacy_conf/host.hh" +#include "common/engine_legacy_conf/hostdependency.hh" +#include "common/engine_legacy_conf/hostescalation.hh" +#include "common/engine_legacy_conf/service.hh" +#include "common/engine_legacy_conf/servicedependency.hh" +#include "common/engine_legacy_conf/serviceescalation.hh" using namespace com::centreon::engine; diff --git a/engine/tests/timeperiod/get_next_valid_time/exceptions_test.cc b/engine/tests/timeperiod/get_next_valid_time/exceptions_test.cc index 8f08a0f3276..bdf0f7add12 100644 --- a/engine/tests/timeperiod/get_next_valid_time/exceptions_test.cc +++ b/engine/tests/timeperiod/get_next_valid_time/exceptions_test.cc @@ -19,10 +19,10 @@ #include #include "../../timeperiod/utils.hh" #include "com/centreon/engine/configuration/applier/timeperiod.hh" -#include "com/centreon/engine/configuration/timeperiod.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/string.hh" #include "com/centreon/engine/timeperiod.hh" +#include "common/engine_legacy_conf/timeperiod.hh" #include "helper.hh" From d5f6e8caa8801179c55d9904f967e17f8c96f580 Mon Sep 17 00:00:00 2001 From: tuntoja <58987095+tuntoja@users.noreply.github.com> Date: Tue, 2 Jul 2024 10:50:46 +0200 Subject: [PATCH 57/60] fix(get-version): handle dev maintenance branches (#1487) --- .github/workflows/get-version.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/get-version.yml b/.github/workflows/get-version.yml index eff58cd5573..c48ef8ca58e 100644 --- a/.github/workflows/get-version.yml +++ b/.github/workflows/get-version.yml @@ -101,6 +101,11 @@ jobs: echo "release_cloud=1" >> $GITHUB_OUTPUT echo "release_type=$GITHUB_RELEASE_TYPE" >> $GITHUB_OUTPUT ;; + dev-[2-9][0-9].[0-9][0-9].x) + echo "release=`date +%s`.`echo ${{ github.sha }} | cut -c -7`" >> $GITHUB_OUTPUT + echo "release_cloud=0" >> $GITHUB_OUTPUT + echo "release_type=$GITHUB_RELEASE_TYPE" >> $GITHUB_OUTPUT + ;; release* | hotfix*) # Handle workflow_dispatch run triggers and run a dispatch ONLY for cloud release GITHUB_RELEASE_BRANCH_BASE_REF_NAME="$(gh pr view $BRANCHNAME -q .baseRefName --json headRefName,baseRefName,state)" From 7821c28ce1fdb2c3b9ad2d6720e4278ae9443e0d Mon Sep 17 00:00:00 2001 From: David Boucher Date: Tue, 2 Jul 2024 14:14:41 +0200 Subject: [PATCH 58/60] cleanup(engine): perfdata files not used anymore. They are removed. * enh(engine): perfdata files in engine are definitely removed * fix(engine): ut tests fail because of removed perfdata REFS: MON-34072 --- common/engine_legacy_conf/state.cc | 322 ------- common/engine_legacy_conf/state.hh | 44 - engine/CMakeLists.txt | 2 - .../engine/configuration/applier/scheduler.hh | 2 - engine/inc/com/centreon/engine/xpddefault.hh | 65 -- engine/inc/compatibility/xpddefault.h | 26 - engine/src/compatibility/CMakeLists.txt | 1 - engine/src/configuration/applier/macros.cc | 2 - engine/src/configuration/applier/scheduler.cc | 52 -- engine/src/configuration/applier/state.cc | 51 -- engine/src/host.cc | 4 - engine/src/service.cc | 3 - engine/src/xpddefault.cc | 836 ------------------ engine/tests/CMakeLists.txt | 1 - engine/tests/macros/macro_hostname.cc | 23 - engine/tests/macros/macro_service.cc | 23 - engine/tests/perfdata/perfdata.cc | 32 - 17 files changed, 1489 deletions(-) delete mode 100644 engine/inc/com/centreon/engine/xpddefault.hh delete mode 100644 engine/inc/compatibility/xpddefault.h delete mode 100644 engine/src/xpddefault.cc delete mode 100644 engine/tests/perfdata/perfdata.cc diff --git a/common/engine_legacy_conf/state.cc b/common/engine_legacy_conf/state.cc index 3b818e522af..5086b3d6439 100644 --- a/common/engine_legacy_conf/state.cc +++ b/common/engine_legacy_conf/state.cc @@ -187,16 +187,6 @@ void state::_init_setter() { "host_freshness_check_interval"); SETTER(const std::string&, _set_host_inter_check_delay_method, "host_inter_check_delay_method"); - SETTER(const std::string&, host_perfdata_command, "host_perfdata_command"); - SETTER(const std::string&, host_perfdata_file, "host_perfdata_file"); - SETTER(const std::string&, _set_host_perfdata_file_mode, - "host_perfdata_file_mode"); - SETTER(const std::string&, host_perfdata_file_processing_command, - "host_perfdata_file_processing_command"); - SETTER(unsigned int, host_perfdata_file_processing_interval, - "host_perfdata_file_processing_interval"); - SETTER(const std::string&, host_perfdata_file_template, - "host_perfdata_file_template"); SETTER(const std::string&, illegal_output_chars, "illegal_macro_output_chars"); SETTER(const std::string&, illegal_object_chars, "illegal_object_name_chars"); @@ -252,17 +242,6 @@ void state::_init_setter() { "service_inter_check_delay_method"); SETTER(const std::string&, _set_service_interleave_factor_method, "service_interleave_factor"); - SETTER(const std::string&, service_perfdata_command, - "service_perfdata_command"); - SETTER(const std::string&, service_perfdata_file, "service_perfdata_file"); - SETTER(const std::string&, _set_service_perfdata_file_mode, - "service_perfdata_file_mode"); - SETTER(const std::string&, service_perfdata_file_processing_command, - "service_perfdata_file_processing_command"); - SETTER(unsigned int, service_perfdata_file_processing_interval, - "service_perfdata_file_processing_interval"); - SETTER(const std::string&, service_perfdata_file_template, - "service_perfdata_file_template"); SETTER(unsigned int, check_reaper_interval, "service_reaper_frequency"); SETTER(float, sleep_time, "sleep_time"); SETTER(bool, soft_state_dependencies, "soft_state_dependencies"); @@ -350,13 +329,6 @@ static unsigned int const default_host_check_timeout(30); static unsigned int const default_host_freshness_check_interval(60); static state::inter_check_delay const default_host_inter_check_delay_method( state::icd_smart); -static state::perfdata_file_mode const default_host_perfdata_file_mode( - state::mode_pipe); -static unsigned int const default_host_perfdata_file_processing_interval(0); -static std::string const default_host_perfdata_file_template( - "[HOSTPERFDATA]\t$TIMET$\t$HOSTNAME$\t$HOSTEXECUTIONTIME$\t$HOSTOUTPUT$" - "\t$" - "HOSTPERFDATA$"); static std::string const default_illegal_object_chars(""); static std::string const default_illegal_output_chars("`~$&|'\"<>"); static unsigned int const default_interval_length(60); @@ -398,13 +370,6 @@ static state::inter_check_delay const default_service_inter_check_delay_method( state::icd_smart); static state::interleave_factor const default_service_interleave_factor_method( state::ilf_smart); -static state::perfdata_file_mode const default_service_perfdata_file_mode( - state::mode_pipe); -static unsigned int const default_service_perfdata_file_processing_interval(0); -static std::string const default_service_perfdata_file_template( - "[SERVICEPERFDATA]\t$TIMET$\t$HOSTNAME$\t$SERVICEDESC$\t$" - "SERVICEEXECUTIONTIME$\t$SERVICELATENCY$\t$SERVICEOUTPUT$\t$" - "SERVICEPERFDATA$"); static float const default_sleep_time(0.5); static bool const default_soft_state_dependencies(false); static std::string const default_state_retention_file(DEFAULT_RETENTION_FILE); @@ -490,10 +455,6 @@ state::state() _host_check_timeout(default_host_check_timeout), _host_freshness_check_interval(default_host_freshness_check_interval), _host_inter_check_delay_method(default_host_inter_check_delay_method), - _host_perfdata_file_mode(default_host_perfdata_file_mode), - _host_perfdata_file_processing_interval( - default_host_perfdata_file_processing_interval), - _host_perfdata_file_template(default_host_perfdata_file_template), _illegal_object_chars(default_illegal_object_chars), _illegal_output_chars(default_illegal_output_chars), _interval_length(default_interval_length), @@ -544,10 +505,6 @@ state::state() default_service_inter_check_delay_method), _service_interleave_factor_method( default_service_interleave_factor_method), - _service_perfdata_file_mode(default_service_perfdata_file_mode), - _service_perfdata_file_processing_interval( - default_service_perfdata_file_processing_interval), - _service_perfdata_file_template(default_service_perfdata_file_template), _sleep_time(default_sleep_time), _soft_state_dependencies(default_soft_state_dependencies), _state_retention_file(default_state_retention_file), @@ -661,14 +618,6 @@ state& state::operator=(state const& right) { _host_check_timeout = right._host_check_timeout; _host_freshness_check_interval = right._host_freshness_check_interval; _host_inter_check_delay_method = right._host_inter_check_delay_method; - _host_perfdata_command = right._host_perfdata_command; - _host_perfdata_file = right._host_perfdata_file; - _host_perfdata_file_mode = right._host_perfdata_file_mode; - _host_perfdata_file_processing_command = - right._host_perfdata_file_processing_command; - _host_perfdata_file_processing_interval = - right._host_perfdata_file_processing_interval; - _host_perfdata_file_template = right._host_perfdata_file_template; _illegal_object_chars = right._illegal_object_chars; _illegal_output_chars = right._illegal_output_chars; _interval_length = right._interval_length; @@ -720,14 +669,6 @@ state& state::operator=(state const& right) { _service_freshness_check_interval = right._service_freshness_check_interval; _service_inter_check_delay_method = right._service_inter_check_delay_method; _service_interleave_factor_method = right._service_interleave_factor_method; - _service_perfdata_command = right._service_perfdata_command; - _service_perfdata_file = right._service_perfdata_file; - _service_perfdata_file_mode = right._service_perfdata_file_mode; - _service_perfdata_file_processing_command = - right._service_perfdata_file_processing_command; - _service_perfdata_file_processing_interval = - right._service_perfdata_file_processing_interval; - _service_perfdata_file_template = right._service_perfdata_file_template; _sleep_time = right._sleep_time; _soft_state_dependencies = right._soft_state_dependencies; _state_retention_file = right._state_retention_file; @@ -830,14 +771,6 @@ bool state::operator==(state const& right) const noexcept { _host_check_timeout == right._host_check_timeout && _host_freshness_check_interval == right._host_freshness_check_interval && _host_inter_check_delay_method == right._host_inter_check_delay_method && - _host_perfdata_command == right._host_perfdata_command && - _host_perfdata_file == right._host_perfdata_file && - _host_perfdata_file_mode == right._host_perfdata_file_mode && - _host_perfdata_file_processing_command == - right._host_perfdata_file_processing_command && - _host_perfdata_file_processing_interval == - right._host_perfdata_file_processing_interval && - _host_perfdata_file_template == right._host_perfdata_file_template && _illegal_object_chars == right._illegal_object_chars && _illegal_output_chars == right._illegal_output_chars && _interval_length == right._interval_length && @@ -889,15 +822,6 @@ bool state::operator==(state const& right) const noexcept { right._service_inter_check_delay_method && _service_interleave_factor_method == right._service_interleave_factor_method && - _service_perfdata_command == right._service_perfdata_command && - _service_perfdata_file == right._service_perfdata_file && - _service_perfdata_file_mode == right._service_perfdata_file_mode && - _service_perfdata_file_processing_command == - right._service_perfdata_file_processing_command && - _service_perfdata_file_processing_interval == - right._service_perfdata_file_processing_interval && - _service_perfdata_file_template == - right._service_perfdata_file_template && _sleep_time == right._sleep_time && _soft_state_dependencies == right._soft_state_dependencies && _state_retention_file == right._state_retention_file && @@ -2227,115 +2151,6 @@ void state::host_inter_check_delay_method(inter_check_delay value) { _host_inter_check_delay_method = value; } -/** - * Get host_perfdata_command value. - * - * @return The host_perfdata_command value. - */ -const std::string& state::host_perfdata_command() const noexcept { - return _host_perfdata_command; -} - -/** - * Set host_perfdata_command value. - * - * @param[in] value The new host_perfdata_command value. - */ -void state::host_perfdata_command(const std::string& value) { - _host_perfdata_command = value; -} - -/** - * Get host_perfdata_file value. - * - * @return The host_perfdata_file value. - */ -const std::string& state::host_perfdata_file() const noexcept { - return _host_perfdata_file; -} - -/** - * Set host_perfdata_file value. - * - * @param[in] value The new host_perfdata_file value. - */ -void state::host_perfdata_file(const std::string& value) { - _host_perfdata_file = value; -} - -/** - * Get host_perfdata_file_mode value. - * - * @return The host_perfdata_file_mode value. - */ -state::perfdata_file_mode state::host_perfdata_file_mode() const noexcept { - return _host_perfdata_file_mode; -} - -/** - * Set host_perfdata_file_mode value. - * - * @param[in] value The new host_perfdata_file_mode value. - */ -void state::host_perfdata_file_mode(perfdata_file_mode value) { - _host_perfdata_file_mode = value; -} - -/** - * Get host_perfdata_file_processing_command value. - * - * @return The host_perfdata_file_processing_command value. - */ -const std::string& state::host_perfdata_file_processing_command() - const noexcept { - return _host_perfdata_file_processing_command; -} - -/** - * Set host_perfdata_file_processing_command value. - * - * @param[in] value The new host_perfdata_file_processing_command value. - */ -void state::host_perfdata_file_processing_command(const std::string& value) { - _host_perfdata_file_processing_command = value; -} - -/** - * Get host_perfdata_file_processing_interval value. - * - * @return The host_perfdata_file_processing_interval value. - */ -unsigned int state::host_perfdata_file_processing_interval() const noexcept { - return _host_perfdata_file_processing_interval; -} - -/** - * Set host_perfdata_file_processing_interval value. - * - * @param[in] value The new host_perfdata_file_processing_interval value. - */ -void state::host_perfdata_file_processing_interval(unsigned int value) { - _host_perfdata_file_processing_interval = value; -} - -/** - * Get host_perfdata_file_template value. - * - * @return The host_perfdata_file_template value. - */ -const std::string& state::host_perfdata_file_template() const noexcept { - return _host_perfdata_file_template; -} - -/** - * Set host_perfdata_file_template value. - * - * @param[in] value The new host_perfdata_file_template value. - */ -void state::host_perfdata_file_template(const std::string& value) { - _host_perfdata_file_template = value; -} - /** * Get illegal_object_chars value. * @@ -3395,115 +3210,6 @@ void state::service_interleave_factor_method(interleave_factor value) { _service_interleave_factor_method = value; } -/** - * Get service_perfdata_command value. - * - * @return The service_perfdata_command value. - */ -const std::string& state::service_perfdata_command() const noexcept { - return _service_perfdata_command; -} - -/** - * Set service_perfdata_command value. - * - * @param[in] value The new service_perfdata_command value. - */ -void state::service_perfdata_command(const std::string& value) { - _service_perfdata_command = value; -} - -/** - * Get service_perfdata_file value. - * - * @return The service_perfdata_file value. - */ -const std::string& state::service_perfdata_file() const noexcept { - return _service_perfdata_file; -} - -/** - * Set service_perfdata_file value. - * - * @param[in] value The new service_perfdata_file value. - */ -void state::service_perfdata_file(const std::string& value) { - _service_perfdata_file = value; -} - -/** - * Get service_perfdata_file_mode value. - * - * @return The service_perfdata_file_mode value. - */ -state::perfdata_file_mode state::service_perfdata_file_mode() const noexcept { - return _service_perfdata_file_mode; -} - -/** - * Set service_perfdata_file_mode value. - * - * @param[in] value The new service_perfdata_file_mode value. - */ -void state::service_perfdata_file_mode(perfdata_file_mode value) { - _service_perfdata_file_mode = value; -} - -/** - * Get service_perfdata_file_processing_command value. - * - * @return The service_perfdata_file_processing_command value. - */ -const std::string& state::service_perfdata_file_processing_command() - const noexcept { - return _service_perfdata_file_processing_command; -} - -/** - * Set service_perfdata_file_processing_command value. - * - * @param[in] value The new service_perfdata_file_processing_command value. - */ -void state::service_perfdata_file_processing_command(const std::string& value) { - _service_perfdata_file_processing_command = value; -} - -/** - * Get service_perfdata_file_processing_interval value. - * - * @return The service_perfdata_file_processing_interval value. - */ -unsigned int state::service_perfdata_file_processing_interval() const noexcept { - return _service_perfdata_file_processing_interval; -} - -/** - * Set service_perfdata_file_processing_interval value. - * - * @param[in] value The new service_perfdata_file_processing_interval value. - */ -void state::service_perfdata_file_processing_interval(unsigned int value) { - _service_perfdata_file_processing_interval = value; -} - -/** - * Get service_perfdata_file_template value. - * - * @return The service_perfdata_file_template value. - */ -const std::string& state::service_perfdata_file_template() const noexcept { - return _service_perfdata_file_template; -} - -/** - * Set service_perfdata_file_template value. - * - * @param[in] value The new service_perfdata_file_template value. - */ -void state::service_perfdata_file_template(const std::string& value) { - _service_perfdata_file_template = value; -} - /** * Get sleep_time value. * @@ -4371,20 +4077,6 @@ void state::_set_host_inter_check_delay_method(const std::string& value) { } } -/** - * Set host_perfdata_file_mode. - * - * @param[in] value The new host_inter_check_delay_method value. - */ -void state::_set_host_perfdata_file_mode(const std::string& value) { - if (value == "p") - _host_perfdata_file_mode = mode_pipe; - else if (value == "w") - _host_perfdata_file_mode = mode_file; - else - _host_perfdata_file_mode = mode_file_append; -} - /** * Set resource_file. * @@ -4440,20 +4132,6 @@ void state::_set_service_interleave_factor_method(const std::string& value) { } } -/** - * Set service_perfdata_file_mode. - * - * @param[in] value The new service_inter_check_delay_method value. - */ -void state::_set_service_perfdata_file_mode(const std::string& value) { - if (value == "p") - _service_perfdata_file_mode = mode_pipe; - else if (value == "w") - _service_perfdata_file_mode = mode_file; - else - _service_perfdata_file_mode = mode_file_append; -} - void state::macros_filter(const std::string& value) { size_t previous(0), first, last; size_t current(value.find(',')); diff --git a/common/engine_legacy_conf/state.hh b/common/engine_legacy_conf/state.hh index 6d5bf435706..13865cf28b3 100644 --- a/common/engine_legacy_conf/state.hh +++ b/common/engine_legacy_conf/state.hh @@ -113,12 +113,6 @@ class state { ilf_smart // smart interleave }; - /** - * @enum state::perdata_file_mode - * - */ - enum perfdata_file_mode { mode_pipe = 0, mode_file, mode_file_append }; - state(); state(state const& right); ~state() noexcept = default; @@ -256,18 +250,6 @@ class state { void host_freshness_check_interval(unsigned int value); inter_check_delay host_inter_check_delay_method() const noexcept; void host_inter_check_delay_method(inter_check_delay value); - std::string const& host_perfdata_command() const noexcept; - void host_perfdata_command(std::string const& value); - std::string const& host_perfdata_file() const noexcept; - void host_perfdata_file(std::string const& value); - perfdata_file_mode host_perfdata_file_mode() const noexcept; - void host_perfdata_file_mode(perfdata_file_mode value); - std::string const& host_perfdata_file_processing_command() const noexcept; - void host_perfdata_file_processing_command(std::string const& value); - unsigned int host_perfdata_file_processing_interval() const noexcept; - void host_perfdata_file_processing_interval(unsigned int value); - std::string const& host_perfdata_file_template() const noexcept; - void host_perfdata_file_template(std::string const& value); std::string const& illegal_object_chars() const noexcept; void illegal_object_chars(std::string const& value); std::string const& illegal_output_chars() const noexcept; @@ -382,18 +364,6 @@ class state { void service_inter_check_delay_method(inter_check_delay value); interleave_factor service_interleave_factor_method() const noexcept; void service_interleave_factor_method(interleave_factor value); - std::string const& service_perfdata_command() const noexcept; - void service_perfdata_command(std::string const& value); - std::string const& service_perfdata_file() const noexcept; - void service_perfdata_file(std::string const& value); - perfdata_file_mode service_perfdata_file_mode() const noexcept; - void service_perfdata_file_mode(perfdata_file_mode value); - std::string const& service_perfdata_file_processing_command() const noexcept; - void service_perfdata_file_processing_command(std::string const& value); - unsigned int service_perfdata_file_processing_interval() const noexcept; - void service_perfdata_file_processing_interval(unsigned int value); - std::string const& service_perfdata_file_template() const noexcept; - void service_perfdata_file_template(std::string const& value); float sleep_time() const noexcept; void sleep_time(float value); bool soft_state_dependencies() const noexcept; @@ -491,12 +461,10 @@ class state { void _set_date_format(std::string const& value); void _set_event_broker_options(std::string const& value); void _set_host_inter_check_delay_method(std::string const& value); - void _set_host_perfdata_file_mode(std::string const& value); void _set_object_cache_file(std::string const& value); void _set_resource_file(std::string const& value); void _set_service_inter_check_delay_method(std::string const& value); void _set_service_interleave_factor_method(std::string const& value); - void _set_service_perfdata_file_mode(std::string const& value); bool _accept_passive_host_checks; bool _accept_passive_service_checks; @@ -556,12 +524,6 @@ class state { unsigned int _host_check_timeout; unsigned int _host_freshness_check_interval; inter_check_delay _host_inter_check_delay_method; - std::string _host_perfdata_command; - std::string _host_perfdata_file; - perfdata_file_mode _host_perfdata_file_mode; - std::string _host_perfdata_file_processing_command; - unsigned int _host_perfdata_file_processing_interval; - std::string _host_perfdata_file_template; std::string _illegal_object_chars; std::string _illegal_output_chars; unsigned int _interval_length; @@ -613,12 +575,6 @@ class state { unsigned int _service_freshness_check_interval; inter_check_delay _service_inter_check_delay_method; interleave_factor _service_interleave_factor_method; - std::string _service_perfdata_command; - std::string _service_perfdata_file; - perfdata_file_mode _service_perfdata_file_mode; - std::string _service_perfdata_file_processing_command; - unsigned int _service_perfdata_file_processing_interval; - std::string _service_perfdata_file_template; static setter_map _setters; float _sleep_time; bool _soft_state_dependencies; diff --git a/engine/CMakeLists.txt b/engine/CMakeLists.txt index e1855ab5156..2f51ffb32d9 100644 --- a/engine/CMakeLists.txt +++ b/engine/CMakeLists.txt @@ -407,7 +407,6 @@ set(FILES "${SRC_DIR}/timezone_locker.cc" "${SRC_DIR}/timezone_manager.cc" "${SRC_DIR}/utils.cc" - "${SRC_DIR}/xpddefault.cc" "${SRC_DIR}/xsddefault.cc" # Headers. "${INC_DIR}/com/centreon/engine/anomalydetection.hh" @@ -460,7 +459,6 @@ set(FILES "${INC_DIR}/com/centreon/engine/timezone_manager.hh" "${INC_DIR}/com/centreon/engine/utils.hh" "${INC_DIR}/com/centreon/engine/version.hh" - "${INC_DIR}/com/centreon/engine/xpddefault.hh" "${INC_DIR}/com/centreon/engine/xsddefault.hh") # Subdirectories with core features. diff --git a/engine/inc/com/centreon/engine/configuration/applier/scheduler.hh b/engine/inc/com/centreon/engine/configuration/applier/scheduler.hh index 78d19824499..87f4ad37c19 100644 --- a/engine/inc/com/centreon/engine/configuration/applier/scheduler.hh +++ b/engine/inc/com/centreon/engine/configuration/applier/scheduler.hh @@ -88,12 +88,10 @@ class scheduler { timed_event* _evt_check_reaper; timed_event* _evt_command_check; timed_event* _evt_hfreshness_check; - timed_event* _evt_host_perfdata; timed_event* _evt_orphan_check; timed_event* _evt_reschedule_checks; timed_event* _evt_retention_save; timed_event* _evt_sfreshness_check; - timed_event* _evt_service_perfdata; timed_event* _evt_status_save; unsigned int _old_auto_rescheduling_interval; unsigned int _old_check_reaper_interval; diff --git a/engine/inc/com/centreon/engine/xpddefault.hh b/engine/inc/com/centreon/engine/xpddefault.hh deleted file mode 100644 index 6fce4315790..00000000000 --- a/engine/inc/com/centreon/engine/xpddefault.hh +++ /dev/null @@ -1,65 +0,0 @@ -/* -** Copyright 2001-2006 Ethan Galstad -** Copyright 2011-2013 Merethis -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - -#ifndef CCE_XPDDEFAULT_HH -#define CCE_XPDDEFAULT_HH - -#include "com/centreon/engine/macros/defines.hh" - -#ifdef __cplusplus -extern "C" { -#endif // C++ - -int xpddefault_initialize_performance_data(); -int xpddefault_cleanup_performance_data(); - -int xpddefault_update_service_performance_data( - com::centreon::engine::service* svc); -int xpddefault_update_host_performance_data(com::centreon::engine::host* hst); - -int xpddefault_run_service_performance_data_command( - nagios_macros* mac, - com::centreon::engine::service* svc); -int xpddefault_run_host_performance_data_command( - nagios_macros* mac, - com::centreon::engine::host* hst); - -int xpddefault_update_service_performance_data_file( - nagios_macros* mac, - com::centreon::engine::service* svc); -int xpddefault_update_host_performance_data_file( - nagios_macros* mac, - com::centreon::engine::host* hst); - -void xpddefault_preprocess_file_templates(char* tmpl); - -int xpddefault_open_host_perfdata_file(); -int xpddefault_open_service_perfdata_file(); -int xpddefault_close_host_perfdata_file(); -int xpddefault_close_service_perfdata_file(); - -int xpddefault_process_host_perfdata_file(); -int xpddefault_process_service_perfdata_file(); - -#ifdef __cplusplus -} -#endif // C++ - -#endif // !CCE_XPDDEFAULT_HH diff --git a/engine/inc/compatibility/xpddefault.h b/engine/inc/compatibility/xpddefault.h deleted file mode 100644 index 7e4cc4cde3e..00000000000 --- a/engine/inc/compatibility/xpddefault.h +++ /dev/null @@ -1,26 +0,0 @@ -/* -** Copyright 2011-2013 Merethis -** -** This file is part of Centreon Engine. -** -** Centreon Engine is free software: you can redistribute it and/or -** modify it under the terms of the GNU General Public License version 2 -** as published by the Free Software Foundation. -** -** Centreon Engine is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with Centreon Engine. If not, see -** . -*/ - -#ifndef CCE_COMPATIBILITY_XPDDEFAULT_H -#define CCE_COMPATIBILITY_XPDDEFAULT_H - -#include "com/centreon/engine/xpddefault.hh" -#include "objects.h" - -#endif // !CCE_COMPATIBILITY_XPDDEFAULT_H diff --git a/engine/src/compatibility/CMakeLists.txt b/engine/src/compatibility/CMakeLists.txt index 4c2db02f906..a87aff549b1 100644 --- a/engine/src/compatibility/CMakeLists.txt +++ b/engine/src/compatibility/CMakeLists.txt @@ -65,7 +65,6 @@ set( "${INC_DIR}/statusdata.h" "${INC_DIR}/xcddefault.h" "${INC_DIR}/xodtemplate.h" - "${INC_DIR}/xpddefault.h" "${INC_DIR}/xrddefault.h" "${INC_DIR}/xsddefault.h" diff --git a/engine/src/configuration/applier/macros.cc b/engine/src/configuration/applier/macros.cc index 18275987d59..57f2358f801 100644 --- a/engine/src/configuration/applier/macros.cc +++ b/engine/src/configuration/applier/macros.cc @@ -65,8 +65,6 @@ void applier::macros::apply(configuration::state& config) { _set_macro(MACRO_RESOURCEFILE, config.resource_file().front()); _set_macro(MACRO_STATUSDATAFILE, config.status_file()); _set_macro(MACRO_RETENTIONDATAFILE, config.state_retention_file()); - _set_macro(MACRO_HOSTPERFDATAFILE, config.host_perfdata_file()); - _set_macro(MACRO_SERVICEPERFDATAFILE, config.service_perfdata_file()); _set_macro(MACRO_POLLERNAME, config.poller_name()); _set_macro(MACRO_POLLERID, std::to_string(config.poller_id())); diff --git a/engine/src/configuration/applier/scheduler.cc b/engine/src/configuration/applier/scheduler.cc index 2b05898ba13..aea739f7aef 100644 --- a/engine/src/configuration/applier/scheduler.cc +++ b/engine/src/configuration/applier/scheduler.cc @@ -26,7 +26,6 @@ #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/statusdata.hh" #include "com/centreon/engine/timezone_locker.hh" -#include "com/centreon/engine/xpddefault.hh" #include "com/centreon/logging/logger.hh" using namespace com::centreon::engine; @@ -216,12 +215,10 @@ void applier::scheduler::clear() { _evt_check_reaper = nullptr; _evt_command_check = nullptr; _evt_hfreshness_check = nullptr; - _evt_host_perfdata = nullptr; _evt_orphan_check = nullptr; _evt_reschedule_checks = nullptr; _evt_retention_save = nullptr; _evt_sfreshness_check = nullptr; - _evt_service_perfdata = nullptr; _evt_status_save = nullptr; _old_auto_rescheduling_interval = 0; _old_check_reaper_interval = 0; @@ -276,12 +273,10 @@ applier::scheduler::scheduler() _evt_check_reaper(nullptr), _evt_command_check(nullptr), _evt_hfreshness_check(nullptr), - _evt_host_perfdata(nullptr), _evt_orphan_check(nullptr), _evt_reschedule_checks(nullptr), _evt_retention_save(nullptr), _evt_sfreshness_check(nullptr), - _evt_service_perfdata(nullptr), _evt_status_save(nullptr), _old_auto_rescheduling_interval(0), _old_check_reaper_interval(0), @@ -410,53 +405,6 @@ void applier::scheduler::_apply_misc_event() { _config->status_update_interval()); _old_status_update_interval = _config->status_update_interval(); } - - union { - int (*func)(); - void* data; - } type; - - // Remove and add process host perfdata file. - if (!_evt_host_perfdata || - (_old_host_perfdata_file_processing_interval != - _config->host_perfdata_file_processing_interval()) || - (_old_host_perfdata_file_processing_command != - _config->host_perfdata_file_processing_command())) { - _remove_misc_event(_evt_host_perfdata); - if (_config->host_perfdata_file_processing_interval() > 0 && - !_config->host_perfdata_file_processing_command().empty()) { - type.func = &xpddefault_process_host_perfdata_file; - _evt_host_perfdata = _create_misc_event( - timed_event::EVENT_USER_FUNCTION, - now + _config->host_perfdata_file_processing_interval(), - _config->host_perfdata_file_processing_interval(), type.data); - } - _old_host_perfdata_file_processing_interval = - _config->host_perfdata_file_processing_interval(); - _old_host_perfdata_file_processing_command = - _config->host_perfdata_file_processing_command(); - } - - // Remove and add process service perfdata file. - if (!_evt_service_perfdata || - (_old_service_perfdata_file_processing_interval != - _config->service_perfdata_file_processing_interval()) || - (_old_service_perfdata_file_processing_command != - _config->service_perfdata_file_processing_command())) { - _remove_misc_event(_evt_service_perfdata); - if (_config->service_perfdata_file_processing_interval() > 0 && - !_config->service_perfdata_file_processing_command().empty()) { - type.func = &xpddefault_process_service_perfdata_file; - _evt_service_perfdata = _create_misc_event( - timed_event::EVENT_USER_FUNCTION, - now + _config->service_perfdata_file_processing_interval(), - _config->service_perfdata_file_processing_interval(), type.data); - } - _old_service_perfdata_file_processing_interval = - _config->service_perfdata_file_processing_interval(); - _old_service_perfdata_file_processing_command = - _config->service_perfdata_file_processing_command(); - } } /** diff --git a/engine/src/configuration/applier/state.cc b/engine/src/configuration/applier/state.cc index 44bd189d5ad..0111a51dcb4 100644 --- a/engine/src/configuration/applier/state.cc +++ b/engine/src/configuration/applier/state.cc @@ -49,7 +49,6 @@ #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/retention/applier/state.hh" #include "com/centreon/engine/version.hh" -#include "com/centreon/engine/xpddefault.hh" #include "com/centreon/engine/xsddefault.hh" #include "common/engine_legacy_conf/command.hh" #include "common/log_v2/log_v2.hh" @@ -128,8 +127,6 @@ void applier::state::clear() { engine::comment::comments.clear(); engine::comment::set_next_comment_id(1llu); - xpddefault_cleanup_performance_data(); - applier::scheduler::instance().clear(); applier::macros::instance().clear(); applier::globals::instance().clear(); @@ -166,8 +163,6 @@ applier::state::~state() noexcept { engine::timeperiod::timeperiods.clear(); engine::comment::comments.clear(); engine::comment::set_next_comment_id(1llu); - - xpddefault_cleanup_performance_data(); } /** @@ -252,31 +247,6 @@ void applier::state::_apply(configuration::state const& new_cfg, } } - // Initialize perfdata if necessary. - bool modify_perfdata(false); - if (!has_already_been_loaded || - config->host_perfdata_command() != new_cfg.host_perfdata_command() || - config->host_perfdata_file() != new_cfg.host_perfdata_file() || - config->host_perfdata_file_mode() != new_cfg.host_perfdata_file_mode() || - config->host_perfdata_file_processing_command() != - new_cfg.host_perfdata_file_processing_command() || - config->host_perfdata_file_processing_interval() != - new_cfg.host_perfdata_file_processing_interval() || - config->host_perfdata_file_template() != - new_cfg.host_perfdata_file_template() || - config->service_perfdata_command() != - new_cfg.service_perfdata_command() || - config->service_perfdata_file() != new_cfg.service_perfdata_file() || - config->service_perfdata_file_mode() != - new_cfg.service_perfdata_file_mode() || - config->service_perfdata_file_processing_command() != - new_cfg.service_perfdata_file_processing_command() || - config->service_perfdata_file_processing_interval() != - new_cfg.service_perfdata_file_processing_interval() || - config->service_perfdata_file_template() != - new_cfg.service_perfdata_file_template()) - modify_perfdata = true; - // Initialize status file. bool modify_status(false); if (!has_already_been_loaded || @@ -284,8 +254,6 @@ void applier::state::_apply(configuration::state const& new_cfg, modify_status = true; // Cleanup. - if (modify_perfdata) - xpddefault_cleanup_performance_data(); if (modify_status) xsddefault_cleanup_status_data(true); @@ -337,14 +305,6 @@ void applier::state::_apply(configuration::state const& new_cfg, new_cfg.host_freshness_check_interval()); config->host_inter_check_delay_method( new_cfg.host_inter_check_delay_method()); - config->host_perfdata_command(new_cfg.host_perfdata_command()); - config->host_perfdata_file(new_cfg.host_perfdata_file()); - config->host_perfdata_file_mode(new_cfg.host_perfdata_file_mode()); - config->host_perfdata_file_processing_command( - new_cfg.host_perfdata_file_processing_command()); - config->host_perfdata_file_processing_interval( - new_cfg.host_perfdata_file_processing_interval()); - config->host_perfdata_file_template(new_cfg.host_perfdata_file_template()); config->illegal_object_chars(new_cfg.illegal_object_chars()); config->illegal_output_chars(new_cfg.illegal_output_chars()); config->interval_length(new_cfg.interval_length()); @@ -389,15 +349,6 @@ void applier::state::_apply(configuration::state const& new_cfg, new_cfg.service_inter_check_delay_method()); config->service_interleave_factor_method( new_cfg.service_interleave_factor_method()); - config->service_perfdata_command(new_cfg.service_perfdata_command()); - config->service_perfdata_file(new_cfg.service_perfdata_file()); - config->service_perfdata_file_mode(new_cfg.service_perfdata_file_mode()); - config->service_perfdata_file_processing_command( - new_cfg.service_perfdata_file_processing_command()); - config->service_perfdata_file_processing_interval( - new_cfg.service_perfdata_file_processing_interval()); - config->service_perfdata_file_template( - new_cfg.service_perfdata_file_template()); config->sleep_time(new_cfg.sleep_time()); config->soft_state_dependencies(new_cfg.soft_state_dependencies()); config->state_retention_file(new_cfg.state_retention_file()); @@ -446,8 +397,6 @@ void applier::state::_apply(configuration::state const& new_cfg, // Initialize. if (modify_status) xsddefault_initialize_status_data(); - if (modify_perfdata) - xpddefault_initialize_performance_data(); // Check global event handler commands... if (verify_config) { diff --git a/engine/src/host.cc b/engine/src/host.cc index 023fe969f6f..2abfd5b67bc 100644 --- a/engine/src/host.cc +++ b/engine/src/host.cc @@ -43,7 +43,6 @@ #include "com/centreon/engine/statusdata.hh" #include "com/centreon/engine/string.hh" #include "com/centreon/engine/timezone_locker.hh" -#include "com/centreon/engine/xpddefault.hh" #include "com/centreon/exceptions/interruption.hh" using namespace com::centreon; @@ -2465,9 +2464,6 @@ void host::update_performance_data() { /* should we process performance data for this host? */ if (!get_process_performance_data()) return; - - /* process the performance data! */ - xpddefault_update_host_performance_data(this); } /** diff --git a/engine/src/service.cc b/engine/src/service.cc index 3ca52aa723d..abe5f65711a 100644 --- a/engine/src/service.cc +++ b/engine/src/service.cc @@ -43,7 +43,6 @@ #include "com/centreon/engine/string.hh" #include "com/centreon/engine/timezone_locker.hh" #include "com/centreon/exceptions/interruption.hh" -#include "compatibility/xpddefault.h" using namespace com::centreon; using namespace com::centreon::engine; @@ -2422,8 +2421,6 @@ int service::update_service_performance_data() { if (!this->get_process_performance_data()) return OK; - /* process the performance data! */ - xpddefault_update_service_performance_data(this); return OK; } diff --git a/engine/src/xpddefault.cc b/engine/src/xpddefault.cc deleted file mode 100644 index b21b5b3391a..00000000000 --- a/engine/src/xpddefault.cc +++ /dev/null @@ -1,836 +0,0 @@ -/** - * Copyright 2000-2008 Ethan Galstad - * Copyright 2011-2013 Merethis - * - * This file is part of Centreon Engine. - * - * Centreon Engine is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License version 2 - * as published by the Free Software Foundation. - * - * Centreon Engine is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Centreon Engine. If not, see - * . - */ - -#include "com/centreon/engine/xpddefault.hh" -#include -#include -#include -#include "com/centreon/engine/commands/command.hh" -#include "com/centreon/engine/common.hh" -#include "com/centreon/engine/configuration/applier/state.hh" -#include "com/centreon/engine/globals.hh" -#include "com/centreon/engine/host.hh" -#include "com/centreon/engine/logging/logger.hh" -#include "com/centreon/engine/macros.hh" -#include "com/centreon/engine/service.hh" -#include "com/centreon/engine/string.hh" - -using namespace com::centreon::engine; -using namespace com::centreon::engine::configuration::applier; -using namespace com::centreon::engine::logging; - -static commands::command* xpddefault_host_perfdata_command_ptr(nullptr); -static commands::command* xpddefault_service_perfdata_command_ptr(nullptr); - -static char* xpddefault_host_perfdata_file_template(nullptr); -static char* xpddefault_service_perfdata_file_template(nullptr); - -static commands::command* xpddefault_host_perfdata_file_processing_command_ptr( - nullptr); -static commands::command* - xpddefault_service_perfdata_file_processing_command_ptr(nullptr); - -static FILE* xpddefault_host_perfdata_fp(nullptr); -static FILE* xpddefault_service_perfdata_fp(nullptr); -static int xpddefault_host_perfdata_fd(-1); -static int xpddefault_service_perfdata_fd(-1); - -static pthread_mutex_t xpddefault_host_perfdata_fp_lock; -static pthread_mutex_t xpddefault_service_perfdata_fp_lock; - -/******************************************************************/ -/************** INITIALIZATION & CLEANUP FUNCTIONS ****************/ -/******************************************************************/ - -// initializes performance data. -int xpddefault_initialize_performance_data() { - char* temp_command_name(nullptr); - - // reset vars. - xpddefault_host_perfdata_command_ptr = nullptr; - xpddefault_service_perfdata_command_ptr = nullptr; - xpddefault_host_perfdata_file_processing_command_ptr = nullptr; - xpddefault_service_perfdata_file_processing_command_ptr = nullptr; - - // grab config info from main config file. - xpddefault_host_perfdata_file_template = - string::dup(config->host_perfdata_file_template()); - xpddefault_service_perfdata_file_template = - string::dup(config->service_perfdata_file_template()); - - // process special chars in templates. - xpddefault_preprocess_file_templates(xpddefault_host_perfdata_file_template); - xpddefault_preprocess_file_templates( - xpddefault_service_perfdata_file_template); - - // open the performance data files. - xpddefault_open_host_perfdata_file(); - xpddefault_open_service_perfdata_file(); - - // verify that performance data commands are valid. - if (!config->host_perfdata_command().empty()) { - char* temp_buffer(string::dup(config->host_perfdata_command())); - - // get the command name, leave any arguments behind. - temp_command_name = my_strtok(temp_buffer, "!"); - - command_map::iterator cmd_found = - commands::command::commands.find(temp_command_name); - - if (cmd_found == commands::command::commands.end() || !cmd_found->second) { - engine_logger(log_runtime_warning, basic) - << "Warning: Host performance command '" << temp_command_name - << "' was not found - host performance data will not " - "be processed!"; - runtime_logger->warn( - "Warning: Host performance command '{}' was not found - host " - "performance data will not " - "be processed!", - temp_command_name); - } else - xpddefault_host_perfdata_command_ptr = - cmd_found->second.get(); // save the command pointer for later. - - delete[] temp_buffer; - } - - if (!config->service_perfdata_command().empty()) { - char* temp_buffer(string::dup(config->service_perfdata_command())); - - // get the command name, leave any arguments behind. - temp_command_name = my_strtok(temp_buffer, "!"); - - command_map::iterator cmd_found = - commands::command::commands.find(temp_command_name); - - if (cmd_found == commands::command::commands.end() || !cmd_found->second) { - engine_logger(log_runtime_warning, basic) - << "Warning: Service performance command '" << temp_command_name - << "' was not found - service performance data will not " - "be processed!"; - runtime_logger->warn( - "Warning: Service performance command '{}' was not found - service " - "performance data will not " - "be processed!", - temp_command_name); - } else - xpddefault_service_perfdata_command_ptr = cmd_found->second.get(); - - // free memory. - delete[] temp_buffer; - } - - if (!config->host_perfdata_file_processing_command().empty()) { - char* temp_buffer = - string::dup(config->host_perfdata_file_processing_command()); - - // get the command name, leave any arguments behind. - temp_command_name = my_strtok(temp_buffer, "!"); - command_map::iterator cmd_found = - commands::command::commands.find(temp_command_name); - - if (cmd_found == commands::command::commands.end() || !cmd_found->second) { - engine_logger(log_runtime_warning, basic) - << "Warning: Host performance file processing command '" - << temp_command_name - << "' was not found - host performance " - "data file will not be processed!"; - runtime_logger->warn( - "Warning: Host performance file processing command '{}' was not " - "found - host performance " - "data file will not be processed!", - temp_command_name); - } else - xpddefault_host_perfdata_file_processing_command_ptr = - cmd_found->second.get(); - - // free memory. - delete[] temp_buffer; - } - - if (!config->service_perfdata_file_processing_command().empty()) { - char* temp_buffer = - string::dup(config->service_perfdata_file_processing_command()); - - // get the command name, leave any arguments behind. - temp_command_name = my_strtok(temp_buffer, "!"); - auto cmd_found = commands::command::commands.find(temp_command_name); - - if (cmd_found == commands::command::commands.end() || !cmd_found->second) { - engine_logger(log_runtime_warning, basic) - << "Warning: Service performance file processing command '" - << temp_command_name - << "' was not found - service performance " - "data file will not be processed!"; - runtime_logger->warn( - "Warning: Service performance file processing command '{}' was not " - "found - service performance " - "data file will not be processed!", - temp_command_name); - } else - xpddefault_service_perfdata_file_processing_command_ptr = - cmd_found->second.get(); - // free memory. - delete[] temp_buffer; - } - - return OK; -} - -// cleans up performance data. -int xpddefault_cleanup_performance_data() { - // free memory. - delete[] xpddefault_host_perfdata_file_template; - delete[] xpddefault_service_perfdata_file_template; - - xpddefault_host_perfdata_file_template = nullptr; - xpddefault_service_perfdata_file_template = nullptr; - - // close the files. - xpddefault_close_host_perfdata_file(); - xpddefault_close_service_perfdata_file(); - - return OK; -} - -/******************************************************************/ -/****************** PERFORMANCE DATA FUNCTIONS ********************/ -/******************************************************************/ - -// updates service performance data. -int xpddefault_update_service_performance_data( - com::centreon::engine::service* svc) { - nagios_macros* mac(get_global_macros()); - - /* - * bail early if we've got nothing to do so we don't spend a lot - * of time calculating macros that never get used - */ - if (!svc || svc->get_perf_data().empty()) - return OK; - if ((!xpddefault_service_perfdata_fp || - !xpddefault_service_perfdata_file_template) && - config->service_perfdata_command().empty()) - return OK; - - grab_host_macros_r(mac, svc->get_host_ptr()); - grab_service_macros_r(mac, svc); - - // run the performance data command. - xpddefault_run_service_performance_data_command(mac, svc); - - // get rid of used memory we won't need anymore. - clear_argv_macros_r(mac); - - // update the performance data file. - xpddefault_update_service_performance_data_file(mac, svc); - - // now free() it all. - clear_volatile_macros_r(mac); - - return OK; -} - -// updates host performance data. -int xpddefault_update_host_performance_data(host* hst) { - nagios_macros* mac(get_global_macros()); - - /* - * bail early if we've got nothing to do so we don't spend a lot - * of time calculating macros that never get used - */ - if (!hst || !hst->get_perf_data().empty()) - return OK; - if ((!xpddefault_host_perfdata_fp || - !xpddefault_host_perfdata_file_template) && - config->host_perfdata_command().empty()) - return OK; - - // set up macros and get to work. - grab_host_macros_r(mac, hst); - - // run the performance data command. - xpddefault_run_host_performance_data_command(mac, hst); - - // no more commands to run, so we won't need this any more. - clear_argv_macros_r(mac); - - // update the performance data file. - xpddefault_update_host_performance_data_file(mac, hst); - - // free() all. - clear_volatile_macros_r(mac); - - return OK; -} - -/******************************************************************/ -/************** PERFORMANCE DATA COMMAND FUNCTIONS ****************/ -/******************************************************************/ - -// runs the service performance data command. -int xpddefault_run_service_performance_data_command( - nagios_macros* mac, - com::centreon::engine::service* svc) { - std::string raw_command_line; - std::string processed_command_line; - bool early_timeout = false; - double exectime; - int result(OK); - int macro_options(STRIP_ILLEGAL_MACRO_CHARS | ESCAPE_MACRO_CHARS); - - engine_logger(dbg_functions, basic) - << "run_service_performance_data_command()"; - functions_logger->trace("run_service_performance_data_command()"); - - if (svc == nullptr) - return ERROR; - - // we don't have a command. - if (config->service_perfdata_command().empty()) - return OK; - - // get the raw command line. - get_raw_command_line_r(mac, xpddefault_service_perfdata_command_ptr, - config->service_perfdata_command().c_str(), - raw_command_line, macro_options); - if (raw_command_line.c_str()) - return ERROR; - - engine_logger(dbg_perfdata, most) - << "Raw service performance data command line: " << raw_command_line; - commands_logger->debug("Raw service performance data command line: {}", - raw_command_line); - - // process any macros in the raw command line. - process_macros_r(mac, raw_command_line, processed_command_line, - macro_options); - if (processed_command_line.empty()) - return ERROR; - - engine_logger(dbg_perfdata, most) << "Processed service performance data " - "command line: " - << processed_command_line; - commands_logger->debug("Processed service performance data command line: {}", - processed_command_line); - - // run the command. - try { - std::string tmp; - my_system_r(mac, processed_command_line, config->perfdata_timeout(), - &early_timeout, &exectime, tmp, 0); - } catch (std::exception const& e) { - engine_logger(log_runtime_error, basic) - << "Error: can't execute service performance data command line '" - << processed_command_line << "' : " << e.what(); - runtime_logger->error( - "Error: can't execute service performance data command line '{}' : {}", - processed_command_line, e.what()); - } - - // check to see if the command timed out. - if (early_timeout) - engine_logger(log_runtime_warning, basic) - << "Warning: Service performance data command '" - << processed_command_line << "' for service '" << svc->description() - << "' on host '" << svc->get_hostname() << "' timed out after " - << config->perfdata_timeout() << " seconds"; - runtime_logger->warn( - "Warning: Service performance data command '{}' for service '{}' on host " - "'{}' timed out after {} seconds", - processed_command_line, svc->description(), svc->get_hostname(), - config->perfdata_timeout()); - - return result; -} - -// runs the host performance data command. -int xpddefault_run_host_performance_data_command(nagios_macros* mac, - host* hst) { - std::string raw_command_line; - std::string processed_command_line; - bool early_timeout = false; - double exectime; - int result(OK); - int macro_options(STRIP_ILLEGAL_MACRO_CHARS | ESCAPE_MACRO_CHARS); - - engine_logger(dbg_functions, basic) << "run_host_performance_data_command()"; - functions_logger->trace("run_host_performance_data_command()"); - - if (hst == nullptr) - return ERROR; - - // we don't have a command. - if (config->host_perfdata_command().empty()) - return OK; - - // get the raw command line. - get_raw_command_line_r(mac, xpddefault_host_perfdata_command_ptr, - config->host_perfdata_command().c_str(), - raw_command_line, macro_options); - if (raw_command_line.empty()) - return ERROR; - - engine_logger(dbg_perfdata, most) - << "Raw host performance data command line: " << raw_command_line; - commands_logger->info("Raw host performance data command line: {}", - raw_command_line); - - // process any macros in the raw command line. - process_macros_r(mac, raw_command_line, processed_command_line, - macro_options); - - engine_logger(dbg_perfdata, most) - << "Processed host performance data command line: " - << processed_command_line; - commands_logger->info("Processed host performance data command line: {}", - processed_command_line); - - // run the command. - try { - std::string tmp; - my_system_r(mac, processed_command_line, config->perfdata_timeout(), - &early_timeout, &exectime, tmp, 0); - } catch (std::exception const& e) { - engine_logger(log_runtime_error, basic) - << "Error: can't execute host performance data command line '" - << processed_command_line << "' : " << e.what(); - runtime_logger->error( - "Error: can't execute host performance data command line '{}' : {}", - processed_command_line, e.what()); - } - - if (processed_command_line.empty()) - return ERROR; - - // check to see if the command timed out. - if (early_timeout) - engine_logger(log_runtime_warning, basic) - << "Warning: Host performance data command '" << processed_command_line - << "' for host '" << hst->name() << "' timed out after " - << config->perfdata_timeout() << " seconds"; - runtime_logger->warn( - "Warning: Host performance data command '{}' for host '{}' timed out " - "after {} seconds", - processed_command_line, hst->name(), config->perfdata_timeout()); - - return result; -} - -/******************************************************************/ -/**************** FILE PERFORMANCE DATA FUNCTIONS *****************/ -/******************************************************************/ - -// open the host performance data file for writing. -int xpddefault_open_host_perfdata_file() { - if (!config->host_perfdata_file().empty()) { - if (config->host_perfdata_file_mode() == configuration::state::mode_pipe) { - // must open read-write to avoid failure if the other end isn't ready yet. - xpddefault_host_perfdata_fd = - open(config->host_perfdata_file().c_str(), O_NONBLOCK | O_RDWR); - xpddefault_host_perfdata_fp = fdopen(xpddefault_host_perfdata_fd, "w"); - } else - xpddefault_host_perfdata_fp = fopen( - config->host_perfdata_file().c_str(), - (config->host_perfdata_file_mode() == configuration::state::mode_file) - ? "w" - : "a"); - - if (xpddefault_host_perfdata_fp == nullptr) { - engine_logger(log_runtime_warning, basic) - << "Warning: File '" << xpddefault_host_perfdata_fp - << "' could not be opened - host performance data will not " - "be written to file!"; - runtime_logger->warn( - "Warning: File '{}' could not be opened - host performance data will " - "not " - "be written to file!", - (void*)xpddefault_host_perfdata_fp); - - return ERROR; - } - } - - return OK; -} - -// open the service performance data file for writing. -int xpddefault_open_service_perfdata_file() { - if (!config->service_perfdata_file().empty()) { - if (config->service_perfdata_file_mode() == - configuration::state::mode_pipe) { - // must open read-write to avoid failure if the other end isn't ready yet. - xpddefault_service_perfdata_fd = - open(config->service_perfdata_file().c_str(), O_NONBLOCK | O_RDWR); - xpddefault_service_perfdata_fp = - fdopen(xpddefault_service_perfdata_fd, "w"); - } else - xpddefault_service_perfdata_fp = - fopen(config->service_perfdata_file().c_str(), - (config->service_perfdata_file_mode() == - configuration::state::mode_file) - ? "w" - : "a"); - - if (xpddefault_service_perfdata_fp == nullptr) { - engine_logger(log_runtime_warning, basic) - << "Warning: File '" << config->service_perfdata_file() - << "' could not be opened - service performance data will not " - "be written to file!"; - runtime_logger->warn( - "Warning: File '{}' could not be opened - service performance data " - "will not " - "be written to file!", - config->service_perfdata_file()); - - return ERROR; - } - } - - return OK; -} - -// close the host performance data file. -int xpddefault_close_host_perfdata_file() { - if (xpddefault_host_perfdata_fp != nullptr) - fclose(xpddefault_host_perfdata_fp); - if (xpddefault_host_perfdata_fd >= 0) { - close(xpddefault_host_perfdata_fd); - xpddefault_host_perfdata_fd = -1; - } - - return OK; -} - -// close the service performance data file. -int xpddefault_close_service_perfdata_file() { - if (xpddefault_service_perfdata_fp != nullptr) - fclose(xpddefault_service_perfdata_fp); - if (xpddefault_service_perfdata_fd >= 0) { - close(xpddefault_service_perfdata_fd); - xpddefault_service_perfdata_fd = -1; - } - - return OK; -} - -// processes delimiter characters in templates. -void xpddefault_preprocess_file_templates(char* tmpl) { - if (!tmpl) - return; - char *tmp1{tmpl}, *tmp2{tmpl}; - - for (; *tmp1 != 0; tmp1++, tmp2++) { - if (*tmp1 == '\\') { - switch (tmp1[1]) { - case 't': - *tmp2 = '\t'; - tmp1++; - break; - case 'r': - *tmp2 = '\r'; - tmp1++; - break; - case 'n': - *tmp2 = '\n'; - tmp1++; - break; - default: - *tmp2 = *tmp1; - break; - } - } else - *tmp2 = *tmp1; - } - *tmp2 = 0; -} - -// updates service performance data file. -int xpddefault_update_service_performance_data_file( - nagios_macros* mac, - com::centreon::engine::service* svc) { - std::string raw_output; - std::string processed_output; - int result(OK); - - engine_logger(dbg_functions, basic) - << "update_service_performance_data_file()"; - functions_logger->trace("update_service_performance_data_file()"); - - if (svc == nullptr) - return ERROR; - - // we don't have a file to write to. - if (xpddefault_service_perfdata_fp == nullptr || - xpddefault_service_perfdata_file_template == nullptr) - return OK; - - // get the raw line to write. - raw_output = xpddefault_service_perfdata_file_template; - - engine_logger(dbg_perfdata, most) - << "Raw service performance data file output: " << raw_output; - commands_logger->info("Raw service performance data file output: {}", - raw_output); - - // process any macros in the raw output line. - process_macros_r(mac, raw_output, processed_output, 0); - if (processed_output.empty()) - return ERROR; - - engine_logger(dbg_perfdata, most) - << "Processed service performance data file output: " << processed_output; - commands_logger->info("Processed service performance data file output: {}", - processed_output); - - // lock, write to and unlock host performance data file. - pthread_mutex_lock(&xpddefault_service_perfdata_fp_lock); - fputs(processed_output.c_str(), xpddefault_service_perfdata_fp); - fputc('\n', xpddefault_service_perfdata_fp); - fflush(xpddefault_service_perfdata_fp); - pthread_mutex_unlock(&xpddefault_service_perfdata_fp_lock); - - return result; -} - -// updates host performance data file. -int xpddefault_update_host_performance_data_file(nagios_macros* mac, - host* hst) { - std::string raw_output; - std::string processed_output; - int result(OK); - - engine_logger(dbg_functions, basic) << "update_host_performance_data_file()"; - functions_logger->trace("update_host_performance_data_file()"); - - if (hst == nullptr) - return ERROR; - - // we don't have a host perfdata file. - if (xpddefault_host_perfdata_fp == nullptr || - xpddefault_host_perfdata_file_template == nullptr) - return OK; - - // get the raw output. - raw_output = string::dup(xpddefault_host_perfdata_file_template); - - engine_logger(dbg_perfdata, most) - << "Raw host performance file output: " << raw_output; - commands_logger->info("Raw host performance file output: {}", raw_output); - - // process any macros in the raw output. - process_macros_r(mac, raw_output, processed_output, 0); - if (processed_output.empty()) - return ERROR; - - engine_logger(dbg_perfdata, most) - << "Processed host performance data file output: " << processed_output; - commands_logger->info("Processed host performance data file output: {}", - processed_output); - - // lock, write to and unlock host performance data file. - pthread_mutex_lock(&xpddefault_host_perfdata_fp_lock); - fputs(processed_output.c_str(), xpddefault_host_perfdata_fp); - fputc('\n', xpddefault_host_perfdata_fp); - fflush(xpddefault_host_perfdata_fp); - pthread_mutex_unlock(&xpddefault_host_perfdata_fp_lock); - - return result; -} - -// periodically process the host perf data file. -int xpddefault_process_host_perfdata_file() { - std::string raw_command_line; - std::string processed_command_line; - bool early_timeout = false; - double exectime(0.0); - int result(OK); - int macro_options(STRIP_ILLEGAL_MACRO_CHARS | ESCAPE_MACRO_CHARS); - nagios_macros* mac(get_global_macros()); - - engine_logger(dbg_functions, basic) << "process_host_perfdata_file()"; - functions_logger->trace("process_host_perfdata_file()"); - - // we don't have a command. - if (config->host_perfdata_file_processing_command().empty()) - return OK; - - // get the raw command line. - get_raw_command_line_r( - mac, xpddefault_host_perfdata_file_processing_command_ptr, - config->host_perfdata_file_processing_command().c_str(), raw_command_line, - macro_options); - if (raw_command_line.empty()) { - clear_volatile_macros_r(mac); - return ERROR; - } - - engine_logger(dbg_perfdata, most) - << "Raw host performance data file processing command line: " - << raw_command_line; - commands_logger->info( - "Raw host performance data file processing command line: {}", - raw_command_line); - - // process any macros in the raw command line. - process_macros_r(mac, raw_command_line, processed_command_line, - macro_options); - if (processed_command_line.empty()) { - clear_volatile_macros_r(mac); - return ERROR; - } - - engine_logger(dbg_perfdata, most) - << "Processed host performance data file processing command " - "line: " - << processed_command_line; - commands_logger->info( - "Processed host performance data file processing command line: {}", - processed_command_line); - - // lock and close the performance data file. - pthread_mutex_lock(&xpddefault_host_perfdata_fp_lock); - xpddefault_close_host_perfdata_file(); - - // run the command. - try { - std::string tmp; - my_system_r(mac, processed_command_line, config->perfdata_timeout(), - &early_timeout, &exectime, tmp, 0); - } catch (std::exception const& e) { - engine_logger(log_runtime_error, basic) - << "Error: can't execute host performance data file processing command " - "line '" - << processed_command_line << "' : " << e.what(); - runtime_logger->error( - "Error: can't execute host performance data file processing command " - "line '{}' : {}", - processed_command_line, e.what()); - } - clear_volatile_macros_r(mac); - - // re-open and unlock the performance data file. - xpddefault_open_host_perfdata_file(); - pthread_mutex_unlock(&xpddefault_host_perfdata_fp_lock); - - // check to see if the command timed out. - if (early_timeout) - engine_logger(log_runtime_warning, basic) - << "Warning: Host performance data file processing command '" - << processed_command_line << "' timed out after " - << config->perfdata_timeout() << " seconds"; - runtime_logger->warn( - "Warning: Host performance data file processing command '{}' timed out " - "after {} seconds", - processed_command_line, config->perfdata_timeout()); - return result; -} - -// periodically process the service perf data file. -int xpddefault_process_service_perfdata_file() { - std::string raw_command_line; - std::string processed_command_line; - bool early_timeout = false; - double exectime(0.0); - int result(OK); - int macro_options(STRIP_ILLEGAL_MACRO_CHARS | ESCAPE_MACRO_CHARS); - nagios_macros* mac(get_global_macros()); - - engine_logger(dbg_functions, basic) << "process_service_perfdata_file()"; - functions_logger->trace("process_service_perfdata_file()"); - - // we don't have a command. - if (config->service_perfdata_file_processing_command().empty()) - return OK; - - // get the raw command line. - get_raw_command_line_r( - mac, xpddefault_service_perfdata_file_processing_command_ptr, - config->service_perfdata_file_processing_command().c_str(), - raw_command_line, macro_options); - if (raw_command_line.empty()) { - clear_volatile_macros_r(mac); - return ERROR; - } - - engine_logger(dbg_perfdata, most) - << "Raw service performance data file processing " - "command line: " - << raw_command_line; - commands_logger->info( - "Raw service performance data file processing command line: {}", - raw_command_line); - - // process any macros in the raw command line. - process_macros_r(mac, raw_command_line, processed_command_line, - macro_options); - if (processed_command_line.empty()) { - clear_volatile_macros_r(mac); - return ERROR; - } - - engine_logger(dbg_perfdata, most) - << "Processed service performance data file processing " - "command line: " - << processed_command_line; - commands_logger->info( - "Processed service performance data file processing command line: {}", - processed_command_line); - - // lock and close the performance data file. - pthread_mutex_lock(&xpddefault_service_perfdata_fp_lock); - xpddefault_close_service_perfdata_file(); - - // run the command. - try { - std::string tmp; - my_system_r(mac, processed_command_line, config->perfdata_timeout(), - &early_timeout, &exectime, tmp, 0); - } catch (std::exception const& e) { - engine_logger(log_runtime_error, basic) - << "Error: can't execute service performance data file processing " - "command line '" - << processed_command_line << "' : " << e.what(); - runtime_logger->error( - "Error: can't execute service performance data file processing " - "command line '{}' : {}", - processed_command_line, e.what()); - } - - // re-open and unlock the performance data file. - xpddefault_open_service_perfdata_file(); - pthread_mutex_unlock(&xpddefault_service_perfdata_fp_lock); - - clear_volatile_macros_r(mac); - - // check to see if the command timed out. - if (early_timeout) - engine_logger(log_runtime_warning, basic) - << "Warning: Service performance data file processing command '" - << processed_command_line << "' timed out after " - << config->perfdata_timeout() << " seconds"; - runtime_logger->warn( - "Warning: Service performance data file processing command '{}' timed " - "out after {} seconds", - processed_command_line, config->perfdata_timeout()); - - // free memory. - return result; -} diff --git a/engine/tests/CMakeLists.txt b/engine/tests/CMakeLists.txt index 651c5ae6ef0..a464efc2e72 100755 --- a/engine/tests/CMakeLists.txt +++ b/engine/tests/CMakeLists.txt @@ -116,7 +116,6 @@ if(WITH_TESTING) "${TESTS_DIR}/opentelemetry/otl_server_test.cc" "${TESTS_DIR}/opentelemetry/otl_converter_test.cc" "${TESTS_DIR}/opentelemetry/open_telemetry_test.cc" - "${TESTS_DIR}/perfdata/perfdata.cc" "${TESTS_DIR}/retention/host.cc" "${TESTS_DIR}/retention/service.cc" "${TESTS_DIR}/string/string.cc" diff --git a/engine/tests/macros/macro_hostname.cc b/engine/tests/macros/macro_hostname.cc index feac8d44c7c..e6ef1cf1428 100644 --- a/engine/tests/macros/macro_hostname.cc +++ b/engine/tests/macros/macro_hostname.cc @@ -693,29 +693,6 @@ TEST_F(MacroHostname, HostCheckCommand) { ASSERT_EQ(out, "cmd"); } -TEST_F(MacroHostname, HostPerDataFile) { - configuration::parser parser; - configuration::state st; - configuration::error_cnt err; - - std::remove("/tmp/test-config.cfg"); - - std::ofstream ofs("/tmp/test-config.cfg"); - ofs << "host_perfdata_file=/var/log/centreon-engine/host-perfdata.dat" - << std::endl; - ofs << "log_file=\"\"" << std::endl; - ofs.close(); - - parser.parse("/tmp/test-config.cfg", st, err); - configuration::applier::state::instance().apply(st, err); - init_macros(); - - std::string out; - nagios_macros* mac(get_global_macros()); - process_macros_r(mac, "$HOSTPERFDATAFILE:test_host$", out, 1); - ASSERT_EQ(out, "/var/log/centreon-engine/host-perfdata.dat"); -} - TEST_F(MacroHostname, HostDisplayName) { configuration::applier::host hst_aply; configuration::host hst; diff --git a/engine/tests/macros/macro_service.cc b/engine/tests/macros/macro_service.cc index eca9965f227..13befa25cf2 100644 --- a/engine/tests/macros/macro_service.cc +++ b/engine/tests/macros/macro_service.cc @@ -969,29 +969,6 @@ TEST_F(MacroService, ServiceCheckCommand) { ASSERT_EQ(out, "cmd"); } -TEST_F(MacroService, ServicePerfDataFile) { - configuration::parser parser; - configuration::state st; - configuration::error_cnt err; - - std::remove("/tmp/test-config.cfg"); - - std::ofstream ofs("/tmp/test-config.cfg"); - ofs << "service_perfdata_file=/var/log/centreon-engine/service-perfdata.dat" - << std::endl; - ofs << "log_file=\"\"" << std::endl; - ofs.close(); - - parser.parse("/tmp/test-config.cfg", st, err); - configuration::applier::state::instance().apply(st, err); - init_macros(); - - std::string out; - nagios_macros* mac(get_global_macros()); - process_macros_r(mac, "$SERVICEPERFDATAFILE:test_host$", out, 1); - ASSERT_EQ(out, "/var/log/centreon-engine/service-perfdata.dat"); -} - TEST_F(MacroService, ServiceDisplayName) { configuration::applier::host hst_aply; configuration::applier::service svc_aply; diff --git a/engine/tests/perfdata/perfdata.cc b/engine/tests/perfdata/perfdata.cc deleted file mode 100644 index 9744bbfab4f..00000000000 --- a/engine/tests/perfdata/perfdata.cc +++ /dev/null @@ -1,32 +0,0 @@ -#include "com/centreon/engine/xpddefault.hh" -#include "gtest/gtest.h" - -TEST(preprocess_file_templates, WithAntislash_n) { - char test[] = "This is\\na multiline\\n\\text.\\n"; - xpddefault_preprocess_file_templates(test); - ASSERT_EQ(std::string(test), "This is\na multiline\n\text.\n"); -} - -TEST(preprocess_file_templates, NullLine) { - char* test = nullptr; - xpddefault_preprocess_file_templates(test); - ASSERT_EQ(test, nullptr); -} - -TEST(preprocess_file_templates, EmptyLine) { - char test[] = ""; - xpddefault_preprocess_file_templates(test); - ASSERT_EQ(std::string(test), ""); -} - -TEST(preprocess_file_templates, AntiSlash_t) { - char test[] = "\\tb\\tc\\t\\t\\td"; - xpddefault_preprocess_file_templates(test); - ASSERT_EQ(std::string(test), "\tb\tc\t\t\td"); -} - -TEST(preprocess_file_templates, AntiSlash_r) { - char test[] = "a\\rb\\rc\\r\\r\\r"; - xpddefault_preprocess_file_templates(test); - ASSERT_EQ(std::string(test), "a\rb\rc\r\r\r"); -} From 612c91a7c2828a762f7bb058c66cfda9cf267e61 Mon Sep 17 00:00:00 2001 From: jean-christophe81 <98889244+jean-christophe81@users.noreply.github.com> Date: Tue, 2 Jul 2024 14:19:16 +0200 Subject: [PATCH 59/60] MON-63843 engine accept connections from centreon monitoring agent (#1485) * engine accept connections from centreon monitoring agent * add some comments * review comments --- agent/precomp_inc/precomp.hh | 21 +- agent/src/scheduler.cc | 23 +- .../com/centreon/common/grpc/grpc_config.hh | 31 ++ engine/CMakeLists.txt | 1 + engine/modules/opentelemetry/CMakeLists.txt | 35 +- .../opentelemetry/doc/opentelemetry.md | 154 ++++++ .../agent_check_result_builder.hh | 117 +++++ .../centreon_agent/agent_config.hh | 76 +++ .../centreon_agent/agent_impl.hh | 114 +++++ .../centreon_agent/agent_service.hh | 75 +++ .../modules/opentelemetry/grpc_config.hh | 8 + .../modules/opentelemetry/open_telemetry.hh | 4 +- .../opentelemetry/otl_check_result_builder.hh | 5 +- .../modules/opentelemetry/otl_config.hh | 7 + .../modules/opentelemetry/otl_data_point.hh | 15 + .../engine/modules/opentelemetry/otl_fmt.hh | 66 +++ .../modules/opentelemetry/otl_server.hh | 26 +- .../opentelemetry/precomp_inc/precomp.hh | 1 + .../agent_check_result_builder.cc | 185 +++++++ .../src/centreon_agent/agent_config.cc | 154 ++++++ .../src/centreon_agent/agent_impl.cc | 446 ++++++++++++++++ .../src/centreon_agent/agent_service.cc | 162 ++++++ .../opentelemetry/src/host_serv_extractor.cc | 23 +- .../opentelemetry/src/open_telemetry.cc | 35 +- .../src/otl_check_result_builder.cc | 11 + .../modules/opentelemetry/src/otl_config.cc | 59 ++- .../opentelemetry/src/otl_data_point.cc | 13 + .../modules/opentelemetry/src/otl_server.cc | 32 +- engine/precomp_inc/precomp.hh | 1 + engine/src/configuration/applier/state.cc | 10 +- engine/tests/CMakeLists.txt | 5 +- .../agent_check_result_builder_test.cc | 484 ++++++++++++++++++ .../opentelemetry/open_telemetry_test.cc | 4 +- .../tests/opentelemetry/otl_converter_test.cc | 6 + engine/tests/opentelemetry/otl_server_test.cc | 14 +- engine/tests/test_engine.cc | 22 +- engine/tests/test_engine.hh | 11 +- 37 files changed, 2368 insertions(+), 88 deletions(-) create mode 100644 engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/centreon_agent/agent_check_result_builder.hh create mode 100644 engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/centreon_agent/agent_config.hh create mode 100644 engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/centreon_agent/agent_impl.hh create mode 100644 engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/centreon_agent/agent_service.hh create mode 100644 engine/modules/opentelemetry/src/centreon_agent/agent_check_result_builder.cc create mode 100644 engine/modules/opentelemetry/src/centreon_agent/agent_config.cc create mode 100644 engine/modules/opentelemetry/src/centreon_agent/agent_impl.cc create mode 100644 engine/modules/opentelemetry/src/centreon_agent/agent_service.cc create mode 100644 engine/tests/opentelemetry/agent_check_result_builder_test.cc diff --git a/agent/precomp_inc/precomp.hh b/agent/precomp_inc/precomp.hh index f5384ddeb8f..1cc4bcd1c5f 100644 --- a/agent/precomp_inc/precomp.hh +++ b/agent/precomp_inc/precomp.hh @@ -1,20 +1,19 @@ /** * Copyright 2024 Centreon * - * This file is part of Centreon Agent. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Centreon Engine is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License version 2 - * as published by the Free Software Foundation. + * http://www.apache.org/licenses/LICENSE-2.0 * - * Centreon Engine is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. * - * You should have received a copy of the GNU General Public License - * along with Centreon Engine. If not, see - * . + * For more information : contact@centreon.com */ #ifndef CA_PRECOMP_HH diff --git a/agent/src/scheduler.cc b/agent/src/scheduler.cc index 207ef35721e..890f9d62dff 100644 --- a/agent/src/scheduler.cc +++ b/agent/src/scheduler.cc @@ -1,20 +1,19 @@ /** * Copyright 2024 Centreon * - * This file is part of Centreon Agent. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Centreon Engine is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License version 2 - * as published by the Free Software Foundation. + * http://www.apache.org/licenses/LICENSE-2.0 * - * Centreon Engine is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. * - * You should have received a copy of the GNU General Public License - * along with Centreon Engine. If not, see - * . + * For more information : contact@centreon.com */ #include "scheduler.hh" @@ -402,7 +401,7 @@ void scheduler::_add_metric_to_scope( auto metric = _get_metric(scope_metric, perf.name()); metric->set_unit(perf.unit()); auto data_point = metric->mutable_gauge()->add_data_points(); - data_point->set_as_int(perf.value()); + data_point->set_as_double(perf.value()); data_point->set_time_unix_nano(now); switch (perf.value_type()) { case com::centreon::common::perfdata::counter: { diff --git a/common/grpc/inc/com/centreon/common/grpc/grpc_config.hh b/common/grpc/inc/com/centreon/common/grpc/grpc_config.hh index 2d8b5978be9..4d151fa0baa 100644 --- a/common/grpc/inc/com/centreon/common/grpc/grpc_config.hh +++ b/common/grpc/inc/com/centreon/common/grpc/grpc_config.hh @@ -101,6 +101,37 @@ class grpc_config { _compress == right._compress && _second_keepalive_interval == right._second_keepalive_interval; } + + /** + * @brief identical to std:string::compare + * + * @param right + * @return int -1, 0 if equal or 1 + */ + int compare(const grpc_config& right) const { + int ret = _hostport.compare(right._hostport); + if (ret) + return ret; + ret = _crypted - right._crypted; + if (ret) + return ret; + ret = _certificate.compare(right._certificate); + if (ret) + return ret; + ret = _cert_key.compare(right._cert_key); + if (ret) + return ret; + ret = _ca_cert.compare(right._ca_cert); + if (ret) + return ret; + ret = _ca_name.compare(right._ca_name); + if (ret) + return ret; + ret = _compress - right._compress; + if (ret) + return ret; + return _second_keepalive_interval - right._second_keepalive_interval; + } }; } // namespace com::centreon::common::grpc diff --git a/engine/CMakeLists.txt b/engine/CMakeLists.txt index 2f51ffb32d9..fe556d5bbfc 100644 --- a/engine/CMakeLists.txt +++ b/engine/CMakeLists.txt @@ -525,6 +525,7 @@ target_link_libraries( cce_core gRPC::grpc++ boost_program_options + protobuf "-Wl,--no-whole-archive" gRPC::gpr gRPC::grpc diff --git a/engine/modules/opentelemetry/CMakeLists.txt b/engine/modules/opentelemetry/CMakeLists.txt index f3407f88aaa..16d1976fdc3 100644 --- a/engine/modules/opentelemetry/CMakeLists.txt +++ b/engine/modules/opentelemetry/CMakeLists.txt @@ -20,7 +20,6 @@ set(MODULE_DIR "${PROJECT_SOURCE_DIR}/modules/opentelemetry") set(SRC_DIR "${MODULE_DIR}/src") - #protobuf service set(service_files opentelemetry/proto/collector/metrics/v1/metrics_service @@ -42,9 +41,33 @@ foreach(name IN LISTS service_files) endforeach() +#centagent server and client +add_custom_command( + DEPENDS ${CMAKE_SOURCE_DIR}/agent/proto/agent.proto + COMMENT "Generating interface files of the conf centreon_agent proto file (grpc)" + OUTPUT ${SRC_DIR}/centreon_agent/agent.grpc.pb.cc + COMMAND + ${Protobuf_PROTOC_EXECUTABLE} ARGS + --plugin=protoc-gen-grpc=${GRPC_CPP_PLUGIN} + --proto_path=${CMAKE_SOURCE_DIR}/agent/proto --proto_path=${CMAKE_SOURCE_DIR}/opentelemetry-proto + --grpc_out=${SRC_DIR}/centreon_agent ${CMAKE_SOURCE_DIR}/agent/proto/agent.proto + DEPENDS ${CMAKE_SOURCE_DIR}/agent/proto/agent.proto + COMMENT "Generating interface files of the conf centreon_agent proto file (protobuf)" + OUTPUT ${SRC_DIR}/centreon_agent/agent.pb.cc + COMMAND + ${Protobuf_PROTOC_EXECUTABLE} ARGS --cpp_out=${SRC_DIR}/centreon_agent + --proto_path=${CMAKE_SOURCE_DIR}/agent/proto --proto_path=${CMAKE_SOURCE_DIR}/opentelemetry-proto + ${CMAKE_SOURCE_DIR}/agent/proto/agent.proto + WORKING_DIRECTORY ${CMAKE_BINARY_DIR}) # mod_externalcmd target. -add_library(opentelemetry SHARED +add_library(opentelemetry SHARED +${SRC_DIR}/centreon_agent/agent.grpc.pb.cc +${SRC_DIR}/centreon_agent/agent.pb.cc +${SRC_DIR}/centreon_agent/agent_check_result_builder.cc +${SRC_DIR}/centreon_agent/agent_config.cc +${SRC_DIR}/centreon_agent/agent_impl.cc +${SRC_DIR}/centreon_agent/agent_service.cc ${SRC_DIR}/data_point_fifo.cc ${SRC_DIR}/data_point_fifo_container.cc ${SRC_DIR}/grpc_config.cc @@ -63,11 +86,15 @@ ${SRC_DIR}/opentelemetry/proto/collector/metrics/v1/metrics_service.grpc.pb.cc target_precompile_headers(opentelemetry PRIVATE precomp_inc/precomp.hh) # set(EXTERNALCMD_MODULE "${EXTERNALCMD_MODULE}" PARENT_SCOPE) -target_link_libraries(opentelemetry spdlog::spdlog) +target_link_libraries(opentelemetry + spdlog::spdlog + -L${Boost_LIBRARY_DIR_RELEASE} + boost_program_options) add_dependencies(opentelemetry pb_open_telemetry_lib - pb_neb_lib) + pb_neb_lib + engine_rpc) target_include_directories(opentelemetry PRIVATE "${MODULE_DIR}/inc/com/centreon/engine/modules/opentelemetry" diff --git a/engine/modules/opentelemetry/doc/opentelemetry.md b/engine/modules/opentelemetry/doc/opentelemetry.md index 3ad030d9e8a..4e5867924f5 100644 --- a/engine/modules/opentelemetry/doc/opentelemetry.md +++ b/engine/modules/opentelemetry/doc/opentelemetry.md @@ -207,3 +207,157 @@ An example of configuration: } } ``` + +### centreon monitoring agent +Even if all protobuf objects are opentelemetry objects, grpc communication is made in streaming mode. It is more efficient, it allows reverse connection (engine can connect to an agent running in a DMZ) and +Engine can send configuration on each config update. +You can find all grpc definitions are agent/proto/agent.proto. +Every time engine configuration is updated, we calculate configuration for each connected agent and send it on the wire if we find a difference with the old configuration. That's why each connection has a ```agent::MessageToAgent _last_config``` attribute. +So, the opentelemetry engine server supports two services, opentelemetry service and agent streaming service. +OpenTelemetry data is different from telegraf one: +* host service attributes are stored in resource_metrics.resource.attributes +* performance data (min, max, critical lt, warning gt...) is stored in exemplar, service status is stored in status metric + +Example for metric output ```OK - 127.0.0.1: rta 0,010ms, lost 0%|rta=0,010ms;200,000;500,000;0; pl=0%;40;80;; rtmax=0,035ms;;;; rtmin=0,003ms;;;;```: +```json +resource_metrics { + resource { + attributes { + key: "host.name" + value { + string_value: "host_1" + } + } + attributes { + key: "service.name" + value { + string_value: "" + } + } + } + scope_metrics { + metrics { + name: "status" + description: "OK - 127.0.0.1: rta 0,010ms, lost 0%" + gauge { + data_points { + time_unix_nano: 1719911975421977886 + as_int: 0 + } + } + } + metrics { + name: "rta" + unit: "ms" + gauge { + data_points { + time_unix_nano: 1719911975421977886 + exemplars { + as_double: 500 + filtered_attributes { + key: "crit_gt" + } + } + exemplars { + as_double: 0 + filtered_attributes { + key: "crit_lt" + } + } + exemplars { + as_double: 200 + filtered_attributes { + key: "warn_gt" + } + } + exemplars { + as_double: 0 + filtered_attributes { + key: "warn_lt" + } + } + exemplars { + as_double: 0 + filtered_attributes { + key: "min" + } + } + as_double: 0 + } + } + } + metrics { + name: "pl" + unit: "%" + gauge { + data_points { + time_unix_nano: 1719911975421977886 + exemplars { + as_double: 80 + filtered_attributes { + key: "crit_gt" + } + } + exemplars { + as_double: 0 + filtered_attributes { + key: "crit_lt" + } + } + exemplars { + as_double: 40 + filtered_attributes { + key: "warn_gt" + } + } + exemplars { + as_double: 0 + filtered_attributes { + key: "warn_lt" + } + } + as_double: 0 + } + } + } + metrics { + name: "rtmax" + unit: "ms" + gauge { + data_points { + time_unix_nano: 1719911975421977886 + as_double: 0 + } + } + } + metrics { + name: "rtmin" + unit: "ms" + gauge { + data_points { + time_unix_nano: 1719911975421977886 + as_double: 0 + } + } + } + } +}``` + +Parsing of this format is done by ```agent_check_result_builder``` class + +Configuration of agent is divided in two parts: +* A common part to all agents: + ```protobuf + uint32 check_interval = 2; + //limit the number of active checks in order to limit charge + uint32 max_concurrent_checks = 3; + //period of metric exports (in seconds) + uint32 export_period = 4; + //after this timeout, process is killed (in seconds) + uint32 check_timeout = 5; + ``` +* A list of services that agent has to check + +The first part is owned by agent protobuf service (agent_service.cc), the second is build by a common code shared with telegraf server (conf_helper.hh) + +So when centengine receives a HUP signal, opentelemetry::reload check configuration changes on each established connection and update also agent service conf part1 which is used to configure future incoming connections. \ No newline at end of file diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/centreon_agent/agent_check_result_builder.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/centreon_agent/agent_check_result_builder.hh new file mode 100644 index 00000000000..adcee312878 --- /dev/null +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/centreon_agent/agent_check_result_builder.hh @@ -0,0 +1,117 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#ifndef CCE_MOD_OTL_AGENT_CHECK_RESULT_BUILDER_HH +#define CCE_MOD_OTL_AGENT_CHECK_RESULT_BUILDER_HH + +namespace com::centreon::engine::modules::opentelemetry::centreon_agent { + +/** + * @brief in order to save network usage, agent store metrics infos in examplar + * An example of protobuf data: + * @code {.json} + { + "name": "metric2", + "unit": "ms", + "gauge": { + "dataPoints": [ + { + "timeUnixNano": "1718345061381922153", + "exemplars": [ + { + "asDouble": 80, + "filteredAttributes": [ + { + "key": "crit_gt" + } + ] + }, + { + "asDouble": 75, + "filteredAttributes": [ + { + "key": "crit_lt" + } + ] + }, + { + "asDouble": 75, + "filteredAttributes": [ + { + "key": "warn_gt" + } + ] + }, + { + "asDouble": 50, + "filteredAttributes": [ + { + "key": "warn_lt" + } + ] + }, + { + "asDouble": 0, + "filteredAttributes": [ + { + "key": "min" + } + ] + }, + { + "asDouble": 100, + "filteredAttributes": [ + { + "key": "max" + } + ] + } + ], + "asDouble": 30 + } + ] + } + * @endcode + * + * + */ +class agent_check_result_builder : public otl_check_result_builder { + protected: + bool _build_result_from_metrics(metric_name_to_fifo& fifos, + commands::result& res) override; + + public: + agent_check_result_builder(const std::string& cmd_line, + uint64_t command_id, + const host& host, + const service* service, + std::chrono::system_clock::time_point timeout, + commands::otel::result_callback&& handler, + const std::shared_ptr& logger) + : otl_check_result_builder(cmd_line, + command_id, + host, + service, + timeout, + std::move(handler), + logger) {} +}; + +} // namespace com::centreon::engine::modules::opentelemetry::centreon_agent + +#endif \ No newline at end of file diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/centreon_agent/agent_config.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/centreon_agent/agent_config.hh new file mode 100644 index 00000000000..f65940cbf92 --- /dev/null +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/centreon_agent/agent_config.hh @@ -0,0 +1,76 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#ifndef CCE_MOD_OTL_CENTREON_AGENT_AGENT_CONFIG_HH +#define CCE_MOD_OTL_CENTREON_AGENT_AGENT_CONFIG_HH + +#include "com/centreon/engine/modules/opentelemetry/grpc_config.hh" + +namespace com::centreon::engine::modules::opentelemetry::centreon_agent { + +class agent_config { + public: + using grpc_config_set = + absl::btree_set; + + using pointer = std::shared_ptr; + + private: + // all endpoints engine has to connect to + grpc_config_set _agent_grpc_reverse_conf; + // delay between 2 checks of one service, so we will do all check in that + // period (in seconds) + uint32_t _check_interval; + // limit the number of active checks in order to limit charge + uint32_t _max_concurrent_checks; + // period of metric exports (in seconds) + uint32_t _export_period; + // after this timeout, process is killed (in seconds) + uint32_t _check_timeout; + + public: + agent_config(const rapidjson::Value& json_config_v); + + // used for tests + agent_config(uint32_t check_interval, + uint32_t max_concurrent_checks, + uint32_t export_period, + uint32_t check_timeout); + + agent_config(uint32_t check_interval, + uint32_t max_concurrent_checks, + uint32_t export_period, + uint32_t check_timeout, + const std::initializer_list& endpoints); + + const grpc_config_set& get_agent_grpc_reverse_conf() const { + return _agent_grpc_reverse_conf; + } + + uint32_t get_check_interval() const { return _check_interval; } + uint32_t get_max_concurrent_checks() const { return _max_concurrent_checks; } + uint32_t get_export_period() const { return _export_period; } + uint32_t get_check_timeout() const { return _check_timeout; } + + bool operator==(const agent_config& right) const; + + bool operator!=(const agent_config& right) const { return !(*this == right); } +}; + +}; // namespace com::centreon::engine::modules::opentelemetry::centreon_agent +#endif diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/centreon_agent/agent_impl.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/centreon_agent/agent_impl.hh new file mode 100644 index 00000000000..41d63ac029c --- /dev/null +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/centreon_agent/agent_impl.hh @@ -0,0 +1,114 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#ifndef CCE_MOD_OTL_CENTREON_AGENT_AGENT_IMPL_HH +#define CCE_MOD_OTL_CENTREON_AGENT_AGENT_IMPL_HH + +#include "centreon_agent/agent.grpc.pb.h" +#include "com/centreon/engine/modules/opentelemetry/centreon_agent/agent_config.hh" +#include "com/centreon/engine/modules/opentelemetry/otl_data_point.hh" + +namespace com::centreon::engine::modules::opentelemetry::centreon_agent { + +/** + * @brief this class manages connection with centreon monitoring agent + * reverse connection or no + * + * @tparam bireactor_class (grpc::bireactor<,>) + */ +template +class agent_impl + : public bireactor_class, + public std::enable_shared_from_this> { + std::shared_ptr _io_context; + const std::string_view _class_name; + + agent_config::pointer _conf ABSL_GUARDED_BY(_protect); + + metric_handler _metric_handler; + + std::shared_ptr _agent_info + ABSL_GUARDED_BY(_protect); + std::shared_ptr _last_sent_config + ABSL_GUARDED_BY(_protect); + + static std::set> _instances + ABSL_GUARDED_BY(_instances_m); + static absl::Mutex _instances_m; + + bool _write_pending; + std::deque> _write_queue + ABSL_GUARDED_BY(_protect); + std::shared_ptr _read_current + ABSL_GUARDED_BY(_protect); + + void _calc_and_send_config_if_needed(); + + virtual const std::string& get_peer() const = 0; + + void _write(const std::shared_ptr& request); + + protected: + std::shared_ptr _logger; + bool _alive ABSL_GUARDED_BY(_protect); + mutable absl::Mutex _protect; + + public: + agent_impl(const std::shared_ptr& io_context, + const std::string_view class_name, + const agent_config::pointer& conf, + const metric_handler& handler, + const std::shared_ptr& logger); + + virtual ~agent_impl(); + + void calc_and_send_config_if_needed(const agent_config::pointer& new_conf); + + static void all_agent_calc_and_send_config_if_needed( + const agent_config::pointer& new_conf); + + static void update_config(); + + void on_request(const std::shared_ptr& request); + + static void register_stream(const std::shared_ptr& strm); + + void start_read(); + + void start_write(); + + // bireactor part + void OnReadDone(bool ok) override; + + virtual void on_error() = 0; + + void OnWriteDone(bool ok) override; + + // server version + void OnDone(); + // client version + void OnDone(const ::grpc::Status& /*s*/); + + virtual void shutdown(); + + static void shutdown_all(); +}; + +} // namespace com::centreon::engine::modules::opentelemetry::centreon_agent + +#endif diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/centreon_agent/agent_service.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/centreon_agent/agent_service.hh new file mode 100644 index 00000000000..a58f8263a50 --- /dev/null +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/centreon_agent/agent_service.hh @@ -0,0 +1,75 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#ifndef CCE_MOD_OTL_CENTREON_AGENT_AGENT_SERVICE_HH +#define CCE_MOD_OTL_CENTREON_AGENT_AGENT_SERVICE_HH + +#include "com/centreon/engine/modules/opentelemetry/centreon_agent/agent_config.hh" +#include "com/centreon/engine/modules/opentelemetry/centreon_agent/agent_impl.hh" + +namespace com::centreon::engine::modules::opentelemetry::centreon_agent { + +/** + * @brief this class is a grpc service provided by otel_server for incoming + * centreon monitoring agent connection + * + */ +class agent_service : public agent::AgentService::Service, + public std::enable_shared_from_this { + std::shared_ptr _io_context; + agent_config::pointer _conf; + absl::Mutex _conf_m; + + metric_handler _metric_handler; + std::shared_ptr _logger; + + public: + agent_service(const std::shared_ptr& io_context, + const agent_config::pointer& conf, + const metric_handler& handler, + const std::shared_ptr& logger); + + void init(); + + static std::shared_ptr load( + const std::shared_ptr& io_context, + const agent_config::pointer& conf, + const metric_handler& handler, + const std::shared_ptr& logger); + + // disable synchronous version of this method + ::grpc::Status Export( + ::grpc::ServerContext* /*context*/, + ::grpc::ServerReaderWriter* /*stream*/) + override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + + ::grpc::ServerBidiReactor* + Export(::grpc::CallbackServerContext* context); + + void update(const agent_config::pointer& conf); + + static void shutdown_all_accepted(); +}; + +} // namespace com::centreon::engine::modules::opentelemetry::centreon_agent + +#endif diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/grpc_config.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/grpc_config.hh index a31149670f7..8775f42c420 100644 --- a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/grpc_config.hh +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/grpc_config.hh @@ -43,6 +43,14 @@ class grpc_config : public common::grpc::grpc_config { return !(*this == right); } }; + +struct grpc_config_compare { + bool operator()(const grpc_config::pointer& left, + const grpc_config::pointer& right) const { + return left->compare(*right) < 0; + } +}; + } // namespace com::centreon::engine::modules::opentelemetry #endif // !CCE_MOD_OTL_SERVER_GRPC_CONFIG_HH diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/open_telemetry.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/open_telemetry.hh index b558b07c4e4..ee2d82e7ef3 100644 --- a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/open_telemetry.hh +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/open_telemetry.hh @@ -98,7 +98,9 @@ class open_telemetry : public commands::otel::open_telemetry_base { const telegraf::conf_server_config::pointer& conf); protected: - virtual void _create_otl_server(const grpc_config::pointer& server_conf); + virtual void _create_otl_server( + const grpc_config::pointer& server_conf, + const centreon_agent::agent_config::pointer& agent_conf); void _on_metric(const metric_request_ptr& metric); void _reload(); void _start_second_timer(); diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_check_result_builder.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_check_result_builder.hh index 2c1d3526819..71b44670c3a 100644 --- a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_check_result_builder.hh +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_check_result_builder.hh @@ -35,7 +35,10 @@ class data_point_fifo_container; class check_result_builder_config : public commands::otel::check_result_builder_config { public: - enum class converter_type { nagios_check_result_builder }; + enum class converter_type { + nagios_check_result_builder, + centreon_agent_check_result_builder + }; private: const converter_type _type; diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_config.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_config.hh index 16276151653..5b87b0db2fb 100644 --- a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_config.hh +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_config.hh @@ -19,6 +19,7 @@ #ifndef CCE_MOD_OTL_SERVER_OTLCONFIG_HH #define CCE_MOD_OTL_SERVER_OTLCONFIG_HH +#include "centreon_agent/agent_config.hh" #include "grpc_config.hh" #include "telegraf/conf_server.hh" @@ -27,6 +28,8 @@ class otl_config { grpc_config::pointer _grpc_conf; telegraf::conf_server_config::pointer _telegraf_conf_server_config; + centreon_agent::agent_config::pointer _centreon_agent_config; + int _max_length_grpc_log = -1; // all otel are logged if negative bool _json_grpc_log = false; // if true, otel object are logged in json // format instead of protobuf debug format @@ -46,6 +49,10 @@ class otl_config { return _telegraf_conf_server_config; } + centreon_agent::agent_config::pointer get_centreon_agent_config() const { + return _centreon_agent_config; + } + int get_max_length_grpc_log() const { return _max_length_grpc_log; } bool get_json_grpc_log() const { return _json_grpc_log; } diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_data_point.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_data_point.hh index 1e0ca128278..bad1bc2236e 100644 --- a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_data_point.hh +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_data_point.hh @@ -88,6 +88,13 @@ using metric_request_ptr = std::shared_ptr<::opentelemetry::proto::collector::metrics::v1:: ExportMetricsServiceRequest>; +/** + * @brief the server grpc model used is the callback model + * So you need to give to the server this handler to handle incoming requests + * + */ +using metric_handler = std::function; + /** * @brief some metrics will be computed and other not * This bean represents a DataPoint, it embeds all ExportMetricsServiceRequest @@ -113,6 +120,8 @@ class otl_data_point { const google::protobuf::Message& _data_point; const ::google::protobuf::RepeatedPtrField< ::opentelemetry::proto::common::v1::KeyValue>& _data_point_attributes; + const ::google::protobuf::RepeatedPtrField< + ::opentelemetry::proto::metrics::v1::Exemplar>& _exemplars; uint64_t _nano_timestamp; data_point_type _type; double _value; @@ -176,6 +185,12 @@ class otl_data_point { double get_value() const { return _value; } + const ::google::protobuf::RepeatedPtrField< + ::opentelemetry::proto::metrics::v1::Exemplar>& + get_exemplars() const { + return _exemplars; + } + template static void extract_data_points(const metric_request_ptr& metrics, data_point_handler&& handler); diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_fmt.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_fmt.hh index c50048a6d0b..40c2facfd18 100644 --- a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_fmt.hh +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_fmt.hh @@ -63,6 +63,72 @@ struct formatter< } }; +template <> +struct formatter + : formatter { + /** + * @brief if this static parameter is < 0, we dump all request, otherwise, we + * limit dump length to this value + * + */ + template + auto format(const com::centreon::agent::MessageFromAgent& p, + FormatContext& ctx) const -> decltype(ctx.out()) { + using otl_formatter = + formatter< ::opentelemetry::proto::collector::metrics::v1:: + ExportMetricsServiceRequest>; + + if (otl_formatter::json_grpc_format) { + std::string output; + google::protobuf::util::MessageToJsonString(p, &output); + return formatter::format( + otl_formatter::max_length_log > 0 + ? output.substr(0, otl_formatter::max_length_log) + : output, + ctx); + } else { + return formatter::format( + otl_formatter::max_length_log > 0 + ? p.ShortDebugString().substr(0, otl_formatter::max_length_log) + : p.ShortDebugString(), + ctx); + } + } +}; + +template <> +struct formatter + : formatter { + /** + * @brief if this static parameter is < 0, we dump all request, otherwise, we + * limit dump length to this value + * + */ + template + auto format(const com::centreon::agent::MessageToAgent& p, + FormatContext& ctx) const -> decltype(ctx.out()) { + using otl_formatter = + formatter< ::opentelemetry::proto::collector::metrics::v1:: + ExportMetricsServiceRequest>; + + if (otl_formatter::json_grpc_format) { + std::string output; + google::protobuf::util::MessageToJsonString(p, &output); + return formatter::format( + otl_formatter::max_length_log > 0 + ? output.substr(0, otl_formatter::max_length_log) + : output, + ctx); + } else { + return formatter::format( + otl_formatter::max_length_log > 0 + ? p.ShortDebugString().substr(0, otl_formatter::max_length_log) + : p.ShortDebugString(), + ctx); + } + } +}; + }; // namespace fmt #endif diff --git a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_server.hh b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_server.hh index 0dd766bb982..935aac30d9c 100644 --- a/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_server.hh +++ b/engine/modules/opentelemetry/inc/com/centreon/engine/modules/opentelemetry/otl_server.hh @@ -24,6 +24,7 @@ #include "otl_data_point.hh" #include "com/centreon/common/grpc/grpc_server.hh" +#include "com/centreon/engine/modules/opentelemetry/centreon_agent/agent_service.hh" namespace com::centreon::engine::modules::opentelemetry { @@ -31,13 +32,6 @@ namespace detail { class metric_service; }; -/** - * @brief the server grpc model used is the callback model - * So you need to give to the server this handler to handle incoming requests - * - */ -using metric_handler = std::function; - /** * @brief grpc metric receiver server * must be constructed with load method @@ -45,8 +39,12 @@ using metric_handler = std::function; */ class otl_server : public common::grpc::grpc_server_base { std::shared_ptr _service; + std::shared_ptr _agent_service; + absl::Mutex _protect; - otl_server(const grpc_config::pointer& conf, + otl_server(const std::shared_ptr& io_context, + const grpc_config::pointer& conf, + const centreon_agent::agent_config::pointer& agent_config, const metric_handler& handler, const std::shared_ptr& logger); void start(); @@ -56,9 +54,15 @@ class otl_server : public common::grpc::grpc_server_base { ~otl_server(); - static pointer load(const grpc_config::pointer& conf, - const metric_handler& handler, - const std::shared_ptr& logger); + static pointer load( + const std::shared_ptr& io_context, + const grpc_config::pointer& conf, + const centreon_agent::agent_config::pointer& agent_config, + const metric_handler& handler, + const std::shared_ptr& logger); + + void update_agent_config( + const centreon_agent::agent_config::pointer& agent_config); }; } // namespace com::centreon::engine::modules::opentelemetry diff --git a/engine/modules/opentelemetry/precomp_inc/precomp.hh b/engine/modules/opentelemetry/precomp_inc/precomp.hh index 67a56f7e324..de025ed071d 100644 --- a/engine/modules/opentelemetry/precomp_inc/precomp.hh +++ b/engine/modules/opentelemetry/precomp_inc/precomp.hh @@ -25,6 +25,7 @@ #include #include +#include #include #include #include diff --git a/engine/modules/opentelemetry/src/centreon_agent/agent_check_result_builder.cc b/engine/modules/opentelemetry/src/centreon_agent/agent_check_result_builder.cc new file mode 100644 index 00000000000..769869ea12e --- /dev/null +++ b/engine/modules/opentelemetry/src/centreon_agent/agent_check_result_builder.cc @@ -0,0 +1,185 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#include "data_point_fifo_container.hh" + +#include "otl_check_result_builder.hh" + +#include "centreon_agent/agent_check_result_builder.hh" + +using namespace com::centreon::engine::modules::opentelemetry::centreon_agent; + +namespace com::centreon::engine::modules::opentelemetry::centreon_agent:: + detail { + +/** + * @brief used to create centreon perfdata from agent metric data + * + */ +struct perf_data { + std::optional warning_le, warning_lt, warning_ge, warning_gt; + std::optional critical_le, critical_lt, critical_ge, critical_gt; + std::optional min, max; + + void apply_exemplar( + const ::opentelemetry::proto::metrics::v1::Exemplar& exemplar); + + void append_to_string(std::string* to_append); + + static const absl::flat_hash_map perf_data::*> + _suffix_to_value; +}; + +const absl::flat_hash_map perf_data::*> + perf_data::_suffix_to_value = {{"warn_le", &perf_data::warning_le}, + {"warn_lt", &perf_data::warning_lt}, + {"warn_ge", &perf_data::warning_ge}, + {"warn_gt", &perf_data::warning_gt}, + {"crit_le", &perf_data::critical_le}, + {"crit_lt", &perf_data::critical_lt}, + {"crit_ge", &perf_data::critical_ge}, + {"crit_gt", &perf_data::critical_gt}, + {"min", &perf_data::min}, + {"max", &perf_data::max}}; + +/** + * @brief all metrics sub values are stored in exemplars, so we apply above + * table to perfdata + * + * @param exemplar + */ +void perf_data::apply_exemplar( + const ::opentelemetry::proto::metrics::v1::Exemplar& exemplar) { + if (!exemplar.filtered_attributes().empty()) { + auto search = + _suffix_to_value.find(exemplar.filtered_attributes().begin()->key()); + if (search != _suffix_to_value.end()) { + this->*search->second = exemplar.as_double(); + } + } +} + +/** + * @brief create a nagios style perfdata string from protobuf received data + * + * @param to_append + */ +void perf_data::append_to_string(std::string* to_append) { + if (warning_le) { + absl::StrAppend(to_append, "@", *warning_le, ":"); + if (warning_ge) + absl::StrAppend(to_append, *warning_ge); + } else if (warning_ge) { + absl::StrAppend(to_append, "@~:", *warning_ge); + } else if (warning_lt) { + absl::StrAppend(to_append, *warning_lt, ":"); + if (warning_gt) + absl::StrAppend(to_append, *warning_gt); + } else if (warning_gt) { + absl::StrAppend(to_append, "~:", *warning_gt); + } + to_append->push_back(';'); + if (critical_le) { + absl::StrAppend(to_append, "@", *critical_le, ":"); + if (critical_ge) + absl::StrAppend(to_append, *critical_ge); + } else if (critical_ge) { + absl::StrAppend(to_append, "@~:", *critical_ge); + } else if (critical_lt) { + absl::StrAppend(to_append, *critical_lt, ":"); + if (critical_gt) + absl::StrAppend(to_append, *critical_gt); + } else if (critical_gt) { + absl::StrAppend(to_append, "~:", *critical_gt); + } + to_append->push_back(';'); + if (min) + absl::StrAppend(to_append, *min); + to_append->push_back(';'); + if (max) + absl::StrAppend(to_append, *max); +} + +} // namespace + // com::centreon::engine::modules::opentelemetry::centreon_agent::detail + +/** + * @brief + * + * @param fifos all metrics for a given service + * @param res + * @return true + * @return false + */ +bool agent_check_result_builder::_build_result_from_metrics( + metric_name_to_fifo& fifos, + commands::result& res) { + // first we search last state timestamp from status + uint64_t last_time = 0; + + for (auto& metric_to_fifo : fifos) { + if (metric_to_fifo.first == "status") { + auto& fifo = metric_to_fifo.second.get_fifo(); + if (!fifo.empty()) { + const auto& last_sample = *fifo.rbegin(); + last_time = last_sample.get_nano_timestamp(); + res.exit_code = last_sample.get_value(); + // output of plugins is stored in description metric field + res.output = last_sample.get_metric().description(); + metric_to_fifo.second.clean_oldest(last_time); + } + break; + } + } + if (!last_time) { + return false; + } + res.command_id = get_command_id(); + res.exit_status = process::normal; + res.end_time = res.start_time = + timestamp(last_time / 1000000000, (last_time / 1000) % 1000000); + + res.output.push_back('|'); + + for (auto& metric_to_fifo : fifos) { + if (metric_to_fifo.first == "status") + continue; + auto& fifo = metric_to_fifo.second.get_fifo(); + auto data_pt_search = fifo.find(last_time); + if (data_pt_search != fifo.end()) { + res.output.push_back(' '); + const otl_data_point& data_pt = *data_pt_search; + absl::StrAppend(&res.output, metric_to_fifo.first, "=", + data_pt.get_value(), data_pt.get_metric().unit(), ";"); + + // all other metric value (warning_lt, critical_gt, min... are stored in + // exemplars) + detail::perf_data to_append; + for (const auto& exemplar : data_pt.get_exemplars()) { + to_append.apply_exemplar(exemplar); + } + to_append.append_to_string(&res.output); + } + metric_to_fifo.second.clean_oldest(last_time); + } + + data_point_fifo_container::clean_empty_fifos(fifos); + + return true; +} diff --git a/engine/modules/opentelemetry/src/centreon_agent/agent_config.cc b/engine/modules/opentelemetry/src/centreon_agent/agent_config.cc new file mode 100644 index 00000000000..d5cbce16780 --- /dev/null +++ b/engine/modules/opentelemetry/src/centreon_agent/agent_config.cc @@ -0,0 +1,154 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#include "com/centreon/common/rapidjson_helper.hh" + +#include "centreon_agent/agent_config.hh" + +#include "com/centreon/exceptions/msg_fmt.hh" + +using namespace com::centreon::engine::modules::opentelemetry::centreon_agent; +using namespace com::centreon::common; + +static constexpr std::string_view _config_schema(R"( +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "title": "centreon agent config", + "properties": { + "check_interval": { + "description": "interval in seconds between two checks", + "type": "integer", + "minimum": 10 + }, + "max_concurrent_checks": { + "description": "maximum of running checks at the same time", + "type": "integer", + "minimum": 1 + }, + "export_period": { + "description": "period in second of agent metric export", + "type": "integer", + "minimum": 10 + }, + "check_timeout": { + "description": "check running timeout", + "type": "integer", + "minimum": 1 + }, + "reverse_connections": { + "description": "array of agent endpoints (reverse mode, engine connects to centreon-agent) ", + "type": "array", + "items": { + "type" : "object" + } + } + }, + "type": "object" +} +)"); + +/** + * @brief Construct a new agent config::agent from json data + * + * @param json_config_v + */ +agent_config::agent_config(const rapidjson::Value& json_config_v) { + static json_validator validator(_config_schema); + + rapidjson_helper file_content(json_config_v); + + file_content.validate(validator); + + _check_interval = file_content.get_unsigned("check_interval", 60); + _max_concurrent_checks = + file_content.get_unsigned("max_concurrent_checks", 100); + _export_period = file_content.get_unsigned("export_period", 60); + _check_timeout = file_content.get_unsigned("_check_timeout", 30); + + if (file_content.has_member("reverse_connections")) { + const auto& reverse_array = file_content.get_member("reverse_connections"); + for (auto conf_iter = reverse_array.Begin(); + conf_iter != reverse_array.End(); ++conf_iter) { + _agent_grpc_reverse_conf.insert( + std::make_shared(*conf_iter)); + } + } +} + +/** + * @brief Constructor used by tests + * + * @param check_interval + * @param max_concurrent_checks + * @param export_period + * @param check_timeout + */ +agent_config::agent_config(uint32_t check_interval, + uint32_t max_concurrent_checks, + uint32_t export_period, + uint32_t check_timeout) + : _check_interval(check_interval), + _max_concurrent_checks(max_concurrent_checks), + _export_period(export_period), + _check_timeout(check_timeout) {} + +/** + * @brief Constructor used by tests + * + * @param check_interval + * @param max_concurrent_checks + * @param export_period + * @param check_timeout + * @param endpoints + */ +agent_config::agent_config( + uint32_t check_interval, + uint32_t max_concurrent_checks, + uint32_t export_period, + uint32_t check_timeout, + const std::initializer_list& endpoints) + : _agent_grpc_reverse_conf(endpoints), + _check_interval(check_interval), + _max_concurrent_checks(max_concurrent_checks), + _export_period(export_period), + _check_timeout(check_timeout) {} + +/** + * @brief equality operator + * + * @param right + * @return true + * @return false + */ +bool agent_config::operator==(const agent_config& right) const { + if (_check_interval != right._check_interval || + _max_concurrent_checks != right._max_concurrent_checks || + _export_period != right._export_period || + _check_timeout != right._check_timeout || + _agent_grpc_reverse_conf.size() != right._agent_grpc_reverse_conf.size()) + return false; + + for (auto rev_conf_left = _agent_grpc_reverse_conf.begin(), + rev_conf_right = right._agent_grpc_reverse_conf.begin(); + rev_conf_left != _agent_grpc_reverse_conf.end(); + ++rev_conf_left, ++rev_conf_right) { + if (**rev_conf_left != **rev_conf_right) + return false; + } + return true; +} diff --git a/engine/modules/opentelemetry/src/centreon_agent/agent_impl.cc b/engine/modules/opentelemetry/src/centreon_agent/agent_impl.cc new file mode 100644 index 00000000000..5db31e4c877 --- /dev/null +++ b/engine/modules/opentelemetry/src/centreon_agent/agent_impl.cc @@ -0,0 +1,446 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#include + +#include "centreon_agent/agent_impl.hh" + +#include "conf_helper.hh" +#include "otl_fmt.hh" + +#include "com/centreon/engine/command_manager.hh" + +using namespace com::centreon::engine::modules::opentelemetry::centreon_agent; + +/** + * @brief when BiReactor::OnDone is called by grpc layers, we should delete + * this. But this object is even used by others. + * So it's stored in this container and just removed from this container when + * OnDone is called + * This container is also used to push configuration changes to agent + * + * @tparam bireactor_class + */ +template +std::set>> + agent_impl::_instances; + +template +absl::Mutex agent_impl::_instances_m; + +/** + * @brief Construct a new agent impl::agent impl object + * + * @tparam bireactor_class + * @param io_context + * @param class_name + * @param handler handler that will process received metrics + * @param logger + */ +template +agent_impl::agent_impl( + const std::shared_ptr& io_context, + const std::string_view class_name, + const agent_config::pointer& conf, + const metric_handler& handler, + const std::shared_ptr& logger) + : _io_context(io_context), + _class_name(class_name), + _conf(conf), + _metric_handler(handler), + _logger(logger), + _write_pending(false), + _alive(true) { + SPDLOG_LOGGER_DEBUG(logger, "create {} this={:p}", _class_name, + static_cast(this)); +} + +/** + * @brief Destroy the agent impl::agent impl object + * + * @tparam bireactor_class + */ +template +agent_impl::~agent_impl() { + SPDLOG_LOGGER_DEBUG(_logger, "delete {} this={:p}", _class_name, + static_cast(this)); +} + +/** + * @brief just call _calc_and_send_config_if_needed in main engine thread + * + * @tparam bireactor_class + */ +template +void agent_impl::calc_and_send_config_if_needed( + const agent_config::pointer& new_conf) { + { + absl::MutexLock l(&_protect); + _conf = new_conf; + } + auto to_call = std::packaged_task( + [me = std::enable_shared_from_this>:: + shared_from_this()]() mutable -> int32_t { + // then we are in the main thread + // services, hosts and commands are stable + me->_calc_and_send_config_if_needed(); + return 0; + }); + command_manager::instance().enqueue(std::move(to_call)); +} + +/** + * @brief static method used to push new configuration to all agents + * + * @tparam bireactor_class + */ +template +void agent_impl::all_agent_calc_and_send_config_if_needed( + const agent_config::pointer& new_conf) { + absl::MutexLock l(&_instances_m); + for (auto& instance : _instances) { + instance->calc_and_send_config_if_needed(new_conf); + } +} + +static bool add_command_to_agent_conf( + const std::string& cmd_name, + const std::string& cmd_line, + const std::string& service, + com::centreon::agent::AgentConfiguration* cnf, + const std::shared_ptr& logger, + const std::string& peer) { + std::string plugins_cmdline = boost::trim_copy(cmd_line); + + if (plugins_cmdline.empty()) { + SPDLOG_LOGGER_ERROR( + logger, + "no add command: agent: {} serv: {}, no plugins cmd_line found in {}", + peer, service, cmd_line); + return false; + } + + SPDLOG_LOGGER_TRACE( + logger, "add command to agent: {}, serv: {}, cmd {} plugins cmd_line {}", + peer, service, cmd_name, cmd_line); + + com::centreon::agent::Service* serv = cnf->add_services(); + serv->set_service_description(service); + serv->set_command_name(cmd_name); + serv->set_command_line(plugins_cmdline); + + return true; +} + +/** + * @brief this function must be called in the engine main thread + * It calculates agent configuration, if different to the older, it sends it to + * agent + * + * @tparam bireactor_class + */ +template +void agent_impl::_calc_and_send_config_if_needed() { + std::shared_ptr new_conf = + std::make_shared(); + { + agent::AgentConfiguration* cnf = new_conf->mutable_config(); + cnf->set_check_interval(_conf->get_check_interval()); + cnf->set_check_timeout(_conf->get_check_timeout()); + cnf->set_export_period(_conf->get_export_period()); + cnf->set_max_concurrent_checks(_conf->get_max_concurrent_checks()); + cnf->set_use_exemplar(true); + absl::MutexLock l(&_protect); + if (!_alive) { + return; + } + if (_agent_info) { + const std::string& peer = get_peer(); + bool at_least_one_command_found = get_otel_commands( + _agent_info->init().host(), + [cnf, &peer](const std::string& cmd_name, const std::string& cmd_line, + const std::string& service, + const std::shared_ptr& logger) { + return add_command_to_agent_conf(cmd_name, cmd_line, service, cnf, + logger, peer); + }, + _logger); + if (!at_least_one_command_found) { + SPDLOG_LOGGER_ERROR(_logger, "no command found for agent {}", + get_peer()); + } + } + if (!_last_sent_config || + !::google::protobuf::util::MessageDifferencer::Equals( + *cnf, _last_sent_config->config())) { + _last_sent_config = new_conf; + } else { + new_conf.reset(); + SPDLOG_LOGGER_DEBUG(_logger, "no need to update conf to {}", get_peer()); + } + } + if (new_conf) { + SPDLOG_LOGGER_DEBUG(_logger, "send conf to {}", get_peer()); + _write(new_conf); + } +} + +/** + * @brief manages incoming request (init or otel data) + * + * @tparam bireactor_class + * @param request + */ +template +void agent_impl::on_request( + const std::shared_ptr& request) { + agent_config::pointer agent_conf; + if (request->has_init()) { + { + absl::MutexLock l(&_protect); + _agent_info = request; + agent_conf = _conf; + _last_sent_config.reset(); + } + SPDLOG_LOGGER_DEBUG(_logger, "init from {}", get_peer()); + calc_and_send_config_if_needed(agent_conf); + } + if (request->has_otel_request()) { + metric_request_ptr received(request->unsafe_arena_release_otel_request()); + _metric_handler(received); + } +} + +/** + * @brief send request to agent + * + * @tparam bireactor_class + * @param request + */ +template +void agent_impl::_write( + const std::shared_ptr& request) { + { + absl::MutexLock l(&_protect); + if (!_alive) { + return; + } + _write_queue.push_back(request); + } + start_write(); +} + +/** + * @brief all grpc streams are stored in an static container + * + * @tparam bireactor_class + * @param strm + */ +template +void agent_impl::register_stream( + const std::shared_ptr& strm) { + absl::MutexLock l(&_instances_m); + _instances.insert(strm); +} + +/** + * @brief start an asynchronous read + * + * @tparam bireactor_class + */ +template +void agent_impl::start_read() { + absl::MutexLock l(&_protect); + if (!_alive) { + return; + } + std::shared_ptr to_read; + if (_read_current) { + return; + } + to_read = _read_current = std::make_shared(); + bireactor_class::StartRead(to_read.get()); +} + +/** + * @brief we have receive a request or an eof + * + * @tparam bireactor_class + * @param ok + */ +template +void agent_impl::OnReadDone(bool ok) { + if (ok) { + std::shared_ptr readden; + { + absl::MutexLock l(&_protect); + SPDLOG_LOGGER_TRACE(_logger, "{:p} {} receive from {}: {}", + static_cast(this), _class_name, + get_peer(), *_read_current); + readden = _read_current; + _read_current.reset(); + } + start_read(); + on_request(readden); + } else { + SPDLOG_LOGGER_ERROR(_logger, "{:p} {} fail read from {}", + static_cast(this), _class_name, get_peer()); + on_error(); + this->shutdown(); + } +} + +/** + * @brief starts an asynchronous write + * + * @tparam bireactor_class + */ +template +void agent_impl::start_write() { + std::shared_ptr to_send; + { + absl::MutexLock l(&_protect); + if (!_alive || _write_pending || _write_queue.empty()) { + return; + } + to_send = _write_queue.front(); + _write_pending = true; + } + SPDLOG_LOGGER_TRACE(_logger, "{:p} {} send to {}: {}", + static_cast(this), _class_name, get_peer(), + *to_send); + bireactor_class::StartWrite(to_send.get()); +} + +/** + * @brief write handler + * + * @tparam bireactor_class + * @param ok + */ +template +void agent_impl::OnWriteDone(bool ok) { + if (ok) { + { + absl::MutexLock l(&_protect); + _write_pending = false; + SPDLOG_LOGGER_TRACE(_logger, "{:p} {} {} sent", + static_cast(this), _class_name, + **_write_queue.begin()); + _write_queue.pop_front(); + } + start_write(); + } else { + SPDLOG_LOGGER_ERROR(_logger, "{:p} {} fail write to stream", + static_cast(this), _class_name); + on_error(); + this->shutdown(); + } +} + +/** + * @brief called when server agent connection is closed + * When grpc layers call this handler, oject must be deleted + * + * @tparam bireactor_class + */ +template +void agent_impl::OnDone() { + /**grpc has a bug, sometimes if we delete this class in this handler as it is + * described in examples, it also deletes used channel and does a pthread_join + * of the current thread witch go to a EDEADLOCK error and call grpc::Crash. + * So we uses asio thread to do the job + */ + _io_context->post([me = std::enable_shared_from_this< + agent_impl>::shared_from_this(), + logger = _logger]() { + absl::MutexLock l(&_instances_m); + SPDLOG_LOGGER_DEBUG(logger, "{:p} server::OnDone()", + static_cast(me.get())); + _instances.erase(std::static_pointer_cast>(me)); + }); +} + +/** + * @brief called when client agent connection is closed + * When grpc layers call this handler, oject must be deleted + * + * @tparam bireactor_class + * @param status status passed to Finish agent side method + */ +template +void agent_impl::OnDone(const ::grpc::Status& status) { + /**grpc has a bug, sometimes if we delete this class in this handler as it is + * described in examples, it also deletes used channel and does a + * pthread_join of the current thread witch go to a EDEADLOCK error and call + * grpc::Crash. So we uses asio thread to do the job + */ + _io_context->post([me = std::enable_shared_from_this< + agent_impl>::shared_from_this(), + status, logger = _logger]() { + absl::MutexLock l(&_instances_m); + if (status.ok()) { + SPDLOG_LOGGER_DEBUG(logger, "{:p} client::OnDone({}) {}", + static_cast(me.get()), status.error_message(), + status.error_details()); + } else { + SPDLOG_LOGGER_ERROR(logger, "{:p} client::OnDone({}) {}", + static_cast(me.get()), status.error_message(), + status.error_details()); + } + _instances.erase(std::static_pointer_cast>(me)); + }); +} + +/** + * @brief just log, must be inherited + * + * @tparam bireactor_class + */ +template +void agent_impl::shutdown() { + SPDLOG_LOGGER_DEBUG(_logger, "{:p} {}::shutdown", static_cast(this), + _class_name); +} + +/** + * @brief static method used to shutdown all connections + * + * @tparam bireactor_class + */ +template +void agent_impl::shutdown_all() { + std::set> to_shutdown; + { + absl::MutexLock l(&_instances_m); + to_shutdown = std::move(_instances); + } + for (std::shared_ptr conn : to_shutdown) { + conn->shutdown(); + } +} + +namespace com::centreon::engine::modules::opentelemetry::centreon_agent { + +template class agent_impl< + ::grpc::ClientBidiReactor>; + +template class agent_impl< + ::grpc::ServerBidiReactor>; + +} // namespace com::centreon::engine::modules::opentelemetry::centreon_agent \ No newline at end of file diff --git a/engine/modules/opentelemetry/src/centreon_agent/agent_service.cc b/engine/modules/opentelemetry/src/centreon_agent/agent_service.cc new file mode 100644 index 00000000000..8fea6fcb1bc --- /dev/null +++ b/engine/modules/opentelemetry/src/centreon_agent/agent_service.cc @@ -0,0 +1,162 @@ +/** + * Copyright 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + */ + +#include "centreon_agent/agent_service.hh" + +using namespace com::centreon::engine::modules::opentelemetry::centreon_agent; + +namespace com::centreon::engine::modules::opentelemetry::centreon_agent { + +/** + * @brief managed incoming centreon monitoring agent connection + * + */ +class server_bireactor + : public agent_impl<::grpc::ServerBidiReactor> { + const std::string _peer; + + public: + template + server_bireactor(const std::shared_ptr& io_context, + const agent_config::pointer& conf, + const otel_request_handler& handler, + const std::shared_ptr& logger, + const std::string& peer) + : agent_impl<::grpc::ServerBidiReactor>( + io_context, + "agent_server", + conf, + handler, + logger), + _peer(peer) { + SPDLOG_LOGGER_DEBUG(_logger, "connected with agent {}", _peer); + } + + const std::string& get_peer() const override { return _peer; } + + void on_error() override; + void shutdown() override; +}; + +void server_bireactor::on_error() { + shutdown(); +} + +void server_bireactor::shutdown() { + absl::MutexLock l(&_protect); + if (_alive) { + _alive = false; + agent_impl<::grpc::ServerBidiReactor>::shutdown(); + Finish(::grpc::Status::CANCELLED); + SPDLOG_LOGGER_DEBUG(_logger, "end of agent connection with {}", _peer); + } +} + +} // namespace com::centreon::engine::modules::opentelemetry::centreon_agent + +/** + * @brief Construct a new agent service::agent service object + * don't use it, use agent_service::load instead + * + * @param io_context + * @param handler + * @param logger + */ +agent_service::agent_service( + const std::shared_ptr& io_context, + const agent_config::pointer& conf, + const metric_handler& handler, + const std::shared_ptr& logger) + : _io_context(io_context), + _conf(conf), + _metric_handler(handler), + _logger(logger) { + if (!_conf) { + _conf = std::make_shared(60, 100, 10, 30); + SPDLOG_LOGGER_INFO(logger, + "no centreon_agent configuration given => we use a " + "default configuration "); + } +} + +/** + * @brief prefered way to construct an agent_service + * + * @param io_context + * @param handler + * @param logger + * @return std::shared_ptr + */ +std::shared_ptr agent_service::load( + const std::shared_ptr& io_context, + const agent_config::pointer& conf, + const metric_handler& handler, + const std::shared_ptr& logger) { + std::shared_ptr ret = std::make_shared( + io_context, conf, std::move(handler), logger); + ret->init(); + return ret; +} + +/** + * @brief to call after construction + * + */ +void agent_service::init() { + ::grpc::Service::MarkMethodCallback( + 0, new ::grpc::internal::CallbackBidiHandler< + com::centreon::agent::MessageFromAgent, + com::centreon::agent::MessageToAgent>( + [me = shared_from_this()](::grpc::CallbackServerContext* context) { + return me->Export(context); + })); +} + +/** + * @brief called by grpc layer on each incoming connection + * + * @param context + * @return ::grpc::ServerBidiReactor* + */ +::grpc::ServerBidiReactor* +agent_service::Export(::grpc::CallbackServerContext* context) { + std::shared_ptr new_reactor; + { + absl::MutexLock l(&_conf_m); + new_reactor = std::make_shared( + _io_context, _conf, _metric_handler, _logger, context->peer()); + } + server_bireactor::register_stream(new_reactor); + new_reactor->start_read(); + + return new_reactor.get(); +} + +void agent_service::shutdown_all_accepted() { + server_bireactor::shutdown_all(); +} + +void agent_service::update(const agent_config::pointer& conf) { + absl::MutexLock l(&_conf_m); + _conf = conf; +} diff --git a/engine/modules/opentelemetry/src/host_serv_extractor.cc b/engine/modules/opentelemetry/src/host_serv_extractor.cc index bbb26cdb215..6a9ed8506ad 100644 --- a/engine/modules/opentelemetry/src/host_serv_extractor.cc +++ b/engine/modules/opentelemetry/src/host_serv_extractor.cc @@ -87,17 +87,26 @@ host_serv_attributes_extractor::host_serv_attributes_extractor( [](po::options_description& desc) { desc.add_options()( "host_path", po::value(), - "where to find host name. Example: " - "resourceMetrics.scopeMetrics.metrics.dataPoints.attributes.host"); - desc.add_options()("service_path", po::value(), - "where to find service description. Example: " - "resourceMetrics.scopeMetrics.metrics.dataPoints." - "attributes.service"); + "where to find host name. Example:\n" + "resource_metrics.scopeMetrics.metrics.dataPoints.attributes.host\n" + "or\n" + "resource_metrics.resource.attributes.host\n" + "or\n" + "resource_metrics.scope_metrics.scope.attributes.host"); + desc.add_options()( + "service_path", po::value(), + "where to find service description. Example:\n" + "resource_metrics.scope_metrics.data.data_points.attributes." + "service\n" + "or\n" + "resource_metrics.resource.attributes.service\n" + "or\n" + "resource_metrics.scope_metrics.scope.attributes.service"); }); static auto parse_path = [](const std::string& path, attribute_owner& attr, std::string& key) { - static re2::RE2 path_extractor("\\.(\\w+)\\.attributes\\.(\\w+)"); + static re2::RE2 path_extractor("(?i)\\.(\\w+)\\.attributes\\.([\\.\\w]+)"); std::string sz_attr; if (!RE2::PartialMatch(path, path_extractor, &sz_attr, &key)) { throw exceptions::msg_fmt( diff --git a/engine/modules/opentelemetry/src/open_telemetry.cc b/engine/modules/opentelemetry/src/open_telemetry.cc index 34da5d8fbf8..a89910b7293 100644 --- a/engine/modules/opentelemetry/src/open_telemetry.cc +++ b/engine/modules/opentelemetry/src/open_telemetry.cc @@ -18,6 +18,7 @@ #include "com/centreon/exceptions/msg_fmt.hh" +#include "centreon_agent/agent_impl.hh" #include "com/centreon/common/http/https_connection.hh" #include "com/centreon/engine/modules/opentelemetry/open_telemetry.hh" @@ -50,8 +51,23 @@ open_telemetry::open_telemetry( void open_telemetry::_reload() { std::unique_ptr new_conf = std::make_unique(_config_file_path, *_io_context); - if (!_conf || *new_conf->get_grpc_config() != *_conf->get_grpc_config()) { - this->_create_otl_server(new_conf->get_grpc_config()); + + if (new_conf->get_grpc_config()) { + if (!_conf || !_conf->get_grpc_config() || + *new_conf->get_grpc_config() != *_conf->get_grpc_config()) { + this->_create_otl_server(new_conf->get_grpc_config(), + new_conf->get_centreon_agent_config()); + } + if (_conf && _conf->get_centreon_agent_config() && + *_conf->get_centreon_agent_config() != + *new_conf->get_centreon_agent_config()) { + _otl_server->update_agent_config(new_conf->get_centreon_agent_config()); + } + } else { // only reverse connection + std::shared_ptr to_shutdown = std::move(_otl_server); + if (to_shutdown) { + to_shutdown->shutdown(std::chrono::seconds(10)); + } } if (!new_conf->get_telegraf_conf_server_config()) { @@ -77,6 +93,16 @@ void open_telemetry::_reload() { _conf = std::move(new_conf); } + // push new configuration to connected agents + centreon_agent::agent_impl<::grpc::ServerBidiReactor>:: + all_agent_calc_and_send_config_if_needed( + _conf->get_centreon_agent_config()); + + centreon_agent::agent_impl<::grpc::ClientBidiReactor< + agent::MessageToAgent, agent::MessageFromAgent>>:: + all_agent_calc_and_send_config_if_needed( + _conf->get_centreon_agent_config()); } /** @@ -105,14 +131,15 @@ std::shared_ptr open_telemetry::load( * @param server_conf json server config */ void open_telemetry::_create_otl_server( - const grpc_config::pointer& server_conf) { + const grpc_config::pointer& server_conf, + const centreon_agent::agent_config::pointer& agent_conf) { try { std::shared_ptr to_shutdown = std::move(_otl_server); if (to_shutdown) { to_shutdown->shutdown(std::chrono::seconds(10)); } _otl_server = otl_server::load( - server_conf, + _io_context, server_conf, agent_conf, [me = shared_from_this()](const metric_request_ptr& request) { me->_on_metric(request); }, diff --git a/engine/modules/opentelemetry/src/otl_check_result_builder.cc b/engine/modules/opentelemetry/src/otl_check_result_builder.cc index e1f75423fee..517374773a5 100644 --- a/engine/modules/opentelemetry/src/otl_check_result_builder.cc +++ b/engine/modules/opentelemetry/src/otl_check_result_builder.cc @@ -21,6 +21,8 @@ #include "data_point_fifo_container.hh" #include "otl_check_result_builder.hh" + +#include "centreon_agent/agent_check_result_builder.hh" #include "telegraf/nagios_check_result_builder.hh" #include "absl/flags/commandlineflag.h" @@ -147,6 +149,11 @@ std::shared_ptr otl_check_result_builder::create( return std::make_shared( cmd_line, command_id, host, service, timeout, std::move(handler), logger); + case check_result_builder_config::converter_type:: + centreon_agent_check_result_builder: + return std::make_shared( + cmd_line, command_id, host, service, timeout, std::move(handler), + logger); default: SPDLOG_LOGGER_ERROR(logger, "unknown converter type:{}", cmd_line); throw exceptions::msg_fmt("unknown converter type:{}", cmd_line); @@ -200,6 +207,10 @@ otl_check_result_builder::create_check_result_builder_config( return std::make_shared( check_result_builder_config::converter_type:: nagios_check_result_builder); + } else if (extractor_type == "centreon_agent") { + return std::make_shared( + check_result_builder_config::converter_type:: + centreon_agent_check_result_builder); } else { throw exceptions::msg_fmt("unknown processor in {}", cmd_line); } diff --git a/engine/modules/opentelemetry/src/otl_config.cc b/engine/modules/opentelemetry/src/otl_config.cc index c36fd359f24..f0c62dda374 100644 --- a/engine/modules/opentelemetry/src/otl_config.cc +++ b/engine/modules/opentelemetry/src/otl_config.cc @@ -19,6 +19,8 @@ #include "com/centreon/common/rapidjson_helper.hh" #include "com/centreon/engine/globals.hh" +#include "centreon_agent/agent.grpc.pb.h" + #include "otl_config.hh" #include "otl_fmt.hh" @@ -62,12 +64,13 @@ static constexpr std::string_view _grpc_config_schema(R"( "telegraf_conf_server": { "description": "http(s) telegraf config server", "type": "object" + }, + "centreon_agent": { + "description": "config of centreon_agent", + "type": "object" } - }, - "required": [ - "otel_server" - ], - "type": "object" + }, + "type" : "object" } )"); @@ -97,12 +100,48 @@ otl_config::otl_config(const std::string_view& file_path, _json_grpc_log = file_content.get_bool("grpc_json_log", false); _second_fifo_expiry = file_content.get_unsigned("second_fifo_expiry", 600); _max_fifo_size = file_content.get_unsigned("max_fifo_size", 5); - _grpc_conf = - std::make_shared(file_content.get_member("otel_server")); + if (file_content.has_member("otel_server")) { + try { + _grpc_conf = + std::make_shared(file_content.get_member("otel_server")); + } catch (const std::exception& e) { + SPDLOG_LOGGER_ERROR(config_logger, + "fail to parse otl_server object: ", e.what()); + throw; + } + } + + if (file_content.has_member("centreon_agent")) { + try { + _centreon_agent_config = std::make_shared( + file_content.get_member("centreon_agent")); + } catch (const std::exception& e) { + SPDLOG_LOGGER_ERROR( + config_logger, + "fail to parse centreon agent conf server object: ", e.what()); + throw; + } + } + + // nor server nor reverse client? + if (!_grpc_conf && + !(_centreon_agent_config && + !_centreon_agent_config->get_agent_grpc_reverse_conf().empty())) { + throw exceptions::msg_fmt( + "nor an grpc server, nor a reverse client configured"); + } + if (file_content.has_member("telegraf_conf_server")) { - _telegraf_conf_server_config = - std::make_shared( - file_content.get_member("telegraf_conf_server"), io_context); + try { + _telegraf_conf_server_config = + std::make_shared( + file_content.get_member("telegraf_conf_server"), io_context); + } catch (const std::exception& e) { + SPDLOG_LOGGER_ERROR( + config_logger, + "fail to parse telegraf conf server object: ", e.what()); + throw; + } } } diff --git a/engine/modules/opentelemetry/src/otl_data_point.cc b/engine/modules/opentelemetry/src/otl_data_point.cc index 515244c92a9..7e5273725f1 100644 --- a/engine/modules/opentelemetry/src/otl_data_point.cc +++ b/engine/modules/opentelemetry/src/otl_data_point.cc @@ -21,6 +21,15 @@ using namespace com::centreon::engine::modules::opentelemetry; using namespace ::opentelemetry::proto::metrics::v1; +/** + * @brief SummaryDataPoint doesn't have Exemplars so we use it to return an + * array of exemplars in any case + * + */ +static const ::google::protobuf::RepeatedPtrField< + ::opentelemetry::proto::metrics::v1::Exemplar> + _empty_exemplars; + otl_data_point::otl_data_point( const metric_request_ptr& parent, const ::opentelemetry::proto::resource::v1::Resource& resource, @@ -33,6 +42,7 @@ otl_data_point::otl_data_point( _metric(metric), _data_point(data_pt), _data_point_attributes(data_pt.attributes()), + _exemplars(data_pt.exemplars()), _nano_timestamp(data_pt.time_unix_nano()), _type(data_point_type::number) { _value = data_pt.as_double() ? data_pt.as_double() : data_pt.as_int(); @@ -50,6 +60,7 @@ otl_data_point::otl_data_point( _metric(metric), _data_point(data_pt), _data_point_attributes(data_pt.attributes()), + _exemplars(data_pt.exemplars()), _nano_timestamp(data_pt.time_unix_nano()), _type(data_point_type::histogram) { _value = data_pt.count(); @@ -68,6 +79,7 @@ otl_data_point::otl_data_point( _metric(metric), _data_point(data_pt), _data_point_attributes(data_pt.attributes()), + _exemplars(data_pt.exemplars()), _nano_timestamp(data_pt.time_unix_nano()), _type(data_point_type::exponential_histogram) { _value = data_pt.count(); @@ -85,6 +97,7 @@ otl_data_point::otl_data_point( _metric(metric), _data_point(data_pt), _data_point_attributes(data_pt.attributes()), + _exemplars(_empty_exemplars), _nano_timestamp(data_pt.time_unix_nano()), _type(data_point_type::summary) { _value = data_pt.count(); diff --git a/engine/modules/opentelemetry/src/otl_server.cc b/engine/modules/opentelemetry/src/otl_server.cc index b6b9097df78..b502953ddb3 100644 --- a/engine/modules/opentelemetry/src/otl_server.cc +++ b/engine/modules/opentelemetry/src/otl_server.cc @@ -19,6 +19,7 @@ #include #include +#include "centreon_agent/agent.grpc.pb.h" #include "opentelemetry/proto/collector/metrics/v1/metrics_service.grpc.pb.h" #include "otl_fmt.hh" @@ -282,12 +283,19 @@ ::grpc::ServerUnaryReactor* metric_service::Export( * @param conf grpc configuration * @param handler handler that will be called on every request */ -otl_server::otl_server(const grpc_config::pointer& conf, - const metric_handler& handler, - const std::shared_ptr& logger) +otl_server::otl_server( + const std::shared_ptr& io_context, + const grpc_config::pointer& conf, + const centreon_agent::agent_config::pointer& agent_config, + const metric_handler& handler, + const std::shared_ptr& logger) : common::grpc::grpc_server_base(conf, logger), - _service(detail::metric_service::load(handler, logger)) {} + _service(detail::metric_service::load(handler, logger)), + _agent_service(centreon_agent::agent_service::load(io_context, + agent_config, + handler, + logger)) {} /** * @brief Destroy the otl server::otl server object @@ -305,10 +313,13 @@ otl_server::~otl_server() { * @return otl_server::pointer otl_server started */ otl_server::pointer otl_server::load( + const std::shared_ptr& io_context, const grpc_config::pointer& conf, + const centreon_agent::agent_config::pointer& agent_config, const metric_handler& handler, const std::shared_ptr& logger) { - otl_server::pointer ret(new otl_server(conf, handler, logger)); + otl_server::pointer ret( + new otl_server(io_context, conf, agent_config, handler, logger)); ret->start(); return ret; } @@ -320,5 +331,16 @@ otl_server::pointer otl_server::load( void otl_server::start() { _init([this](::grpc::ServerBuilder& builder) { builder.RegisterService(_service.get()); + builder.RegisterService(_agent_service.get()); }); } + +/** + * @brief update conf used by service to create + * + * @param agent_config + */ +void otl_server::update_agent_config( + const centreon_agent::agent_config::pointer& agent_config) { + _agent_service->update(agent_config); +} diff --git a/engine/precomp_inc/precomp.hh b/engine/precomp_inc/precomp.hh index 852545a1567..0d306a733b3 100644 --- a/engine/precomp_inc/precomp.hh +++ b/engine/precomp_inc/precomp.hh @@ -62,6 +62,7 @@ #include #include +#include #include #include #include diff --git a/engine/src/configuration/applier/state.cc b/engine/src/configuration/applier/state.cc index 0111a51dcb4..15453d1912e 100644 --- a/engine/src/configuration/applier/state.cc +++ b/engine/src/configuration/applier/state.cc @@ -377,6 +377,7 @@ void applier::state::_apply(configuration::state const& new_cfg, config->log_level_downtimes(new_cfg.log_level_downtimes()); config->log_level_comments(new_cfg.log_level_comments()); config->log_level_macros(new_cfg.log_level_macros()); + config->log_level_otl(new_cfg.log_level_otl()); config->use_true_regexp_matching(new_cfg.use_true_regexp_matching()); config->use_send_recovery_notifications_anyways( new_cfg.use_send_recovery_notifications_anyways()); @@ -1084,10 +1085,10 @@ void applier::state::apply_log_config(configuration::state& new_cfg) { broker_sink->set_level(spdlog::level::info); log_cfg.add_custom_sink(broker_sink); - log_cfg.apply_custom_sinks({"functions", "config", "events", "checks", - "notifications", "eventbroker", - "external_command", "commands", "downtimes", - "comments", "macros", "process", "runtime"}); + log_cfg.apply_custom_sinks( + {"functions", "config", "events", "checks", "notifications", + "eventbroker", "external_command", "commands", "downtimes", "comments", + "macros", "process", "runtime", "otl"}); log_cfg.set_level("functions", new_cfg.log_level_functions()); log_cfg.set_level("config", new_cfg.log_level_config()); log_cfg.set_level("events", new_cfg.log_level_events()); @@ -1101,6 +1102,7 @@ void applier::state::apply_log_config(configuration::state& new_cfg) { log_cfg.set_level("macros", new_cfg.log_level_macros()); log_cfg.set_level("process", new_cfg.log_level_process()); log_cfg.set_level("runtime", new_cfg.log_level_runtime()); + log_cfg.set_level("otel", new_cfg.log_level_otl()); if (has_already_been_loaded) log_cfg.allow_only_atomic_changes(true); log_v2::instance().apply(log_cfg); diff --git a/engine/tests/CMakeLists.txt b/engine/tests/CMakeLists.txt index a464efc2e72..56d3122b9ee 100755 --- a/engine/tests/CMakeLists.txt +++ b/engine/tests/CMakeLists.txt @@ -111,6 +111,7 @@ if(WITH_TESTING) "${TESTS_DIR}/notifications/service_timeperiod_notification.cc" "${TESTS_DIR}/notifications/service_flapping_notification.cc" "${TESTS_DIR}/notifications/service_downtime_notification_test.cc" + "${TESTS_DIR}/opentelemetry/agent_check_result_builder_test.cc" "${TESTS_DIR}/opentelemetry/grpc_config_test.cc" "${TESTS_DIR}/opentelemetry/host_serv_extractor_test.cc" "${TESTS_DIR}/opentelemetry/otl_server_test.cc" @@ -156,7 +157,9 @@ if(WITH_TESTING) add_executable(ut_engine ${ut_sources}) target_include_directories(ut_engine PRIVATE ${MODULE_DIR_OTL}/src - ${CMAKE_SOURCE_DIR}/common/grpc/inc) + ${CMAKE_SOURCE_DIR}/common/grpc/inc + ${CMAKE_SOURCE_DIR}/agent/inc + ${CMAKE_SOURCE_DIR}/agent/src) target_precompile_headers(ut_engine REUSE_FROM cce_core) diff --git a/engine/tests/opentelemetry/agent_check_result_builder_test.cc b/engine/tests/opentelemetry/agent_check_result_builder_test.cc new file mode 100644 index 00000000000..1f8f0438830 --- /dev/null +++ b/engine/tests/opentelemetry/agent_check_result_builder_test.cc @@ -0,0 +1,484 @@ +/** + * Copyright 2024 Centreon + * + * This file is part of Centreon Engine. + * + * Centreon Engine is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * Centreon Engine is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Centreon Engine. If not, see + * . + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "com/centreon/engine/configuration/applier/contact.hh" +#include "com/centreon/engine/configuration/applier/host.hh" +#include "com/centreon/engine/configuration/applier/service.hh" +#include "common/engine_legacy_conf/host.hh" +#include "common/engine_legacy_conf/service.hh" + +#include "opentelemetry/proto/collector/metrics/v1/metrics_service.pb.h" +#include "opentelemetry/proto/common/v1/common.pb.h" +#include "opentelemetry/proto/metrics/v1/metrics.pb.h" + +#include "com/centreon/engine/modules/opentelemetry/data_point_fifo_container.hh" + +#include "com/centreon/engine/modules/opentelemetry/otl_check_result_builder.hh" + +#include "com/centreon/engine/modules/opentelemetry/centreon_agent/agent_check_result_builder.hh" + +#include "helper.hh" +#include "test_engine.hh" + +using namespace com::centreon::engine::modules::opentelemetry; +using namespace com::centreon::engine; + +static const char* agent_exemple = R"( +{ + "resourceMetrics": [ + { + "resource": { + "attributes": [ + { + "key": "host.name", + "value": { + "stringValue": "test_host" + } + }, + { + "key": "service.name", + "value": { + "stringValue": "" + } + } + ] + }, + "scopeMetrics": [ + { + "metrics": [ + { + "name": "status", + "description": "0", + "gauge": { + "dataPoints": [ + { + "timeUnixNano": "1718345061146529731", + "asInt": "0" + } + ] + } + } + ] + } + ] + }, + { + "resource": { + "attributes": [ + { + "key": "host.name", + "value": { + "stringValue": "test_host" + } + }, + { + "key": "service.name", + "value": { + "stringValue": "test_svc_builder" + } + } + ] + }, + "scopeMetrics": [ + { + "metrics": [ + { + "name": "status", + "description": "output of plugin", + "gauge": { + "dataPoints": [ + { + "timeUnixNano": "1718345061381922153", + "asInt": "0" + } + ] + } + }, + { + "name": "metric", + "gauge": { + "dataPoints": [ + { + "timeUnixNano": "1718345061381922153", + "exemplars": [ + { + "asDouble": 75, + "filteredAttributes": [ + { + "key": "crit_gt" + } + ] + }, + { + "asDouble": 0, + "filteredAttributes": [ + { + "key": "crit_lt" + } + ] + }, + { + "asDouble": 50, + "filteredAttributes": [ + { + "key": "warn_gt" + } + ] + }, + { + "asDouble": 0, + "filteredAttributes": [ + { + "key": "warn_lt" + } + ] + } + ], + "asInt": "12" + } + ] + } + }, + { + "name": "metric2", + "unit": "ms", + "gauge": { + "dataPoints": [ + { + "timeUnixNano": "1718345061381922153", + "exemplars": [ + { + "asDouble": 80, + "filteredAttributes": [ + { + "key": "crit_gt" + } + ] + }, + { + "asDouble": 75, + "filteredAttributes": [ + { + "key": "crit_lt" + } + ] + }, + { + "asDouble": 75, + "filteredAttributes": [ + { + "key": "warn_gt" + } + ] + }, + { + "asDouble": 50, + "filteredAttributes": [ + { + "key": "warn_lt" + } + ] + }, + { + "asDouble": 0, + "filteredAttributes": [ + { + "key": "min" + } + ] + }, + { + "asDouble": 100, + "filteredAttributes": [ + { + "key": "max" + } + ] + } + ], + "asInt": "30" + } + ] + } + } + ] + } + ] + }, + { + "resource": { + "attributes": [ + { + "key": "host.name", + "value": { + "stringValue": "test_host" + } + }, + { + "key": "service.name", + "value": { + "stringValue": "test_svc_builder_2" + } + } + ] + }, + "scopeMetrics": [ + { + "metrics": [ + { + "name": "status", + "description": "output taratata", + "gauge": { + "dataPoints": [ + { + "timeUnixNano": "1718345061713456225", + "asInt": "0" + } + ] + } + }, + { + "name": "metric", + "gauge": { + "dataPoints": [ + { + "timeUnixNano": "1718345061713456225", + "exemplars": [ + { + "asDouble": 75, + "filteredAttributes": [ + { + "key": "crit_ge" + } + ] + }, + { + "asDouble": 50, + "filteredAttributes": [ + { + "key": "warn_ge" + } + ] + }, + { + "asDouble": 0, + "filteredAttributes": [ + { + "key": "warn_le" + } + ] + } + ], + "asInt": "12" + } + ] + } + }, + { + "name": "metric2", + "unit": "ms", + "gauge": { + "dataPoints": [ + { + "timeUnixNano": "1718345061713456225", + "exemplars": [ + { + "asDouble": 80, + "filteredAttributes": [ + { + "key": "crit_gt" + } + ] + }, + { + "asDouble": 75, + "filteredAttributes": [ + { + "key": "crit_lt" + } + ] + }, + { + "asDouble": 75, + "filteredAttributes": [ + { + "key": "warn_gt" + } + ] + }, + { + "asDouble": 0, + "filteredAttributes": [ + { + "key": "min" + } + ] + }, + { + "asDouble": 100, + "filteredAttributes": [ + { + "key": "max" + } + ] + } + ], + "asInt": "30" + } + ] + } + } + ] + } + ] + } + ] +} +)"; + +class otl_agent_check_result_builder_test : public TestEngine { + protected: + std::shared_ptr _builder_config; + data_point_fifo_container _fifos; + + public: + otl_agent_check_result_builder_test() { + if (service::services.find({"test_host", "test_svc_builder_2"}) == + service::services.end()) { + init_config_state(); + config->contacts().clear(); + configuration::error_cnt err; + + configuration::applier::contact ct_aply; + configuration::contact ctct{new_configuration_contact("admin", true)}; + ct_aply.add_object(ctct); + ct_aply.expand_objects(*config); + ct_aply.resolve_object(ctct, err); + + configuration::host hst{ + new_configuration_host("test_host", "admin", 457)}; + configuration::applier::host hst_aply; + hst_aply.add_object(hst); + + configuration::service svc{new_configuration_service( + "test_host", "test_svc_builder", "admin", 458)}; + configuration::applier::service svc_aply; + svc_aply.add_object(svc); + configuration::service svc2{new_configuration_service( + "test_host", "test_svc_builder_2", "admin", 459)}; + svc_aply.add_object(svc2); + + hst_aply.resolve_object(hst, err); + svc_aply.resolve_object(svc, err); + svc_aply.resolve_object(svc2, err); + } + + _builder_config = + otl_check_result_builder::create_check_result_builder_config( + "--processor=centreon_agent"); + + metric_request_ptr request = + std::make_shared< ::opentelemetry::proto::collector::metrics::v1:: + ExportMetricsServiceRequest>(); + + ::google::protobuf::util::JsonStringToMessage(agent_exemple, request.get()); + + otl_data_point::extract_data_points( + request, [&](const otl_data_point& data_pt) { + std::string service_name; + for (const auto attrib : data_pt.get_resource().attributes()) { + if (attrib.key() == "service.name") { + service_name = attrib.value().string_value(); + break; + } + } + _fifos.add_data_point("test_host", service_name, + data_pt.get_metric().name(), data_pt); + }); + } +}; + +TEST_F(otl_agent_check_result_builder_test, test_svc_builder) { + auto check_result_builder = otl_check_result_builder::create( + "", _builder_config, 1789, *host::hosts.find("test_host")->second, + service::services.find({"test_host", "test_svc_builder"})->second.get(), + std::chrono::system_clock::time_point(), [&](const commands::result&) {}, + spdlog::default_logger()); + + commands::result res; + bool success = + check_result_builder->sync_build_result_from_metrics(_fifos, res); + + ASSERT_TRUE(success); + ASSERT_EQ(res.exit_code, 0); + ASSERT_EQ(res.exit_status, com::centreon::process::normal); + ASSERT_EQ(res.command_id, 1789); + ASSERT_EQ(res.start_time.to_useconds(), 1718345061381922153 / 1000); + ASSERT_EQ(res.end_time.to_useconds(), 1718345061381922153 / 1000); + + auto compare_to_excepted = [](const std::string& to_cmp) -> bool { + return to_cmp == + "output of plugin| metric=12;0:50;0:75;; " + "metric2=30ms;50:75;75:80;0;100" || + to_cmp == + "output of plugin| metric2=30ms;50:75;75:80;0;100 " + "metric=12;0:50;0:75;;"; + }; + + ASSERT_PRED1(compare_to_excepted, res.output); +} + +TEST_F(otl_agent_check_result_builder_test, test_svc_builder_2) { + auto check_result_builder = otl_check_result_builder::create( + "", _builder_config, 1789, *host::hosts.find("test_host")->second, + service::services.find({"test_host", "test_svc_builder_2"})->second.get(), + std::chrono::system_clock::time_point(), [&](const commands::result&) {}, + spdlog::default_logger()); + + commands::result res; + bool success = + check_result_builder->sync_build_result_from_metrics(_fifos, res); + + ASSERT_TRUE(success); + ASSERT_EQ(res.exit_code, 0); + ASSERT_EQ(res.exit_status, com::centreon::process::normal); + ASSERT_EQ(res.command_id, 1789); + ASSERT_EQ(res.start_time.to_useconds(), 1718345061713456225 / 1000); + ASSERT_EQ(res.end_time.to_useconds(), 1718345061713456225 / 1000); + + auto compare_to_excepted = [](const std::string& to_cmp) -> bool { + return to_cmp == + "output taratata| metric=12;@0:50;@~:75;; " + "metric2=30ms;~:75;75:80;0;100" || + to_cmp == + "output taratata| metric2=30ms;~:75;75:80;0;100 " + "metric=12;@0:50;@~:75;;"; + }; + + ASSERT_PRED1(compare_to_excepted, res.output); +} \ No newline at end of file diff --git a/engine/tests/opentelemetry/open_telemetry_test.cc b/engine/tests/opentelemetry/open_telemetry_test.cc index 2286fe34964..469de553274 100644 --- a/engine/tests/opentelemetry/open_telemetry_test.cc +++ b/engine/tests/opentelemetry/open_telemetry_test.cc @@ -60,7 +60,9 @@ extern std::shared_ptr g_io_context; class open_telemetry : public com::centreon::engine::modules::opentelemetry::open_telemetry { protected: - void _create_otl_server(const grpc_config::pointer& server_conf) override {} + void _create_otl_server( + const grpc_config::pointer& server_conf, + const centreon_agent::agent_config::pointer&) override {} public: open_telemetry(const std::string_view config_file_path, diff --git a/engine/tests/opentelemetry/otl_converter_test.cc b/engine/tests/opentelemetry/otl_converter_test.cc index 8f7d8c36df4..d8f4265f499 100644 --- a/engine/tests/opentelemetry/otl_converter_test.cc +++ b/engine/tests/opentelemetry/otl_converter_test.cc @@ -55,6 +55,12 @@ class otl_converter_test : public TestEngine { void otl_converter_test::SetUp() { configuration::error_cnt err; init_config_state(); + timeperiod::timeperiods.clear(); + contact::contacts.clear(); + host::hosts.clear(); + host::hosts_by_id.clear(); + service::services.clear(); + service::services_by_id.clear(); config->contacts().clear(); configuration::applier::contact ct_aply; configuration::contact ctct{new_configuration_contact("admin", true)}; diff --git a/engine/tests/opentelemetry/otl_server_test.cc b/engine/tests/opentelemetry/otl_server_test.cc index 8c99d849c64..5d6291a6cc3 100644 --- a/engine/tests/opentelemetry/otl_server_test.cc +++ b/engine/tests/opentelemetry/otl_server_test.cc @@ -32,6 +32,8 @@ using namespace com::centreon::engine::modules::opentelemetry; using namespace ::opentelemetry::proto::collector::metrics::v1; +extern std::shared_ptr g_io_context; + class otl_client { std::shared_ptr<::grpc::Channel> _channel; std::unique_ptr _stub; @@ -81,18 +83,18 @@ class otl_server_test : public ::testing::Test { template void start_server(const grpc_config::pointer& conf, const metric_handler_type& handler) { - _server = otl_server::load(conf, handler, spdlog::default_logger()); + std::shared_ptr agent_conf = + std::make_shared(60, 100, 60, 10); + _server = otl_server::load(g_io_context, conf, agent_conf, handler, + spdlog::default_logger()); } }; TEST_F(otl_server_test, unsecure_client_server) { grpc_config::pointer serv_conf = std::make_shared("127.0.0.1:6789", false); - std::shared_ptr received; - auto handler = - [&](const std::shared_ptr& request) { - received = request; - }; + metric_request_ptr received; + auto handler = [&](const metric_request_ptr& request) { received = request; }; start_server(serv_conf, handler); otl_client client("127.0.0.1:6789"); diff --git a/engine/tests/test_engine.cc b/engine/tests/test_engine.cc index 1c24630e8b0..2528e488033 100644 --- a/engine/tests/test_engine.cc +++ b/engine/tests/test_engine.cc @@ -132,7 +132,8 @@ TestEngine::new_configuration_servicedependency( configuration::host TestEngine::new_configuration_host( const std::string& hostname, const std::string& contacts, - uint64_t hst_id) { + uint64_t hst_id, + const std::string_view& connector) { configuration::host hst; hst.parse("host_name", hostname.c_str()); hst.parse("address", "127.0.0.1"); @@ -140,7 +141,10 @@ configuration::host TestEngine::new_configuration_host( hst.parse("contacts", contacts.c_str()); configuration::command cmd("hcmd"); - cmd.parse("command_line", "echo 0"); + cmd.parse("command_line", "/bin/echo 0"); + if (!connector.empty()) { + cmd.parse("connector", connector.data()); + } hst.parse("check_command", "hcmd"); configuration::applier::command cmd_aply; cmd_aply.add_object(cmd); @@ -169,7 +173,8 @@ configuration::service TestEngine::new_configuration_service( const std::string& hostname, const std::string& description, const std::string& contacts, - uint64_t svc_id) { + uint64_t svc_id, + const std::string_view& connector) { configuration::service svc; svc.parse("host_name", hostname.c_str()); svc.parse("description", description.c_str()); @@ -187,9 +192,14 @@ configuration::service TestEngine::new_configuration_service( else svc.set_host_id(12); - configuration::command cmd("cmd"); - cmd.parse("command_line", "echo 'output| metric=$ARG1$;50;75'"); - svc.parse("check_command", "cmd!12"); + configuration::command cmd(fmt::format("cmd_serv_{}", svc_id)); + cmd.parse("command_line", + "/bin/echo -n 'output| metric=$ARG1$;50;75 " + "metric2=30ms;50:75;75:80;0;100'"); + if (!connector.empty()) { + cmd.parse("connector", connector.data()); + } + svc.parse("check_command", (cmd.command_name() + "!12").c_str()); configuration::applier::command cmd_aply; cmd_aply.add_object(cmd); diff --git a/engine/tests/test_engine.hh b/engine/tests/test_engine.hh index 843cb87a4ef..3271cb8873c 100644 --- a/engine/tests/test_engine.hh +++ b/engine/tests/test_engine.hh @@ -41,14 +41,17 @@ class TestEngine : public ::testing::Test { std::string const& name, bool full, const std::string& notif = "a") const; - configuration::host new_configuration_host(std::string const& hostname, - std::string const& contacts, - uint64_t hst_id = 12); + configuration::host new_configuration_host( + std::string const& hostname, + std::string const& contacts, + uint64_t hst_id = 12, + const std::string_view& connector = ""); configuration::service new_configuration_service( std::string const& hostname, std::string const& description, std::string const& contacts, - uint64_t svc_id = 13); + uint64_t svc_id = 13, + const std::string_view& connector = ""); configuration::anomalydetection new_configuration_anomalydetection( std::string const& hostname, std::string const& description, From 124fe9e62bb6bb04b7ba86b1687712c5e1970b6c Mon Sep 17 00:00:00 2001 From: pkippes Date: Thu, 4 Jul 2024 09:34:59 +0200 Subject: [PATCH 60/60] Empty-Commit