diff --git a/.github/actions/release/action.yml b/.github/actions/release/action.yml index 1848c030357..c1da256ea6f 100644 --- a/.github/actions/release/action.yml +++ b/.github/actions/release/action.yml @@ -1,9 +1,19 @@ name: "tag version" description: "Tag package" inputs: - jira_token: + jira_api_token: description: "Token to authenticate to Jira" required: true + jira_user_email: + description: "Email linked to token" + required: true + jira_project_id: + description: "Jira project id to create release" + required: true + jira_base_url: + description: "Jira base url" + required: true + runs: using: "composite" steps: @@ -44,11 +54,11 @@ runs: TYPE=Release fi - VERSION_DATA="{\"archived\":false,\"releaseDate\":\"$(date +%Y-%m-%d)\",\"name\":\"centreon-collect-$NEW_VERSION\",\"description\":\"$TYPE:$RELEASE_ID\",\"projectId\":11789,\"released\":false}" + VERSION_DATA="{\"archived\":false,\"releaseDate\":\"$(date +%Y-%m-%d)\",\"name\":\"centreon-collect-$NEW_VERSION\",\"description\":\"$TYPE:$RELEASE_ID\",\"projectId\":${{ inputs.jira_project_id }},\"released\":false}" curl --fail --request POST \ - --url 'https://centreon.atlassian.net/rest/api/3/version' \ - --header 'Authorization: Basic ${{ inputs.jira_token }}' \ + --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' \ --data ''$VERSION_DATA'' diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 3db635e65a3..6eeff4da184 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -3,7 +3,7 @@ updates: - package-ecosystem: github-actions directory: '/' schedule: - interval: weekly + interval: monthly open-pull-requests-limit: 10 labels: - 'dependencies' diff --git a/.github/workflows/release-collect.yml b/.github/workflows/release-collect.yml index 730286513ec..ed2cecbf068 100644 --- a/.github/workflows/release-collect.yml +++ b/.github/workflows/release-collect.yml @@ -10,6 +10,8 @@ on: - "[2-9][0-9].[0-9][0-9].x" paths: - "centreon-collect/**" + - "!centreon-collect/ci/**" + - "!centreon-collect/tests/**" workflow_dispatch: env: @@ -29,4 +31,7 @@ jobs: id: release uses: ./.github/actions/release with: - jira_token: ${{ secrets.JIRA_TOKEN }} + jira_user_email: ${{ secrets.XRAY_JIRA_USER_EMAIL }} + jira_api_token: ${{ secrets.XRAY_JIRA_TOKEN }} + jira_project_id: ${{ secrets.JIRA_PROJECT_ID }} + jira_base_url: ${{ secrets.JIRA_BASE_URL }} diff --git a/.github/workflows/veracode-analysis.yml b/.github/workflows/veracode-analysis.yml index 18d81598138..86c8f4cd936 100644 --- a/.github/workflows/veracode-analysis.yml +++ b/.github/workflows/veracode-analysis.yml @@ -37,12 +37,15 @@ jobs: - name: Set routing mode id: routing-mode run: | - CHECK_BRANCH=`echo "${{ github.ref_name }}" | cut -d'/' -f2` - if [[ $CHECK_BRANCH != "merge" && '${{ github.event_name }}' != 'pull_request' ]]; then - DEVELOPMENT_STAGE="Release" - else - DEVELOPMENT_STAGE="Development" - fi + DEVELOPMENT_STAGE="Development" + + ALLOWED_BRANCHES=(develop master dev-${{ inputs.major_version }}.x ${{ inputs.major_version }}.x) + for BRANCH in "${ALLOWED_BRANCHES[@]}"; do + if [[ "${{ github.ref_name }}" == "$BRANCH" ]] && [[ '${{ github.event_name }}' != 'pull_request' ]]; then + DEVELOPMENT_STAGE="Release" + fi + done + echo "development_stage=$DEVELOPMENT_STAGE" >> $GITHUB_OUTPUT cat $GITHUB_OUTPUT @@ -134,13 +137,15 @@ jobs: path: "${{ inputs.module_name }}-${{ github.sha }}-${{ github.run_id }}-veracode-binary.tar.gz" key: "${{ inputs.module_name }}-${{ github.sha }}-${{ github.run_id }}-veracode-binary" - sandbox-scan: + policy-scan: name: Sandbox scan - needs: [build] + needs: [routing, build] + if: needs.routing.outputs.development_stage != 'Development' runs-on: ubuntu-latest steps: - name: Promote latest scan + # only develop will be promoted to policy scan if: github.ref_name == 'develop' env: VERACODE_API_ID: "${{ secrets.veracode_api_id }}" @@ -148,7 +153,7 @@ jobs: # Action forked as API calls hardcoded '.com' route uses: sc979/veracode-sandboxes-helper@cf67241c27cbe6405ad8705111121ece9a48c4ff # v0.2 - # Promote should not fail if sandbox was not found. + # Promote should not fail to trigger following sandbox scan. continue-on-error: true with: activity: "promote-latest-scan" diff --git a/.gitignore b/.gitignore index e19c09d631c..c8f77542641 100644 --- a/.gitignore +++ b/.gitignore @@ -84,6 +84,9 @@ broker/libroker.a broker/librokerbase.a broker/test/python/*.crt broker/test/python/*.key +broker/compile_commands.json +broker/grpc/grpc_stream.proto +broker/grpc/src/grpc_bridge.cc # clib clib/inc/com/centreon/clib/version.hh diff --git a/CMakeLists.txt b/CMakeLists.txt index ddd289280c8..2538bc52a20 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -116,7 +116,7 @@ endif() # Version. set(COLLECT_MAJOR 23) set(COLLECT_MINOR 04) -set(COLLECT_PATCH 8) +set(COLLECT_PATCH 9) set(COLLECT_VERSION "${COLLECT_MAJOR}.${COLLECT_MINOR}.${COLLECT_PATCH}") add_definitions(-DCENTREON_CONNECTOR_VERSION=\"${COLLECT_VERSION}\") diff --git a/bbdo/CMakeLists.txt b/bbdo/CMakeLists.txt index a5170b3873d..6163c0bbc0e 100644 --- a/bbdo/CMakeLists.txt +++ b/bbdo/CMakeLists.txt @@ -17,15 +17,16 @@ # set(protobuf_files - header - rebuild_message - remove_graph_message - severity - tag - bbdo - neb - storage - bam) + header + rebuild_message + remove_graph_message + severity + tag + bbdo + neb + storage + bam + bam_state) foreach(name IN LISTS protobuf_files) set(proto_file "${name}.proto") @@ -69,8 +70,8 @@ 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) -add_dependencies(pb_bam_lib target_bam target_header) +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) macro(get_protobuf_files name) diff --git a/bbdo/bam.proto b/bbdo/bam.proto index bdd45567846..e41bf092204 100644 --- a/bbdo/bam.proto +++ b/bbdo/bam.proto @@ -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 + */ syntax = "proto3"; @@ -23,16 +23,16 @@ import "header.proto"; package com.centreon.broker; enum State { - OK = 0; - WARNING = 1; - CRITICAL = 2; - UNKNOWN = 3; + OK = 0; + WARNING = 1; + CRITICAL = 2; + UNKNOWN = 3; } message InheritedDowntime { - BBDOHeader header = 1; - uint32 ba_id = 2; - bool in_downtime = 3; + BBDOHeader header = 1; + uint32 ba_id = 2; + bool in_downtime = 3; } message BaStatus { @@ -47,111 +47,111 @@ message BaStatus { } message BaEvent { - uint32 ba_id = 1; - double first_level = 2; - int64 end_time = 3; - bool in_downtime = 4; - uint64 start_time = 5; - State status = 6; + uint32 ba_id = 1; + double first_level = 2; + int64 end_time = 3; + bool in_downtime = 4; + uint64 start_time = 5; + State status = 6; } message KpiEvent { - uint32 ba_id = 1; - uint64 start_time = 2; - int64 end_time = 3; - uint32 kpi_id = 4; - int32 impact_level = 5; - bool in_downtime = 6; - string output = 7; - string perfdata = 8; - State status = 9; + uint32 ba_id = 1; + uint64 start_time = 2; + int64 end_time = 3; + uint32 kpi_id = 4; + int32 impact_level = 5; + bool in_downtime = 6; + string output = 7; + string perfdata = 8; + State status = 9; } message DimensionBvEvent { - uint32 bv_id = 1; - string bv_name = 2; - string bv_description = 3; + uint32 bv_id = 1; + string bv_name = 2; + string bv_description = 3; } message DimensionBaBvRelationEvent { - uint32 ba_id = 1; - uint32 bv_id = 2; + uint32 ba_id = 1; + uint32 bv_id = 2; } message DimensionTimeperiod { - uint32 id = 1; - string name = 2; - string monday = 3; - string tuesday = 4; - string wednesday = 5; - string thursday = 6; - string friday = 7; - string saturday = 8; - string sunday = 9; + uint32 id = 1; + string name = 2; + string monday = 3; + string tuesday = 4; + string wednesday = 5; + string thursday = 6; + string friday = 7; + string saturday = 8; + string sunday = 9; } message DimensionBaEvent { - uint32 ba_id = 1; - string ba_name = 2; - string ba_description = 3; - double sla_month_percent_crit = 4; - double sla_month_percent_warn = 5; - uint32 sla_duration_crit = 6; - uint32 sla_duration_warn = 7; + uint32 ba_id = 1; + string ba_name = 2; + string ba_description = 3; + double sla_month_percent_crit = 4; + double sla_month_percent_warn = 5; + uint32 sla_duration_crit = 6; + uint32 sla_duration_warn = 7; } message DimensionKpiEvent { - uint32 kpi_id = 1; - uint32 ba_id = 2; - string ba_name = 3; - uint32 host_id = 4; - string host_name = 5; - uint32 service_id = 6; - string service_description = 7; - uint32 kpi_ba_id = 8; - string kpi_ba_name = 9; - uint32 meta_service_id = 10; - string meta_service_name = 11; - uint32 boolean_id = 12; - string boolean_name = 13; - double impact_warning = 14; - double impact_critical = 15; - double impact_unknown = 16; + uint32 kpi_id = 1; + uint32 ba_id = 2; + string ba_name = 3; + uint32 host_id = 4; + string host_name = 5; + uint32 service_id = 6; + string service_description = 7; + uint32 kpi_ba_id = 8; + string kpi_ba_name = 9; + uint32 meta_service_id = 10; + string meta_service_name = 11; + uint32 boolean_id = 12; + string boolean_name = 13; + double impact_warning = 14; + double impact_critical = 15; + double impact_unknown = 16; } message KpiStatus { - uint32 kpi_id = 1; - bool in_downtime = 2; - double level_acknowledgement_hard = 3; - double level_acknowledgement_soft = 4; - double level_downtime_hard = 5; - double level_downtime_soft = 6; - double level_nominal_hard = 7; - double level_nominal_soft = 8; - State state_hard = 9; - State state_soft = 10; - int64 last_state_change = 11; - double last_impact = 12; - bool valid = 13; + uint32 kpi_id = 1; + bool in_downtime = 2; + double level_acknowledgement_hard = 3; + double level_acknowledgement_soft = 4; + double level_downtime_hard = 5; + double level_downtime_soft = 6; + double level_nominal_hard = 7; + double level_nominal_soft = 8; + State state_hard = 9; + State state_soft = 10; + int64 last_state_change = 11; + double last_impact = 12; + bool valid = 13; } message BaDurationEvent { - uint32 ba_id = 1; - int64 real_start_time = 2; - int64 end_time = 3; - int64 start_time = 4; - uint32 duration = 5; - uint32 sla_duration = 6; - uint32 timeperiod_id = 7; - bool timeperiod_is_default = 8; + uint32 ba_id = 1; + int64 real_start_time = 2; + int64 end_time = 3; + int64 start_time = 4; + uint32 duration = 5; + uint32 sla_duration = 6; + uint32 timeperiod_id = 7; + bool timeperiod_is_default = 8; } message DimensionBaTimeperiodRelation { - uint32 ba_id = 1; - uint32 timeperiod_id = 2; - bool is_default = 3; + uint32 ba_id = 1; + uint32 timeperiod_id = 2; + bool is_default = 3; } message DimensionTruncateTableSignal { - bool update_started = 1; -} \ No newline at end of file + bool update_started = 1; +} diff --git a/bbdo/bam_state.proto b/bbdo/bam_state.proto new file mode 100644 index 00000000000..19a567c4f58 --- /dev/null +++ b/bbdo/bam_state.proto @@ -0,0 +1,46 @@ +/** + * 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 + */ + +syntax = "proto3"; + +import "bam.proto"; + +package com.centreon.broker; + +/** + * @brief Stores needed information for bool_service or kpi_service. Very useful + * when broker is stopped to save the BA's states. + */ +message ServiceState { + uint64 host_id = 1; + uint64 service_id = 2; + State current_state = 3; + State last_hard_state = 4; + uint64 last_check = 5; + bool state_type = 6; + bool acknowledged = 7; +} + +/** + * @brief This message contains the living informations of the current BA's. + * Thanks to them we can recompute their states when Broker is restarted. + */ +/*io::bam, bam::de_pb_services_book_state*/ +message ServicesBookState { + repeated ServiceState service = 1; +} diff --git a/bbdo/events.hh b/bbdo/events.hh index 56a785b1e7f..94beb56973e 100644 --- a/bbdo/events.hh +++ b/bbdo/events.hh @@ -190,7 +190,8 @@ enum data_element { de_pb_kpi_status = 27, de_pb_ba_duration_event = 28, de_pb_dimension_ba_timeperiod_relation = 29, - de_pb_dimension_truncate_table_signal = 30 + de_pb_dimension_truncate_table_signal = 30, + de_pb_services_book_state = 31, }; } 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 519e56b952c..bcb10b6b2e6 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 diff --git a/broker/bam/inc/com/centreon/broker/bam/ba.hh b/broker/bam/inc/com/centreon/broker/bam/ba.hh index b24d151860c..01146e38e0b 100644 --- a/broker/bam/inc/com/centreon/broker/bam/ba.hh +++ b/broker/bam/inc/com/centreon/broker/bam/ba.hh @@ -91,11 +91,6 @@ class ba : public computable, public service_listener { double _level_hard{100.0}; double _level_soft{100.0}; - double _downtime_hard{0.0}; - double _downtime_soft{0.0}; - double _acknowledgement_hard{0.0}; - double _acknowledgement_soft{0.0}; - std::unordered_map _impacts; bool _valid{true}; configuration::ba::downtime_behaviour _dt_behaviour{ @@ -109,7 +104,8 @@ class ba : public computable, public service_listener { const impact_values& new_hard_impact, const impact_values& new_soft_impact, bool in_downtime) = 0; - std::shared_ptr _generate_ba_status(bool state_changed) const; + virtual std::shared_ptr _generate_ba_status( + bool state_changed) const = 0; std::shared_ptr _generate_virtual_service_status() const; public: 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 5449898cb4d..eb67be88e93 100644 --- a/broker/bam/inc/com/centreon/broker/bam/ba_best.hh +++ b/broker/bam/inc/com/centreon/broker/bam/ba_best.hh @@ -50,6 +50,8 @@ class ba_best : public ba { const impact_values& new_hard_impact, const impact_values& new_soft_impact, bool in_downtime) override; + std::shared_ptr _generate_ba_status( + bool state_changed) const override; public: ba_best(uint32_t id, 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 a174197c819..919cde42054 100644 --- a/broker/bam/inc/com/centreon/broker/bam/ba_impact.hh +++ b/broker/bam/inc/com/centreon/broker/bam/ba_impact.hh @@ -35,6 +35,12 @@ class kpi; * of value. */ class ba_impact : public ba { + double _downtime_hard = 0.0; + double _downtime_soft = 0.0; + + double _acknowledgement_hard = 0.0; + double _acknowledgement_soft = 0.0; + void _recompute(); protected: @@ -44,6 +50,8 @@ class ba_impact : public ba { const impact_values& new_hard_impact, const impact_values& new_soft_impact, bool in_downtime) override; + std::shared_ptr _generate_ba_status( + bool state_changed) const override; public: ba_impact(uint32_t id, 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 25be94cc278..b7e17d69814 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 @@ -41,6 +41,8 @@ class ba_ratio_number : public ba { const impact_values& new_hard_impact, const impact_values& new_soft_impact, bool in_downtime) override; + std::shared_ptr _generate_ba_status( + bool state_changed) const override; public: ba_ratio_number(uint32_t id, 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 7837c75891e..a37c5469cfd 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 @@ -41,6 +41,8 @@ class ba_ratio_percent : public ba { const impact_values& new_hard_impact, const impact_values& new_soft_impact, bool in_downtime) override; + std::shared_ptr _generate_ba_status( + bool state_changed) const override; public: ba_ratio_percent(uint32_t id, 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 06206c1b35c..ba77f57fc3e 100644 --- a/broker/bam/inc/com/centreon/broker/bam/ba_worst.hh +++ b/broker/bam/inc/com/centreon/broker/bam/ba_worst.hh @@ -50,6 +50,8 @@ class ba_worst : public ba { const impact_values& new_hard_impact, const impact_values& new_soft_impact, bool in_downtime) override; + std::shared_ptr _generate_ba_status( + bool state_changed) const override; public: ba_worst(uint32_t id, 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 0cba39906a9..985ac2d872f 100644 --- a/broker/bam/inc/com/centreon/broker/bam/bool_expression.hh +++ b/broker/bam/inc/com/centreon/broker/bam/bool_expression.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. @@ -20,9 +20,8 @@ #define CCB_BAM_BOOL_EXPRESSION_HH #include "bbdo/bam/state.hh" +#include "bbdo/bam_state.pb.h" #include "com/centreon/broker/bam/computable.hh" -#include "com/centreon/broker/io/stream.hh" -#include "com/centreon/broker/namespace.hh" #include "impact_values.hh" CCB_BEGIN() 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 9462ca65c80..3c8a4579dfa 100644 --- a/broker/bam/inc/com/centreon/broker/bam/bool_or.hh +++ b/broker/bam/inc/com/centreon/broker/bam/bool_or.hh @@ -1,20 +1,20 @@ -/* -** Copyright 2014, 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 -*/ +/** + * 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_BOOL_OR_HH #define 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 f876837a277..8652102c2fb 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. @@ -21,6 +21,7 @@ #include "com/centreon/broker/bam/bool_value.hh" #include "com/centreon/broker/bam/service_listener.hh" +#include "com/centreon/broker/bam/service_state.hh" #include "com/centreon/broker/io/stream.hh" #include "com/centreon/broker/namespace.hh" #include "com/centreon/broker/neb/internal.hh" @@ -52,6 +53,7 @@ class bool_service : public bool_value, public service_listener { bool_service& operator=(const bool_service&) = delete; uint32_t get_host_id() const; uint32_t get_service_id() const; + void service_update(const service_state& s) override; void service_update(const std::shared_ptr& status, io::stream* visitor = nullptr) override; void service_update(const std::shared_ptr& status, diff --git a/broker/bam/inc/com/centreon/broker/bam/computable.hh b/broker/bam/inc/com/centreon/broker/bam/computable.hh index bf4dcf54a20..64419b69ab0 100644 --- a/broker/bam/inc/com/centreon/broker/bam/computable.hh +++ b/broker/bam/inc/com/centreon/broker/bam/computable.hh @@ -19,7 +19,6 @@ #ifndef CCB_BAM_COMPUTABLE_HH #define CCB_BAM_COMPUTABLE_HH -#include "com/centreon/broker/io/stream.hh" #include "com/centreon/broker/namespace.hh" #include "com/centreon/broker/persistent_cache.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 4b86a76dd10..4beb2c0a382 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-2024 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -74,7 +74,8 @@ class ba { std::shared_ptr find_ba(uint32_t id) const; void visit(io::stream* visitor); void save_to_cache(persistent_cache& cache); - void load_from_cache(persistent_cache& cache); + void apply_inherited_downtime(const inherited_downtime& dwn); + void apply_inherited_downtime(const pb_inherited_downtime& dwn); }; } // namespace applier } // namespace configuration 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 7b83a7641a0..8f20a7fbb85 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 @@ -1,5 +1,5 @@ -/* - * Copyright 2014-2015 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. @@ -63,8 +63,8 @@ class state { std::unordered_map _nodes; public: - state(); - ~state(); + state() = default; + ~state() noexcept = default; state(const state&) = delete; state& operator=(state const& other) = delete; void apply(configuration::state const& my_state); diff --git a/broker/bam/inc/com/centreon/broker/bam/internal.hh b/broker/bam/inc/com/centreon/broker/bam/internal.hh index d91b3a39267..64f391eeead 100644 --- a/broker/bam/inc/com/centreon/broker/bam/internal.hh +++ b/broker/bam/inc/com/centreon/broker/bam/internal.hh @@ -20,10 +20,10 @@ #define CCB_BAM_INTERNAL_HH #include "bbdo/bam.pb.h" +#include "bbdo/bam_state.pb.h" #include "broker.pb.h" #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/io/protobuf.hh" -#include "com/centreon/broker/namespace.hh" CCB_BEGIN() @@ -76,6 +76,9 @@ using pb_dimension_truncate_table_signal = io::protobuf; +using pb_services_book_state = + io::protobuf; } // namespace bam /* We have to declare the pb_ba_info also here because we don't control the diff --git a/broker/bam/inc/com/centreon/broker/bam/kpi.hh b/broker/bam/inc/com/centreon/broker/bam/kpi.hh index ac1f2f315ad..9e18fb1f02f 100644 --- a/broker/bam/inc/com/centreon/broker/bam/kpi.hh +++ b/broker/bam/inc/com/centreon/broker/bam/kpi.hh @@ -22,7 +22,6 @@ #include "com/centreon/broker/bam/computable.hh" #include "com/centreon/broker/bam/internal.hh" #include "com/centreon/broker/io/stream.hh" -#include "com/centreon/broker/namespace.hh" #include "com/centreon/broker/timestamp.hh" CCB_BEGIN() 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 a515fc45434..a29a5c62546 100644 --- a/broker/bam/inc/com/centreon/broker/bam/kpi_ba.hh +++ b/broker/bam/inc/com/centreon/broker/bam/kpi_ba.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,7 +24,6 @@ #include "com/centreon/broker/bam/internal.hh" #include "com/centreon/broker/bam/kpi.hh" #include "com/centreon/broker/io/stream.hh" -#include "com/centreon/broker/namespace.hh" CCB_BEGIN() 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 c9b424c7c36..4402dcc1100 100644 --- a/broker/bam/inc/com/centreon/broker/bam/kpi_boolexp.hh +++ b/broker/bam/inc/com/centreon/broker/bam/kpi_boolexp.hh @@ -1,5 +1,5 @@ /* - * Copyright 2014, 202122023 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. 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 84006c1cce1..c43abbf201b 100644 --- a/broker/bam/inc/com/centreon/broker/bam/kpi_service.hh +++ b/broker/bam/inc/com/centreon/broker/bam/kpi_service.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. @@ -25,7 +25,6 @@ #include "com/centreon/broker/bam/kpi.hh" #include "com/centreon/broker/bam/service_listener.hh" #include "com/centreon/broker/io/stream.hh" -#include "com/centreon/broker/namespace.hh" #include "com/centreon/broker/timestamp.hh" CCB_BEGIN() @@ -77,6 +76,7 @@ class kpi_service : public service_listener, public kpi { void impact_soft(impact_values& impact) override; bool in_downtime() const override; bool is_acknowledged() const; + void service_update(const service_state& state) override; void service_update(std::shared_ptr const& status, io::stream* visitor = nullptr) override; void service_update(const std::shared_ptr& status, 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 1b8686ab249..0c2ea5dd0d5 100644 --- a/broker/bam/inc/com/centreon/broker/bam/service_book.hh +++ b/broker/bam/inc/com/centreon/broker/bam/service_book.hh @@ -1,26 +1,27 @@ -/* -** 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, 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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_SERVICE_BOOK_HH #define CCB_BAM_SERVICE_BOOK_HH -#include "com/centreon/broker/bam/service_listener.hh" -#include "com/centreon/broker/io/stream.hh" +#include +#include "com/centreon/broker/bam/service_state.hh" +#include "com/centreon/broker/persistent_cache.hh" CCB_BEGIN() @@ -43,9 +44,14 @@ class service_listener; * Propagate updates of services to service listeners. */ class service_book { - using multimap = - std::multimap, service_listener*>; - multimap _book; + struct service_state_listeners { + std::list listeners; + service_state state; + }; + std::unordered_map, + service_state_listeners, + absl::Hash>> + _book; public: service_book() = default; @@ -70,6 +76,8 @@ class service_book { io::stream* visitor = nullptr); void update(const std::shared_ptr& t, io::stream* visitor = nullptr); + void save_to_cache(persistent_cache& cache) const; + void apply_services_state(const ServicesBookState& state); }; } // namespace bam diff --git a/broker/bam/inc/com/centreon/broker/bam/service_listener.hh b/broker/bam/inc/com/centreon/broker/bam/service_listener.hh index 1971e2c07fb..5509bcbb6df 100644 --- a/broker/bam/inc/com/centreon/broker/bam/service_listener.hh +++ b/broker/bam/inc/com/centreon/broker/bam/service_listener.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. @@ -33,6 +33,8 @@ class service_status; } // namespace neb namespace bam { +struct service_state; + /** * @class service_listener service_listener.hh * "com/centreon/broker/bam/service_listener.hh" @@ -47,6 +49,7 @@ class service_listener { service_listener(const service_listener&) = delete; virtual ~service_listener() noexcept = default; service_listener& operator=(const service_listener&) = delete; + virtual void service_update(const service_state& s); virtual void service_update(std::shared_ptr const& status, io::stream* visitor = nullptr); virtual void service_update( diff --git a/broker/bam/inc/com/centreon/broker/bam/service_state.hh b/broker/bam/inc/com/centreon/broker/bam/service_state.hh new file mode 100644 index 00000000000..7695ad0b87d --- /dev/null +++ b/broker/bam/inc/com/centreon/broker/bam/service_state.hh @@ -0,0 +1,62 @@ +/** + * 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 CCB_BAM_SERVICE_STATE_HH +#define CCB_BAM_SERVICE_STATE_HH + +#include "bbdo/bam_state.pb.h" +#include "com/centreon/broker/bam/service_listener.hh" +#include "com/centreon/broker/neb/acknowledgement.hh" + +namespace com::centreon::broker::bam { +struct service_state { + uint64_t host_id = 0; + uint64_t service_id = 0; + State current_state = State::UNKNOWN; + State last_hard_state = State::UNKNOWN; + time_t last_check = 0; + bool state_type = false; + bool acknowledged = false; +}; +} // namespace com::centreon::broker::bam + +namespace fmt { +template <> +struct formatter { + 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::broker::bam::service_state& state, + FormatContext& ctx) const -> decltype(ctx.out()) { + return format_to(ctx.out(), + "service state on service ({},{}): current state: {}, " + "last hard state: {}, last check: {}, state type: {}, " + "acknowledged: {}", + state.host_id, state.service_id, + State_Name(state.current_state), + State_Name(state.last_hard_state), state.last_check, + state.state_type, state.acknowledged); + } +}; +} // namespace fmt + +#endif /* !CCB_BAM_SERVICE_STATE_HH */ diff --git a/broker/bam/src/availability_thread.cc b/broker/bam/src/availability_thread.cc index 44f0c5a6bf8..76fa3659188 100644 --- a/broker/bam/src/availability_thread.cc +++ b/broker/bam/src/availability_thread.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/availability_thread.hh" diff --git a/broker/bam/src/ba.cc b/broker/bam/src/ba.cc index 1c973f6450d..88f80ca4b0b 100644 --- a/broker/bam/src/ba.cc +++ b/broker/bam/src/ba.cc @@ -503,29 +503,6 @@ void ba::_compute_inherited_downtime(io::stream* visitor) { _in_downtime); } -std::shared_ptr ba::_generate_ba_status( - bool state_changed) const { - auto ret{std::make_shared()}; - BaStatus& status = ret->mut_obj(); - status.set_ba_id(get_id()); - status.set_in_downtime(in_downtime()); - if (_event) - status.set_last_state_change(_event->obj().start_time()); - else - status.set_last_state_change(get_last_kpi_update()); - status.set_level_acknowledgement(_normalize(_acknowledgement_hard)); - status.set_level_downtime(_normalize(_downtime_hard)); - status.set_level_nominal(_normalize(_level_hard)); - status.set_state(com::centreon::broker::State(get_state_hard())); - status.set_state_changed(state_changed); - SPDLOG_LOGGER_DEBUG( - log_v2::bam(), - "BAM: generating status of BA {} '{}' (state {}, in downtime {}, " - "level {})", - _id, _name, status.state(), status.in_downtime(), status.level_nominal()); - return ret; -} - std::shared_ptr ba::_generate_virtual_service_status() const { auto bbdo = config::applier::state::instance().get_bbdo_version(); if (bbdo.major_v < 3) { diff --git a/broker/bam/src/ba_best.cc b/broker/bam/src/ba_best.cc index ef52a7aa8de..0f75c6523b0 100644 --- a/broker/bam/src/ba_best.cc +++ b/broker/bam/src/ba_best.cc @@ -200,3 +200,23 @@ std::string ba_best::get_output() const { std::string ba_best::get_perfdata() const { return {}; } + +std::shared_ptr ba_best::_generate_ba_status( + bool state_changed) const { + auto ret{std::make_shared()}; + BaStatus& status = ret->mut_obj(); + status.set_ba_id(get_id()); + status.set_in_downtime(in_downtime()); + if (_event) + status.set_last_state_change(_event->obj().start_time()); + else + status.set_last_state_change(get_last_kpi_update()); + status.set_state(com::centreon::broker::State(get_state_hard())); + status.set_state_changed(state_changed); + + SPDLOG_LOGGER_DEBUG( + log_v2::bam(), + "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 c7defce961b..d916c234cde 100644 --- a/broker/bam/src/ba_impact.cc +++ b/broker/bam/src/ba_impact.cc @@ -265,3 +265,28 @@ void ba_impact::_recompute() { _apply_impact(it->first, it->second); _recompute_count = 0; } + +std::shared_ptr ba_impact::_generate_ba_status( + bool state_changed) const { + auto ret{std::make_shared()}; + BaStatus& status = ret->mut_obj(); + status.set_ba_id(get_id()); + status.set_in_downtime(in_downtime()); + if (_event) + status.set_last_state_change(_event->obj().start_time()); + else + status.set_last_state_change(get_last_kpi_update()); + status.set_level_acknowledgement(_normalize(_acknowledgement_hard)); + status.set_level_downtime(_normalize(_downtime_hard)); + status.set_level_nominal(_normalize(_level_hard)); + status.set_state(com::centreon::broker::State(get_state_hard())); + status.set_state_changed(state_changed); + + SPDLOG_LOGGER_DEBUG( + log_v2::bam(), + "BAM: generating status of impact BA {} '{}' (state {}, in downtime {}, " + "level {})", + get_id(), _name, status.state(), status.in_downtime(), + status.level_nominal()); + return ret; +} diff --git a/broker/bam/src/ba_ratio_number.cc b/broker/bam/src/ba_ratio_number.cc index 4977e563a29..dc124b71df3 100644 --- a/broker/bam/src/ba_ratio_number.cc +++ b/broker/bam/src/ba_ratio_number.cc @@ -188,3 +188,25 @@ std::string ba_ratio_number::get_perfdata() const { static_cast(_level_warning), static_cast(_level_critical), _impacts.size()); } + +std::shared_ptr ba_ratio_number::_generate_ba_status( + bool state_changed) const { + auto ret = std::make_shared(); + BaStatus& status = ret->mut_obj(); + status.set_ba_id(get_id()); + status.set_in_downtime(in_downtime()); + if (_event) + status.set_last_state_change(_event->obj().start_time()); + else + status.set_last_state_change(get_last_kpi_update()); + status.set_level_nominal(_normalize(_level_hard)); + status.set_state(com::centreon::broker::State(get_state_hard())); + status.set_state_changed(state_changed); + + SPDLOG_LOGGER_DEBUG(log_v2::bam(), + "BAM: generating status of ratio number BA {} '{}' " + "(state {}, in downtime {}, level {})", + get_id(), _name, status.state(), status.in_downtime(), + status.level_nominal()); + return ret; +} diff --git a/broker/bam/src/ba_ratio_percent.cc b/broker/bam/src/ba_ratio_percent.cc index 4c4b2e0fb37..8950cfa2b55 100644 --- a/broker/bam/src/ba_ratio_percent.cc +++ b/broker/bam/src/ba_ratio_percent.cc @@ -191,3 +191,25 @@ std::string ba_ratio_percent::get_perfdata() const { static_cast(_level_warning), static_cast(_level_critical)); } + +std::shared_ptr ba_ratio_percent::_generate_ba_status( + bool state_changed) const { + auto ret{std::make_shared()}; + BaStatus& status = ret->mut_obj(); + status.set_ba_id(get_id()); + status.set_in_downtime(in_downtime()); + if (_event) + status.set_last_state_change(_event->obj().start_time()); + else + status.set_last_state_change(get_last_kpi_update()); + status.set_level_nominal(_normalize(_level_hard)); + status.set_state(com::centreon::broker::State(get_state_hard())); + status.set_state_changed(state_changed); + + SPDLOG_LOGGER_DEBUG(log_v2::bam(), + "BAM: generating status of ratio percent BA {} '{}' " + "(state {}, in downtime {}, level {})", + get_id(), _name, status.state(), status.in_downtime(), + status.level_nominal()); + return ret; +} diff --git a/broker/bam/src/ba_svc_mapping.cc b/broker/bam/src/ba_svc_mapping.cc index 4aff684dac8..88a70e5691f 100644 --- a/broker/bam/src/ba_svc_mapping.cc +++ b/broker/bam/src/ba_svc_mapping.cc @@ -1,4 +1,4 @@ -/* +/** * Copyright 2014 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/broker/bam/src/ba_worst.cc b/broker/bam/src/ba_worst.cc index 8c9e79ce25e..7403f26cfb9 100644 --- a/broker/bam/src/ba_worst.cc +++ b/broker/bam/src/ba_worst.cc @@ -220,3 +220,23 @@ std::string ba_worst::get_output() const { std::string ba_worst::get_perfdata() const { return {}; } + +std::shared_ptr ba_worst::_generate_ba_status( + bool state_changed) const { + auto ret = std::make_shared(); + BaStatus& status = ret->mut_obj(); + status.set_ba_id(get_id()); + status.set_in_downtime(in_downtime()); + if (_event) + status.set_last_state_change(_event->obj().start_time()); + else + status.set_last_state_change(get_last_kpi_update()); + status.set_state(com::centreon::broker::State(get_state_hard())); + status.set_state_changed(state_changed); + + SPDLOG_LOGGER_DEBUG( + log_v2::bam(), + "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 b7827e41946..b4bfd08c393 100644 --- a/broker/bam/src/bool_and.cc +++ b/broker/bam/src/bool_and.cc @@ -1,4 +1,4 @@ -/* +/** * Copyright 2014, 2023 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/broker/bam/src/bool_call.cc b/broker/bam/src/bool_call.cc index 61d7e1fc30f..d9ef598ede9 100644 --- a/broker/bam/src/bool_call.cc +++ b/broker/bam/src/bool_call.cc @@ -1,4 +1,4 @@ -/* +/** * Copyright 2014, 2023 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/broker/bam/src/bool_constant.cc b/broker/bam/src/bool_constant.cc index fd68c36aa20..5db05c3c153 100644 --- a/broker/bam/src/bool_constant.cc +++ b/broker/bam/src/bool_constant.cc @@ -1,5 +1,5 @@ -/* - * Copyright 2016, 2023 Centreon +/** + * Copyright 2014, 2023 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/bam/src/bool_equal.cc b/broker/bam/src/bool_equal.cc index 471fcb3d9a9..fb60c27e62d 100644 --- a/broker/bam/src/bool_equal.cc +++ b/broker/bam/src/bool_equal.cc @@ -1,4 +1,4 @@ -/* +/** * Copyright 2014-2023 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -33,7 +33,6 @@ double bool_equal::value_hard() const { if (state_known()) retval = std::fabs(_left_hard - _right_hard) < COMPARE_EPSILON; - log_v2::bam()->trace("BAM: bool_equal: value as double: {}", retval); return retval; } @@ -47,7 +46,6 @@ bool bool_equal::boolean_value() const { if (state_known()) retval = std::fabs(_left_hard - _right_hard) < COMPARE_EPSILON; - log_v2::bam()->trace("BAM: bool_equal: value: {}", retval); return retval; } diff --git a/broker/bam/src/bool_expression.cc b/broker/bam/src/bool_expression.cc index ddae66dbd62..91786490f2f 100644 --- a/broker/bam/src/bool_expression.cc +++ b/broker/bam/src/bool_expression.cc @@ -1,4 +1,4 @@ -/* +/** * Copyright 2014, 2021-2023 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/broker/bam/src/bool_less_than.cc b/broker/bam/src/bool_less_than.cc index e2c6ecac6b6..ec6090d4285 100644 --- a/broker/bam/src/bool_less_than.cc +++ b/broker/bam/src/bool_less_than.cc @@ -1,4 +1,4 @@ -/* +/** * Copyright 2014, 2021-2023 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/broker/bam/src/bool_more_than.cc b/broker/bam/src/bool_more_than.cc index 7b1a65bce18..2f6b25e340a 100644 --- a/broker/bam/src/bool_more_than.cc +++ b/broker/bam/src/bool_more_than.cc @@ -1,4 +1,4 @@ -/* +/** * Copyright 2014, 2023 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/broker/bam/src/bool_not.cc b/broker/bam/src/bool_not.cc index f012089888a..f0b8be0f03c 100644 --- a/broker/bam/src/bool_not.cc +++ b/broker/bam/src/bool_not.cc @@ -1,4 +1,4 @@ -/* +/** * Copyright 2014, 2022-2023 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/broker/bam/src/bool_not_equal.cc b/broker/bam/src/bool_not_equal.cc index 4879a96d3de..77de82ca2a2 100644 --- a/broker/bam/src/bool_not_equal.cc +++ b/broker/bam/src/bool_not_equal.cc @@ -1,4 +1,4 @@ -/* +/** * Copyright 2016-2023 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/broker/bam/src/bool_operation.cc b/broker/bam/src/bool_operation.cc index f9744832078..12bef11453b 100644 --- a/broker/bam/src/bool_operation.cc +++ b/broker/bam/src/bool_operation.cc @@ -1,4 +1,4 @@ -/* +/** * Copyright 2014-2023 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -110,14 +110,19 @@ std::string bool_operation::object_info() const { switch (_type) { case addition: op = "PLUS"; + break; case substraction: op = "MINUS"; + break; case multiplication: op = "MUL"; + break; case division: op = "DIV"; + break; case modulo: op = "MODULO"; + break; default: return "unknown operation"; } diff --git a/broker/bam/src/bool_or.cc b/broker/bam/src/bool_or.cc index 0c15a6cbc72..f85d11d3a3e 100644 --- a/broker/bam/src/bool_or.cc +++ b/broker/bam/src/bool_or.cc @@ -1,4 +1,4 @@ -/* +/** * Copyright 2014, 2021, 2023 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/broker/bam/src/bool_service.cc b/broker/bam/src/bool_service.cc index 406f29cc4fd..fd6fd94d4f2 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. @@ -16,10 +16,9 @@ * For more information : contact@centreon.com */ -#include - #include "com/centreon/broker/bam/bool_service.hh" - +#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" @@ -54,6 +53,30 @@ uint32_t bool_service::get_service_id() const { return _service_id; } +/** + * @brief When the cache is restored, this method is used to update services in + * BAs. It works as others service_update() methods, except no visitor is + * needed here. + * + * @param s The service_state to apply. + */ +void bool_service::service_update(const service_state& s) { + // Update information. + log_v2::bam()->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); + if (_state_hard != state_unknown) + _state_known = true; + + // Propagate change. + if (changed) + notify_parents_of_change(nullptr); +} + /** * Notify of service update. * @@ -159,7 +182,6 @@ bool bool_service::boolean_value() const { * @return True if the state is known. */ bool bool_service::state_known() const { - log_v2::bam()->trace("BAM: bool_service::state_known: {}", _state_known); return _state_known; } diff --git a/broker/bam/src/bool_value.cc b/broker/bam/src/bool_value.cc index 8979e7a3fd6..e2bcb28de06 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-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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/bool_xor.cc b/broker/bam/src/bool_xor.cc index 258b52bbcb3..69bf05d54d3 100644 --- a/broker/bam/src/bool_xor.cc +++ b/broker/bam/src/bool_xor.cc @@ -1,4 +1,4 @@ -/* +/** * Copyright 2014, 2022-2023 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/broker/bam/src/configuration/applier/ba.cc b/broker/bam/src/configuration/applier/ba.cc index f17e72bbb48..84c3dacccd6 100644 --- a/broker/bam/src/configuration/applier/ba.cc +++ b/broker/bam/src/configuration/applier/ba.cc @@ -1,5 +1,5 @@ -/* - * Copyright 2014-2017, 2021-2023 Centreon +/** + * Copyright 2014-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. @@ -18,11 +18,13 @@ #include "com/centreon/broker/bam/configuration/applier/ba.hh" #include +#include "bbdo/bam/inherited_downtime.hh" #include "com/centreon/broker/bam/ba_best.hh" #include "com/centreon/broker/bam/ba_impact.hh" #include "com/centreon/broker/bam/ba_ratio_number.hh" #include "com/centreon/broker/bam/ba_ratio_percent.hh" #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" @@ -70,7 +72,7 @@ applier::ba& applier::ba::operator=(applier::ba const& other) { * @param[in] my_bas BAs to apply. * @param[in] book The service book. */ -void applier::ba::apply(bam::configuration::state::bas const& my_bas, +void applier::ba::apply(const bam::configuration::state::bas& my_bas, service_book& book) { // // DIFF @@ -371,13 +373,11 @@ std::shared_ptr applier::ba::_new_ba(configuration::ba const& cfg, * @param[in] cache The cache. */ void applier::ba::save_to_cache(persistent_cache& cache) { - cache.transaction(); for (std::map::const_iterator it = _applied.begin(), end = _applied.end(); it != end; ++it) { it->second.obj->save_inherited_downtime(cache); } - cache.commit(); } /** @@ -385,53 +385,44 @@ void applier::ba::save_to_cache(persistent_cache& cache) { * * @param[in] cache The cache. */ -void applier::ba::load_from_cache(persistent_cache& cache) { - log_v2::bam()->trace("BAM: loading inherited downtimes from cache"); +void applier::ba::apply_inherited_downtime(const inherited_downtime& dwn) { auto bbdo = config::applier::state::instance().get_bbdo_version(); bool bbdo3_enabled = bbdo.major_v >= 3; - std::shared_ptr d; - cache.get(d); - while (d) { - if (d->type() == inherited_downtime::static_type()) { - inherited_downtime const& dwn = - *std::static_pointer_cast(d); - 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); - found->second.obj->set_inherited_downtime(dwn); - std::shared_ptr s; - if (bbdo3_enabled) - s = _ba_pb_service(found->first, found->second.cfg.get_host_id(), - found->second.cfg.get_service_id(), - dwn.in_downtime); - else - s = _ba_service(found->first, found->second.cfg.get_host_id(), - found->second.cfg.get_service_id(), dwn.in_downtime); - multiplexing::publisher().write(s); - } - cache.get(d); - } else if (d->type() == pb_inherited_downtime::static_type()) { - pb_inherited_downtime const& dwn = - *std::static_pointer_cast(d); - 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); - found->second.obj->set_inherited_downtime(dwn); - std::shared_ptr s; - if (bbdo3_enabled) - s = _ba_pb_service(found->first, found->second.cfg.get_host_id(), - found->second.cfg.get_service_id(), - dwn.obj().in_downtime()); - else - s = _ba_service(found->first, found->second.cfg.get_host_id(), - found->second.cfg.get_service_id(), - dwn.obj().in_downtime()); - multiplexing::publisher().write(s); - } - cache.get(d); - } + + 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); + found->second.obj->set_inherited_downtime(dwn); + std::shared_ptr s; + if (bbdo3_enabled) + s = _ba_pb_service(found->first, found->second.cfg.get_host_id(), + found->second.cfg.get_service_id(), dwn.in_downtime); + else + s = _ba_service(found->first, found->second.cfg.get_host_id(), + found->second.cfg.get_service_id(), dwn.in_downtime); + multiplexing::publisher().write(s); + } +} + +void applier::ba::apply_inherited_downtime(const pb_inherited_downtime& dwn) { + auto bbdo = config::applier::state::instance().get_bbdo_version(); + bool bbdo3_enabled = bbdo.major_v >= 3; + 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); + found->second.obj->set_inherited_downtime(dwn); + std::shared_ptr s; + if (bbdo3_enabled) + s = _ba_pb_service(found->first, found->second.cfg.get_host_id(), + found->second.cfg.get_service_id(), + dwn.obj().in_downtime()); + else + s = _ba_service(found->first, found->second.cfg.get_host_id(), + found->second.cfg.get_service_id(), + dwn.obj().in_downtime()); + multiplexing::publisher().write(s); } } diff --git a/broker/bam/src/configuration/applier/bool_expression.cc b/broker/bam/src/configuration/applier/bool_expression.cc index 6c6d938961a..8aefc3b3d31 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-2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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" diff --git a/broker/bam/src/configuration/applier/kpi.cc b/broker/bam/src/configuration/applier/kpi.cc index 83fb3edd414..73c4ad51356 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, 2024 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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" diff --git a/broker/bam/src/configuration/applier/state.cc b/broker/bam/src/configuration/applier/state.cc index b269b173c87..9473f05190d 100644 --- a/broker/bam/src/configuration/applier/state.cc +++ b/broker/bam/src/configuration/applier/state.cc @@ -1,4 +1,4 @@ -/* +/** * Copyright 2014-2023 Centreon * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -17,10 +17,9 @@ */ #include "com/centreon/broker/bam/configuration/applier/state.hh" -#include #include "com/centreon/broker/bam/exp_builder.hh" -#include "com/centreon/broker/bam/exp_parser.hh" -#include "com/centreon/exceptions/msg_fmt.hh" +#include "com/centreon/broker/bam/internal.hh" +#include "com/centreon/broker/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; @@ -71,16 +70,6 @@ static std::string service_node_id(uint32_t host_id, uint32_t service_id) { return fmt::format("service ({}, {})", host_id, service_id); } -/** - * Default constructor. - */ -applier::state::state() {} - -/** - * Destructor. - */ -applier::state::~state() {} - /** * Apply configuration. * @@ -233,7 +222,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"); + cache.transaction(); + _book_service.save_to_cache(cache); _ba_applier.save_to_cache(cache); + cache.commit(); + log_v2::bam()->trace("BAM: States correctly saved"); } /** @@ -242,7 +236,32 @@ void applier::state::save_to_cache(persistent_cache& cache) { * @param[in] cache the cache. */ void applier::state::load_from_cache(persistent_cache& cache) { - _ba_applier.load_from_cache(cache); + log_v2::bam()->debug( + "BAM: Loading restoring inherited downtimes and BA states"); + + std::shared_ptr d; + cache.get(d); + while (d) { + switch (d->type()) { + case inherited_downtime::static_type(): { + const inherited_downtime& dwn = + *std::static_pointer_cast(d); + _ba_applier.apply_inherited_downtime(dwn); + } break; + case pb_inherited_downtime::static_type(): { + const pb_inherited_downtime& dwn = + *std::static_pointer_cast(d); + _ba_applier.apply_inherited_downtime(dwn); + } break; + case pb_services_book_state::static_type(): { + const ServicesBookState& state = + std::static_pointer_cast(d)->obj(); + _book_service.apply_services_state(state); + } break; + } + cache.get(d); + } + log_v2::bam()->debug("BAM: Inherited downtimes and BA states restored"); } /** diff --git a/broker/bam/src/configuration/ba.cc b/broker/bam/src/configuration/ba.cc index 9d70aa50ac7..b255a5d2b9b 100644 --- a/broker/bam/src/configuration/ba.cc +++ b/broker/bam/src/configuration/ba.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/configuration/ba.hh" #include "com/centreon/broker/bam/configuration/reader_exception.hh" diff --git a/broker/bam/src/configuration/state.cc b/broker/bam/src/configuration/state.cc index 764cf881714..69eb2f00053 100644 --- a/broker/bam/src/configuration/state.cc +++ b/broker/bam/src/configuration/state.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 "com/centreon/broker/bam/configuration/state.hh" diff --git a/broker/bam/src/connector.cc b/broker/bam/src/connector.cc index 37a3d36a319..15749645106 100644 --- a/broker/bam/src/connector.cc +++ b/broker/bam/src/connector.cc @@ -1,20 +1,20 @@ -/* -** Copyright 2014-2015, 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 -*/ +/** + * Copyright 2014-2015, 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 + */ #include "com/centreon/broker/bam/connector.hh" diff --git a/broker/bam/src/event_cache_visitor.cc b/broker/bam/src/event_cache_visitor.cc index 6242ad6bc4f..73f897b141c 100644 --- a/broker/bam/src/event_cache_visitor.cc +++ b/broker/bam/src/event_cache_visitor.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 "com/centreon/broker/bam/event_cache_visitor.hh" diff --git a/broker/bam/src/exp_builder.cc b/broker/bam/src/exp_builder.cc index df218096b99..14dcc4f650f 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 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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" diff --git a/broker/bam/src/exp_parser.cc b/broker/bam/src/exp_parser.cc index 81bbaa3bc25..5326289e5e6 100644 --- a/broker/bam/src/exp_parser.cc +++ b/broker/bam/src/exp_parser.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 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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" diff --git a/broker/bam/src/exp_tokenizer.cc b/broker/bam/src/exp_tokenizer.cc index c7536aba439..5b714231e46 100644 --- a/broker/bam/src/exp_tokenizer.cc +++ b/broker/bam/src/exp_tokenizer.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 Centreon + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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_tokenizer.hh" diff --git a/broker/bam/src/factory.cc b/broker/bam/src/factory.cc index 6f0c5ba0f73..e484e884dd4 100644 --- a/broker/bam/src/factory.cc +++ b/broker/bam/src/factory.cc @@ -1,20 +1,20 @@ -/* -** Copyright 2014-2016, 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-2016, 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/factory.hh" diff --git a/broker/bam/src/hst_svc_mapping.cc b/broker/bam/src/hst_svc_mapping.cc index 40ac81ff8ac..9de8b69627c 100644 --- a/broker/bam/src/hst_svc_mapping.cc +++ b/broker/bam/src/hst_svc_mapping.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/hst_svc_mapping.hh" #include "com/centreon/broker/log_v2.hh" diff --git a/broker/bam/src/impact_values.cc b/broker/bam/src/impact_values.cc index d576fc623fc..88659136476 100644 --- a/broker/bam/src/impact_values.cc +++ b/broker/bam/src/impact_values.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/impact_values.hh" diff --git a/broker/bam/src/kpi.cc b/broker/bam/src/kpi.cc index 02ad2d7d725..cc637c59227 100644 --- a/broker/bam/src/kpi.cc +++ b/broker/bam/src/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/kpi.hh" @@ -124,4 +124,4 @@ void kpi::_event_init() { _event->set_kpi_id(_id); _event->set_ba_id(_ba_id); } -} \ No newline at end of file +} diff --git a/broker/bam/src/kpi_service.cc b/broker/bam/src/kpi_service.cc index 2ebc7f89c13..7e2819a1c67 100644 --- a/broker/bam/src/kpi_service.cc +++ b/broker/bam/src/kpi_service.cc @@ -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. @@ -17,6 +17,7 @@ */ #include "com/centreon/broker/bam/kpi_service.hh" +#include "com/centreon/broker/bam/service_state.hh" #include @@ -32,7 +33,7 @@ using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::bam; -static bool time_is_undefined(uint64_t t) { +static constexpr bool time_is_undefined(uint64_t t) { return t == 0 || t == static_cast(-1); } @@ -164,6 +165,32 @@ bool kpi_service::is_acknowledged() const { return _acknowledged; } +void kpi_service::service_update(const service_state& s) { + // Log message. + log_v2::bam()->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( + "service kpi {} last check updated with status last check {}", _id, + s.last_check); + } + bool changed = _state_hard != static_cast(s.last_hard_state) || + _state_soft != static_cast(s.current_state) || + _state_type != s.state_type || _acknowledged != s.acknowledged; + + _state_hard = static_cast(s.last_hard_state); + _state_soft = static_cast(s.current_state); + _state_type = s.state_type; + _acknowledged = s.acknowledged; + + // Propagate change. + if (changed) + notify_parents_of_change(nullptr); +} + /** * Service got updated ! * @@ -381,15 +408,13 @@ void kpi_service::service_update( */ void kpi_service::service_update(const std::shared_ptr& dt, io::stream* visitor) { - assert(dt && dt->host_id == _host_id && dt->service_id == _service_id); + log_v2::bam()->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 = true; - - if (!_downtimed && downtimed) { - _downtimed = true; - changed = true; - } + 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", @@ -397,17 +422,26 @@ void kpi_service::service_update(const std::shared_ptr& dt, 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); if (downtimed) { log_v2::bam()->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); _downtime_ids.erase(dt->internal_id); bool new_downtimed = !_downtime_ids.empty(); if (new_downtimed != _downtimed) { - _downtimed = !_downtime_ids.empty(); + _downtimed = new_downtimed; changed = true; } } diff --git a/broker/bam/src/main.cc b/broker/bam/src/main.cc index 10b0025bced..45f5190ee1b 100644 --- a/broker/bam/src/main.cc +++ b/broker/bam/src/main.cc @@ -170,6 +170,8 @@ void broker_module_init(void const* arg) { e.register_event(bam::pb_dimension_truncate_table_signal::static_type(), "DimensionTruncateTableSignal", &bam::pb_dimension_truncate_table_signal::operations); + e.register_event(bam::pb_services_book_state::static_type(), "BaState", + &bam::pb_services_book_state::operations); /* Let's register the ba_info event to be sure it is declared in case * brokerrpc is not already instanciated. */ e.register_event(make_type(io::extcmd, extcmd::de_ba_info), "ba_info", diff --git a/broker/bam/src/monitoring_stream.cc b/broker/bam/src/monitoring_stream.cc index 9ba1a58c922..efc97970a6c 100644 --- a/broker/bam/src/monitoring_stream.cc +++ b/broker/bam/src/monitoring_stream.cc @@ -75,8 +75,6 @@ monitoring_stream::monitoring_stream(const std::string& ext_cmd_file, // Let's update BAs then we will be able to load the cache with inherited // downtimes. update(); - // Read cache. - _read_cache(); } /** @@ -181,6 +179,8 @@ void monitoring_stream::update() { _ba_mapping = s.get_ba_svc_mapping(); _rebuild(); initialize(); + // Read cache. + _read_cache(); } catch (std::exception const& e) { throw msg_fmt("BAM: could not process configuration update: {}", e.what()); } @@ -500,6 +500,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"); extcmd::pb_ba_info const& e = *std::static_pointer_cast(data); auto& obj = e.obj(); diff --git a/broker/bam/src/reporting_stream.cc b/broker/bam/src/reporting_stream.cc index afc421d0ea9..0d76622bd93 100644 --- a/broker/bam/src/reporting_stream.cc +++ b/broker/bam/src/reporting_stream.cc @@ -1,20 +1,20 @@ -/* -** Copyright 2014-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 2014-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 + */ #include diff --git a/broker/bam/src/service_book.cc b/broker/bam/src/service_book.cc index 49162bdbeef..5780351485e 100644 --- a/broker/bam/src/service_book.cc +++ b/broker/bam/src/service_book.cc @@ -1,31 +1,34 @@ -/* -** 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/service_book.hh" -#include "com/centreon/broker/bam/service_listener.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" using namespace com::centreon::broker::bam; +static constexpr bool time_is_undefined(uint64_t t) { + return t == 0 || t == static_cast(-1); +} + /** * Make a service listener listen to service updates. * @@ -38,7 +41,13 @@ void service_book::listen(uint32_t host_id, service_listener* listnr) { log_v2::bam()->trace("BAM: service ({}, {}) added to service book", host_id, service_id); - _book.insert(std::make_pair(std::make_pair(host_id, service_id), listnr)); + auto found = _book.find(std::make_pair(host_id, service_id)); + if (found == _book.end()) { + service_state_listeners sl{{listnr}, + {.host_id = host_id, .service_id = service_id}}; + _book[std::make_pair(host_id, service_id)] = sl; + } else + _book[std::make_pair(host_id, service_id)].listeners.push_back(listnr); } /** @@ -51,14 +60,12 @@ void service_book::listen(uint32_t host_id, void service_book::unlisten(uint32_t host_id, uint32_t service_id, service_listener* listnr) { - std::pair range( - _book.equal_range(std::make_pair(host_id, service_id))); - while (range.first != range.second) { - if (range.first->second == listnr) { - _book.erase(range.first); - break; - } - ++range.first; + auto found = _book.find(std::make_pair(host_id, service_id)); + if (found != _book.end()) { + found->second.listeners.remove_if( + [listnr](service_listener* item) { return item == listnr; }); + if (found->second.listeners.empty()) + _book.erase(found); } } @@ -71,12 +78,14 @@ void service_book::unlisten(uint32_t host_id, */ void service_book::update(const std::shared_ptr& t, io::stream* visitor) { - std::pair range{_book.equal_range( - std::make_pair(t->obj().host_id(), t->obj().service_id()))}; - while (range.first != range.second) { - range.first->second->service_update(t, visitor); - ++range.first; - } + auto found = + _book.find(std::make_pair(t->obj().host_id(), t->obj().service_id())); + if (found == _book.end()) + return; + auto& svc_state = found->second.state; + svc_state.acknowledged = time_is_undefined(t->obj().deletion_time()); + for (auto l : found->second.listeners) + l->service_update(t, visitor); } /** @@ -88,12 +97,13 @@ void service_book::update(const std::shared_ptr& t, */ void service_book::update(const std::shared_ptr& t, io::stream* visitor) { - std::pair range{ - _book.equal_range(std::make_pair(t->host_id, t->service_id))}; - while (range.first != range.second) { - range.first->second->service_update(t, visitor); - ++range.first; - } + auto found = _book.find(std::make_pair(t->host_id, t->service_id)); + if (found == _book.end()) + return; + auto& svc_state = found->second.state; + svc_state.acknowledged = t->deletion_time.is_null(); + for (auto l : found->second.listeners) + l->service_update(t, visitor); } /** @@ -105,12 +115,11 @@ void service_book::update(const std::shared_ptr& t, */ void service_book::update(const std::shared_ptr& t, io::stream* visitor) { - std::pair range{ - _book.equal_range(std::make_pair(t->host_id, t->service_id))}; - while (range.first != range.second) { - range.first->second->service_update(t, visitor); - ++range.first; - } + auto found = _book.find(std::make_pair(t->host_id, t->service_id)); + if (found == _book.end()) + return; + for (auto l : found->second.listeners) + l->service_update(t, visitor); } /** @@ -122,13 +131,12 @@ void service_book::update(const std::shared_ptr& t, */ void service_book::update(const std::shared_ptr& t, io::stream* visitor) { - auto& downtime = t->obj(); - std::pair range{_book.equal_range( - std::make_pair(downtime.host_id(), downtime.service_id()))}; - while (range.first != range.second) { - range.first->second->service_update(t, visitor); - ++range.first; - } + auto found = + _book.find(std::make_pair(t->obj().host_id(), t->obj().service_id())); + if (found == _book.end()) + return; + for (auto l : found->second.listeners) + l->service_update(t, visitor); } /** @@ -140,17 +148,17 @@ void service_book::update(const std::shared_ptr& t, */ void service_book::update(const std::shared_ptr& t, io::stream* visitor) { - std::pair range{ - _book.equal_range(std::make_pair(t->host_id, t->service_id))}; - size_t count = 0; - while (range.first != range.second) { - count++; - range.first->second->service_update(t, visitor); - ++range.first; - } - log_v2::bam()->trace( - "service_book: {} listeners notified of service ({},{}) status", count, - t->host_id, t->service_id); + auto found = _book.find(std::make_pair(t->host_id, t->service_id)); + if (found == _book.end()) + return; + auto& svc_state = found->second.state; + svc_state.current_state = static_cast(t->current_state); + svc_state.last_hard_state = static_cast(t->last_hard_state); + svc_state.last_check = t->last_check; + svc_state.state_type = t->state_type; + + for (auto l : found->second.listeners) + l->service_update(t, visitor); } /** @@ -162,17 +170,20 @@ void service_book::update(const std::shared_ptr& t, */ void service_book::update(const std::shared_ptr& t, io::stream* visitor) { - std::pair range{_book.equal_range( - std::make_pair(t->obj().host_id(), t->obj().service_id()))}; - size_t count = 0; - while (range.first != range.second) { - ++count; - range.first->second->service_update(t, visitor); - ++range.first; - } - log_v2::bam()->trace( - "service_book: {} listeners notified of pb service ({},{})", count, - t->obj().host_id(), t->obj().service_id()); + auto found = + _book.find(std::make_pair(t->obj().host_id(), t->obj().service_id())); + if (found == _book.end()) + return; + auto& svc_state = found->second.state; + auto& o = t->obj(); + svc_state.last_check = + time_is_undefined(o.last_check()) ? std::time(nullptr) : o.last_check(); + svc_state.last_hard_state = static_cast(o.last_hard_state()); + svc_state.current_state = static_cast(o.state()); + svc_state.state_type = o.state_type(); + + for (auto l : found->second.listeners) + l->service_update(t, visitor); } /** @@ -184,15 +195,65 @@ void service_book::update(const std::shared_ptr& t, */ void service_book::update(const std::shared_ptr& t, io::stream* visitor) { - std::pair range{_book.equal_range( - std::make_pair(t->obj().host_id(), t->obj().service_id()))}; - size_t count = 0; - while (range.first != range.second) { - ++count; - range.first->second->service_update(t, visitor); - ++range.first; + auto found = + _book.find(std::make_pair(t->obj().host_id(), t->obj().service_id())); + if (found == _book.end()) + return; + auto& svc_state = found->second.state; + auto& o = t->obj(); + svc_state.last_check = + time_is_undefined(o.last_check()) ? std::time(nullptr) : o.last_check(); + svc_state.last_hard_state = static_cast(o.last_hard_state()); + svc_state.current_state = static_cast(o.state()); + svc_state.state_type = o.state_type(); + + for (auto l : found->second.listeners) + l->service_update(t, visitor); +} + +/** + * @brief Save the services states from the service_book to the cache. The cache + * must be open with write mode, otherwise, this function throws an exception. + * + * @param cache The persistent cache to receive data. + */ +void service_book::save_to_cache(persistent_cache& cache) const { + auto to_save_ptr = std::make_shared(); + ServicesBookState& to_save = to_save_ptr->mut_obj(); + for (auto it = _book.begin(); it != _book.end(); ++it) { + auto& state = it->second.state; + auto* svc = to_save.add_service(); + svc->set_host_id(state.host_id); + svc->set_service_id(state.service_id); + svc->set_current_state(state.current_state); + svc->set_last_hard_state(state.last_hard_state); + svc->set_last_check(state.last_check); + svc->set_state_type(state.state_type); + svc->set_acknowledged(state.acknowledged); + } + cache.add(to_save_ptr); +} + +/** + * @brief Restore from the ServicesBookState the states of all the services + * involved in BAs. + * + * @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"); + for (auto& svc : state.service()) { + auto found = _book.find(std::make_pair(svc.host_id(), svc.service_id())); + if (found == _book.end()) + continue; + auto& svc_state = found->second.state; + svc_state.current_state = svc.current_state(); + svc_state.last_hard_state = svc.last_hard_state(); + svc_state.last_check = svc.last_check(); + svc_state.state_type = svc.state_type(); + svc_state.acknowledged = svc.acknowledged(); + for (auto l : found->second.listeners) + l->service_update(svc_state); } - log_v2::bam()->trace( - "service_book: {} listeners notified of pb service ({},{}) status", count, - t->obj().host_id(), t->obj().service_id()); + log_v2::bam()->trace("BAM: Services state applied from cache"); } diff --git a/broker/bam/src/service_listener.cc b/broker/bam/src/service_listener.cc index 91238966b59..46aa9ccce93 100644 --- a/broker/bam/src/service_listener.cc +++ b/broker/bam/src/service_listener.cc @@ -1,25 +1,34 @@ -/* -** 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 "com/centreon/broker/bam/service_listener.hh" using namespace com::centreon::broker::bam; +/** + * Notify of a service status update. + * + * @param[in] status Service status. + * @param[out] visitor Visitor. + */ +void service_listener::service_update(const service_state& state + [[maybe_unused]]) {} + /** * Notify of a service status update. * diff --git a/engine/src/anomalydetection.cc b/engine/src/anomalydetection.cc index d4517d012b2..b03b6f43db4 100644 --- a/engine/src/anomalydetection.cc +++ b/engine/src/anomalydetection.cc @@ -1,21 +1,21 @@ -/* -** 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 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 + * . + */ #include "com/centreon/engine/anomalydetection.hh" @@ -1120,9 +1120,11 @@ void anomalydetection::init_thresholds() { try { t.open(_thresholds_file); } catch (const std::system_error& e) { - SPDLOG_LOGGER_ERROR(log_v2::config(), - "Fail to read thresholds file '{}' : {}", - _thresholds_file, e.code().message()); + if (!verify_config) { + SPDLOG_LOGGER_ERROR(log_v2::config(), + "Fail to read thresholds file '{}' : {}", + _thresholds_file, e.code().message()); + } return; } catch (const std::exception& e) { SPDLOG_LOGGER_ERROR(log_v2::config(), diff --git a/tests/bam/bam_pb.robot b/tests/bam/bam_pb.robot index 0200cd65874..e3d9e9f6518 100644 --- a/tests/bam/bam_pb.robot +++ b/tests/bam/bam_pb.robot @@ -59,8 +59,8 @@ BAPBSTATUS Connect To Database pymysql ${DBNameConf} ${DBUser} ${DBPass} ${DBHost} ${DBPort} ${output} Query - ... SELECT current_level, acknowledged, downtime, in_downtime, current_status FROM mod_bam WHERE name='test' - Should Be Equal As Strings ${output} ((100.0, 0.0, 0.0, 0, 2),) + ... SELECT acknowledged, downtime, in_downtime, current_status FROM mod_bam WHERE name='test' + Should Be Equal As Strings ${output} ((0.0, 0.0, 0, 2),) # Little check of the GetBa gRPC command ${result} Run Keyword And Return Status File Should Exist /tmp/output diff --git a/tests/broker-engine/anomaly-detection.robot b/tests/broker-engine/anomaly-detection.robot index ea79c2b8f6b..c8cefbfeb93 100644 --- a/tests/broker-engine/anomaly-detection.robot +++ b/tests/broker-engine/anomaly-detection.robot @@ -1,348 +1,364 @@ *** Settings *** -Resource ../resources/resources.robot -Suite Setup Clean Before Suite -Suite Teardown Clean After Suite -Test Setup Stop Processes -Test Teardown Save logs If Failed +Resource ../resources/resources.robot +Suite Setup Clean Before Suite +Suite Teardown Clean After Suite +Test Setup Stop Processes +Test Teardown Save logs If Failed -Documentation Centreon Broker and Engine anomaly detection +Documentation Centreon Broker and Engine anomaly detection -Library DateTime -Library Process -Library OperatingSystem -Library ../resources/Engine.py -Library ../resources/Broker.py -Library ../resources/Common.py +Library DateTime +Library Process +Library OperatingSystem +Library ../resources/Engine.py +Library ../resources/Broker.py +Library ../resources/Common.py *** Test Cases *** ANO_NOFILE - [Documentation] an anomaly detection without threshold file must be in unknown state - [Tags] Broker Engine Anomaly - Config Engine ${1} ${50} ${20} - Config Broker central - Config Broker module ${1} - Broker Config Log central sql debug - Config Broker Sql Output central unified_sql - ${serv_id}= Create Anomaly Detection ${0} ${1} ${1} metric - Remove File /tmp/anomaly_threshold.json - Clear Retention - Clear Db services - Start Broker True - Start Engine - Process Service Check result host_1 anomaly_${serv_id} 2 taratata - Check Service Status With Timeout host_1 anomaly_${serv_id} 3 30 - Stop Broker True - Stop Engine + [Documentation] an anomaly detection without threshold file must be in unknown state + [Tags] Broker Engine Anomaly + Config Engine ${1} ${50} ${20} + Config Broker central + Config Broker module ${1} + Broker Config Log central sql debug + Config Broker Sql Output central unified_sql + ${serv_id} Create Anomaly Detection ${0} ${1} ${1} metric + Remove File /tmp/anomaly_threshold.json + Clear Retention + Clear Db services + Start Broker True + Start Engine + Process Service Check result host_1 anomaly_${serv_id} 2 taratata + Check Service Status With Timeout host_1 anomaly_${serv_id} 3 30 + Stop Broker True + Stop Engine ANO_TOO_OLD_FILE - [Documentation] an anomaly detection with an oldest threshold file must be in unknown state - [Tags] Broker Engine Anomaly - Config Engine ${1} ${50} ${20} - Config Broker central - Config Broker module ${1} - Broker Config Log central sql debug - Config Broker Sql Output central unified_sql - ${serv_id}= Create Anomaly Detection ${0} ${1} ${1} metric - ${predict_data} = Evaluate [[0,0,2],[1648812678,0,3]] - Create Anomaly Threshold File /tmp/anomaly_threshold.json ${1} ${serv_id} metric ${predict_data} - Clear Retention - Clear Db services - Start Broker True - Start Engine - Process Service Check result host_1 anomaly_${serv_id} 2 taratata|metric=70%;50;75 - Check Service Status With Timeout host_1 anomaly_${serv_id} 3 30 - Stop Broker True - Stop Engine + [Documentation] an anomaly detection with an oldest threshold file must be in unknown state + [Tags] Broker Engine Anomaly + Config Engine ${1} ${50} ${20} + Config Broker central + Config Broker module ${1} + Broker Config Log central sql debug + Config Broker Sql Output central unified_sql + ${serv_id} Create Anomaly Detection ${0} ${1} ${1} metric + ${predict_data} Evaluate [[0,0,2],[1648812678,0,3]] + Create Anomaly Threshold File /tmp/anomaly_threshold.json ${1} ${serv_id} metric ${predict_data} + Clear Retention + Clear Db services + Start Broker True + Start Engine + Process Service Check result host_1 anomaly_${serv_id} 2 taratata|metric=70%;50;75 + Check Service Status With Timeout host_1 anomaly_${serv_id} 3 30 + Stop Broker True + Stop Engine ANO_OUT_LOWER_THAN_LIMIT - [Documentation] an anomaly detection with a perfdata lower than lower limit make a critical state - [Tags] Broker Engine Anomaly - Config Engine ${1} ${50} ${20} - Config Broker central - Config Broker module ${1} - Broker Config Log central sql debug - Config Broker Sql Output central unified_sql - ${serv_id}= Create Anomaly Detection ${0} ${1} ${1} metric - ${predict_data} = Evaluate [[0,50,52],[2648812678,50,63]] - Create Anomaly Threshold File /tmp/anomaly_threshold.json ${1} ${serv_id} metric ${predict_data} - Clear Retention - Clear Db services - Start Broker True - Start Engine - Process Service Check result host_1 anomaly_${serv_id} 2 taratata|metric=20%;50;75 - Check Service Status With Timeout host_1 anomaly_${serv_id} 2 30 - Stop Broker True - Stop Engine + [Documentation] an anomaly detection with a perfdata lower than lower limit make a critical state + [Tags] Broker Engine Anomaly + Config Engine ${1} ${50} ${20} + Config Broker central + Config Broker module ${1} + Broker Config Log central sql debug + Config Broker Sql Output central unified_sql + ${serv_id} Create Anomaly Detection ${0} ${1} ${1} metric + ${predict_data} Evaluate [[0,50,52],[2648812678,50,63]] + Create Anomaly Threshold File /tmp/anomaly_threshold.json ${1} ${serv_id} metric ${predict_data} + Clear Retention + Clear Db services + Start Broker True + Start Engine + Process Service Check result host_1 anomaly_${serv_id} 2 taratata|metric=20%;50;75 + Check Service Status With Timeout host_1 anomaly_${serv_id} 2 30 + Stop Broker True + Stop Engine ANO_OUT_UPPER_THAN_LIMIT - [Documentation] an anomaly detection with a perfdata upper than upper limit make a critical state - [Tags] Broker Engine Anomaly - Config Engine ${1} ${50} ${20} - Config Broker central - Config Broker module ${1} - Broker Config Log central sql debug - Config Broker Sql Output central unified_sql - ${serv_id}= Create Anomaly Detection ${0} ${1} ${1} metric - ${predict_data} = Evaluate [[0,50,52],[2648812678,50,63]] - Create Anomaly Threshold File /tmp/anomaly_threshold.json ${1} ${serv_id} metric ${predict_data} - Clear Retention - Clear Db services - Start Broker True - Start Engine - Process Service Check result host_1 anomaly_${serv_id} 2 taratata|metric=80%;50;75 - Check Service Status With Timeout host_1 anomaly_${serv_id} 2 30 - Stop Broker True - Stop Engine + [Documentation] an anomaly detection with a perfdata upper than upper limit make a critical state + [Tags] Broker Engine Anomaly + Config Engine ${1} ${50} ${20} + Config Broker central + Config Broker module ${1} + Broker Config Log central sql debug + Config Broker Sql Output central unified_sql + ${serv_id} Create Anomaly Detection ${0} ${1} ${1} metric + ${predict_data} Evaluate [[0,50,52],[2648812678,50,63]] + Create Anomaly Threshold File /tmp/anomaly_threshold.json ${1} ${serv_id} metric ${predict_data} + Clear Retention + Clear Db services + Start Broker True + Start Engine + Process Service Check result host_1 anomaly_${serv_id} 2 taratata|metric=80%;50;75 + Check Service Status With Timeout host_1 anomaly_${serv_id} 2 30 + Stop Broker True + Stop Engine ANO_JSON_SENSITIVITY_NOT_SAVED - [Documentation] json sensitivity not saved in retention - [Tags] Engine Anomaly Retention - Config Engine ${1} ${50} ${20} - ${serv_id}= Create Anomaly Detection ${0} ${1} ${1} metric - ${predict_data} = Evaluate [[0,50,2, 10],[2648812678,25,-5,6]] - Create Anomaly Threshold File V2 /tmp/anomaly_threshold.json ${1} ${serv_id} metric 55.0 ${predict_data} - Clear Retention - Start Engine - Sleep 5s - Stop Engine - ${retention_sensitivity} = Grep Retention ${0} sensitivity=0.00 - Should Be Equal As Strings ${retention_sensitivity} sensitivity=0.00 + [Documentation] json sensitivity not saved in retention + [Tags] Engine Anomaly Retention + Config Engine ${1} ${50} ${20} + ${serv_id} Create Anomaly Detection ${0} ${1} ${1} metric + ${predict_data} Evaluate [[0,50,2, 10],[2648812678,25,-5,6]] + Create Anomaly Threshold File V2 /tmp/anomaly_threshold.json ${1} ${serv_id} metric 55.0 ${predict_data} + Clear Retention + Start Engine + Sleep 5s + Stop Engine + ${retention_sensitivity} Grep Retention ${0} sensitivity=0.00 + Should Be Equal As Strings ${retention_sensitivity} sensitivity=0.00 ANO_CFG_SENSITIVITY_SAVED - [Documentation] cfg sensitivity saved in retention - [Tags] Engine Anomaly Retention - Config Engine ${1} ${50} ${20} - ${serv_id}= Create Anomaly Detection ${0} ${1} ${1} metric 4.00 - ${predict_data} = Evaluate [[0,50,2, 10],[2648812678,25,-5,6]] - Create Anomaly Threshold File V2 /tmp/anomaly_threshold.json ${1} ${serv_id} metric 55.0 ${predict_data} - Clear Retention - Start Engine - Sleep 5s - Stop Engine - ${retention_sensitivity} = Grep Retention ${0} sensitivity=4.00 - Should Be Equal As Strings ${retention_sensitivity} sensitivity=4.00 + [Documentation] cfg sensitivity saved in retention + [Tags] Engine Anomaly Retention + Config Engine ${1} ${50} ${20} + ${serv_id} Create Anomaly Detection ${0} ${1} ${1} metric 4.00 + ${predict_data} Evaluate [[0,50,2, 10],[2648812678,25,-5,6]] + Create Anomaly Threshold File V2 /tmp/anomaly_threshold.json ${1} ${serv_id} metric 55.0 ${predict_data} + Clear Retention + Start Engine + Sleep 5s + Stop Engine + ${retention_sensitivity} Grep Retention ${0} sensitivity=4.00 + Should Be Equal As Strings ${retention_sensitivity} sensitivity=4.00 ANO_EXTCMD_SENSITIVITY_SAVED - [Documentation] extcmd sensitivity saved in retention - [Tags] Engine Anomaly Retention extcmd - FOR ${use_grpc} IN RANGE 1 2 - Config Engine ${1} ${50} ${20} - ${serv_id}= Create Anomaly Detection ${0} ${1} ${1} metric - ${predict_data} = Evaluate [[0,50,2, 10],[2648812678,25,-5,6]] - Create Anomaly Threshold File V2 /tmp/anomaly_threshold.json ${1} ${serv_id} metric 55.0 ${predict_data} - Clear Retention - Start Engine - Sleep 5s - Update Ano Sensitivity ${use_grpc} host_1 anomaly_1001 4.55 - Sleep 1s - Stop Engine - ${retention_sensitivity} = Grep Retention ${0} sensitivity=4.55 - Should Be Equal As Strings ${retention_sensitivity} sensitivity=4.55 - END + [Documentation] extcmd sensitivity saved in retention + [Tags] Engine Anomaly Retention extcmd + FOR ${use_grpc} IN RANGE 1 2 + Config Engine ${1} ${50} ${20} + ${serv_id} Create Anomaly Detection ${0} ${1} ${1} metric + ${predict_data} Evaluate [[0,50,2, 10],[2648812678,25,-5,6]] + Create Anomaly Threshold File V2 /tmp/anomaly_threshold.json ${1} ${serv_id} metric 55.0 ${predict_data} + Clear Retention + Start Engine + Sleep 5s + Update Ano Sensitivity ${use_grpc} host_1 anomaly_1001 4.55 + Sleep 1s + Stop Engine + ${retention_sensitivity} Grep Retention ${0} sensitivity=4.55 + Should Be Equal As Strings ${retention_sensitivity} sensitivity=4.55 + END AOUTLU1 - [Documentation] an anomaly detection with a perfdata upper than upper limit make a critical state with bbdo 3 - [Tags] Broker Engine Anomaly bbdo - Config Engine ${1} ${50} ${20} - Config Broker central - Config Broker rrd - Config Broker module ${1} - Broker Config Log central sql debug - Config Broker Sql Output central unified_sql - Broker Config Add Item module0 bbdo_version 3.0.1 - Broker Config Add Item rrd bbdo_version 3.0.1 - Broker Config Add Item central bbdo_version 3.0.1 - ${serv_id}= Create Anomaly Detection ${0} ${1} ${1} metric - ${predict_data} = Evaluate [[0,50,52],[2648812678,50,63]] - Create Anomaly Threshold File /tmp/anomaly_threshold.json ${1} ${serv_id} metric ${predict_data} - Clear Retention - Clear Db services - Start Broker - ${start}= Get Current Date - Start Engine - # Let's wait for the check of external commands - ${content}= Create List check_for_external_commands - ${result}= Find In Log with Timeout ${engineLog0} ${start} ${content} 60 - Should Be True ${result} msg=No check for external commands executed for 1mn. - - Process Service Check result host_1 anomaly_${serv_id} 2 taratata|metric=80%;50;75 - Check Service Status With Timeout host_1 anomaly_${serv_id} 2 30 - Stop Engine - Kindly Stop Broker - ${lst}= Create List 1 0 4 - ${result}= Check Types in resources ${lst} - Should Be True ${result} msg=The table 'resources' should contain rows of types SERVICE, HOST and ANOMALY_DETECTION. + [Documentation] an anomaly detection with a perfdata upper than upper limit make a critical state with bbdo 3 + [Tags] Broker Engine Anomaly bbdo + Config Engine ${1} ${50} ${20} + Config Broker central + Config Broker rrd + Config Broker module ${1} + Broker Config Log central sql debug + Config Broker Sql Output central unified_sql + Broker Config Add Item module0 bbdo_version 3.0.1 + Broker Config Add Item rrd bbdo_version 3.0.1 + Broker Config Add Item central bbdo_version 3.0.1 + ${serv_id} Create Anomaly Detection ${0} ${1} ${1} metric + ${predict_data} Evaluate [[0,50,52],[2648812678,50,63]] + Create Anomaly Threshold File /tmp/anomaly_threshold.json ${1} ${serv_id} metric ${predict_data} + Clear Retention + Clear Db services + Start Broker + ${start} Get Current Date + Start Engine + # Let's wait for the check of external commands + ${content} Create List check_for_external_commands + ${result} Find In Log with Timeout ${engineLog0} ${start} ${content} 60 + Should Be True ${result} msg=No check for external commands executed for 1mn. + + Process Service Check result host_1 anomaly_${serv_id} 2 taratata|metric=80%;50;75 + Check Service Status With Timeout host_1 anomaly_${serv_id} 2 30 + Stop Engine + Kindly Stop Broker + ${lst} Create List 1 0 4 + ${result} Check Types in resources ${lst} + Should Be True ${result} msg=The table 'resources' should contain rows of types SERVICE, HOST and ANOMALY_DETECTION. ANO_DT1 - [Documentation] downtime on dependent service is inherited by ano - [Tags] Broker Engine Anomaly - Config Engine ${1} ${50} ${20} - Config Broker central - Config Broker rrd - Config Broker module ${1} - Broker Config Log central sql debug - Config Broker Sql Output central unified_sql - Broker Config Add Item module0 bbdo_version 3.0.1 - Broker Config Add Item rrd bbdo_version 3.0.1 - Broker Config Add Item central bbdo_version 3.0.1 - ${serv_id}= Create Anomaly Detection ${0} ${1} ${1} metric - ${predict_data} = Evaluate [[0,50,52],[2648812678,50,63]] - Create Anomaly Threshold File /tmp/anomaly_threshold.json ${1} ${serv_id} metric ${predict_data} - Clear Retention - Clear Db services - Clear Db downtimes - Start Broker - ${start}= Get Current Date - Start Engine - # Let's wait for the check of external commands - ${content}= Create List check_for_external_commands - ${result}= Find In Log with Timeout ${engineLog0} ${start} ${content} 60 - Should Be True ${result} msg=No check for external commands executed for 1mn. - - #create dependent service downtime - Schedule Service Fixed Downtime host_1 service_1 3600 - - ${result}= Check Service Downtime With Timeout host_1 service_1 1 60 - Should Be True ${result} msg=dependent service must be in downtime - ${result}= Check Service Downtime With Timeout host_1 anomaly_${serv_id} 1 60 - Should Be True ${result} msg=anomaly service must be in downtime - - Stop Engine - Kindly Stop Broker + [Documentation] downtime on dependent service is inherited by ano + [Tags] Broker Engine Anomaly + Config Engine ${1} ${50} ${20} + Config Broker central + Config Broker rrd + Config Broker module ${1} + Broker Config Log central sql debug + Config Broker Sql Output central unified_sql + Broker Config Add Item module0 bbdo_version 3.0.1 + Broker Config Add Item rrd bbdo_version 3.0.1 + Broker Config Add Item central bbdo_version 3.0.1 + ${serv_id} Create Anomaly Detection ${0} ${1} ${1} metric + ${predict_data} Evaluate [[0,50,52],[2648812678,50,63]] + Create Anomaly Threshold File /tmp/anomaly_threshold.json ${1} ${serv_id} metric ${predict_data} + Clear Retention + Clear Db services + Clear Db downtimes + Start Broker + ${start} Get Current Date + Start Engine + # Let's wait for the check of external commands + ${content} Create List check_for_external_commands + ${result} Find In Log with Timeout ${engineLog0} ${start} ${content} 60 + Should Be True ${result} msg=No check for external commands executed for 1mn. + + #create dependent service downtime + Schedule Service Fixed Downtime host_1 service_1 3600 + + ${result} Check Service Downtime With Timeout host_1 service_1 1 60 + Should Be True ${result} msg=dependent service must be in downtime + ${result} Check Service Downtime With Timeout host_1 anomaly_${serv_id} 1 60 + Should Be True ${result} msg=anomaly service must be in downtime + + Stop Engine + Kindly Stop Broker ANO_DT2 - [Documentation] delete downtime on dependent service delete one on ano serv - [Tags] Broker Engine Anomaly - Config Engine ${1} ${50} ${20} - Config Broker central - Config Broker rrd - Config Broker module ${1} - Broker Config Log central sql debug - Config Broker Sql Output central unified_sql - Broker Config Add Item module0 bbdo_version 3.0.1 - Broker Config Add Item rrd bbdo_version 3.0.1 - Broker Config Add Item central bbdo_version 3.0.1 - ${serv_id}= Create Anomaly Detection ${0} ${1} ${1} metric - ${predict_data} = Evaluate [[0,50,52],[2648812678,50,63]] - Create Anomaly Threshold File /tmp/anomaly_threshold.json ${1} ${serv_id} metric ${predict_data} - Clear Retention - Clear Db services - Clear Db downtimes - Start Broker - ${start}= Get Current Date - Start Engine - # Let's wait for the check of external commands - ${content}= Create List check_for_external_commands - ${result}= Find In Log with Timeout ${engineLog0} ${start} ${content} 60 - Should Be True ${result} msg=No check for external commands executed for 1mn. - - #create dependent service downtime - Schedule Service Fixed Downtime host_1 service_1 3600 - - ${result}= Check Service Downtime With Timeout host_1 anomaly_${serv_id} 1 60 - Should Be True ${result} msg=anomaly service must be in downtime - - DELETE SERVICE DOWNTIME host_1 service_1 - ${result}= Check Service Downtime With Timeout host_1 service_1 0 60 - Should Be True ${result} msg=dependent service must be in downtime - ${result}= Check Service Downtime With Timeout host_1 anomaly_${serv_id} 0 60 - Should Be True ${result} msg=anomaly service must be in downtime - - - Stop Engine - Kindly Stop Broker + [Documentation] delete downtime on dependent service delete one on ano serv + [Tags] Broker Engine Anomaly + Config Engine ${1} ${50} ${20} + Config Broker central + Config Broker rrd + Config Broker module ${1} + Broker Config Log central sql debug + Config Broker Sql Output central unified_sql + Broker Config Add Item module0 bbdo_version 3.0.1 + Broker Config Add Item rrd bbdo_version 3.0.1 + Broker Config Add Item central bbdo_version 3.0.1 + ${serv_id} Create Anomaly Detection ${0} ${1} ${1} metric + ${predict_data} Evaluate [[0,50,52],[2648812678,50,63]] + Create Anomaly Threshold File /tmp/anomaly_threshold.json ${1} ${serv_id} metric ${predict_data} + Clear Retention + Clear Db services + Clear Db downtimes + Start Broker + ${start} Get Current Date + Start Engine + # Let's wait for the check of external commands + ${content} Create List check_for_external_commands + ${result} Find In Log with Timeout ${engineLog0} ${start} ${content} 60 + Should Be True ${result} msg=No check for external commands executed for 1mn. + + #create dependent service downtime + Schedule Service Fixed Downtime host_1 service_1 3600 + + ${result} Check Service Downtime With Timeout host_1 anomaly_${serv_id} 1 60 + Should Be True ${result} msg=anomaly service must be in downtime + + DELETE SERVICE DOWNTIME host_1 service_1 + ${result} Check Service Downtime With Timeout host_1 service_1 0 60 + Should Be True ${result} msg=dependent service must be in downtime + ${result} Check Service Downtime With Timeout host_1 anomaly_${serv_id} 0 60 + Should Be True ${result} msg=anomaly service must be in downtime + + + Stop Engine + Kindly Stop Broker ANO_DT3 - [Documentation] delete downtime on anomaly don t delete dependent service one - [Tags] Broker Engine Anomaly - Config Engine ${1} ${50} ${20} - Config Broker central - Config Broker rrd - Config Broker module ${1} - Broker Config Log central sql debug - Config Broker Sql Output central unified_sql - Broker Config Add Item module0 bbdo_version 3.0.1 - Broker Config Add Item rrd bbdo_version 3.0.1 - Broker Config Add Item central bbdo_version 3.0.1 - ${serv_id}= Create Anomaly Detection ${0} ${1} ${1} metric - ${predict_data} = Evaluate [[0,50,52],[2648812678,50,63]] - Create Anomaly Threshold File /tmp/anomaly_threshold.json ${1} ${serv_id} metric ${predict_data} - Clear Retention - Clear Db services - Clear Db downtimes - Start Broker - ${start}= Get Current Date - Start Engine - # Let's wait for the check of external commands - ${content}= Create List check_for_external_commands - ${result}= Find In Log with Timeout ${engineLog0} ${start} ${content} 60 - Should Be True ${result} msg=No check for external commands executed for 1mn. - - #create dependent service downtime - Schedule Service Fixed Downtime host_1 service_1 3600 - - ${result}= Check Service Downtime With Timeout host_1 anomaly_${serv_id} 1 60 - Should Be True ${result} msg=anomaly service must be in downtime - - DELETE SERVICE DOWNTIME host_1 anomaly_${serv_id} - ${result}= Check Service Downtime With Timeout host_1 anomaly_${serv_id} 0 60 - Should Be True ${result} msg=anomaly service must be in downtime - Sleep 2s - ${result}= Check Service Downtime With Timeout host_1 service_1 1 60 - Should Be True ${result} msg=dependent service must be in downtime - - - Stop Engine - Kindly Stop Broker + [Documentation] delete downtime on anomaly don t delete dependent service one + [Tags] Broker Engine Anomaly + Config Engine ${1} ${50} ${20} + Config Broker central + Config Broker rrd + Config Broker module ${1} + Broker Config Log central sql debug + Config Broker Sql Output central unified_sql + Broker Config Add Item module0 bbdo_version 3.0.1 + Broker Config Add Item rrd bbdo_version 3.0.1 + Broker Config Add Item central bbdo_version 3.0.1 + ${serv_id} Create Anomaly Detection ${0} ${1} ${1} metric + ${predict_data} Evaluate [[0,50,52],[2648812678,50,63]] + Create Anomaly Threshold File /tmp/anomaly_threshold.json ${1} ${serv_id} metric ${predict_data} + Clear Retention + Clear Db services + Clear Db downtimes + Start Broker + ${start} Get Current Date + Start Engine + # Let's wait for the check of external commands + ${content} Create List check_for_external_commands + ${result} Find In Log with Timeout ${engineLog0} ${start} ${content} 60 + Should Be True ${result} msg=No check for external commands executed for 1mn. + + #create dependent service downtime + Schedule Service Fixed Downtime host_1 service_1 3600 + + ${result} Check Service Downtime With Timeout host_1 anomaly_${serv_id} 1 60 + Should Be True ${result} msg=anomaly service must be in downtime + + DELETE SERVICE DOWNTIME host_1 anomaly_${serv_id} + ${result} Check Service Downtime With Timeout host_1 anomaly_${serv_id} 0 60 + Should Be True ${result} msg=anomaly service must be in downtime + Sleep 2s + ${result} Check Service Downtime With Timeout host_1 service_1 1 60 + Should Be True ${result} msg=dependent service must be in downtime + + + Stop Engine + Kindly Stop Broker ANO_DT4 - [Documentation] set dt on anomaly and on dependent service, delete last one don t delete first one - [Tags] Broker Engine Anomaly - Config Engine ${1} ${50} ${20} - Config Broker central - Config Broker rrd - Config Broker module ${1} - Broker Config Log central sql debug - Config Broker Sql Output central unified_sql - Broker Config Add Item module0 bbdo_version 3.0.1 - Broker Config Add Item rrd bbdo_version 3.0.1 - Broker Config Add Item central bbdo_version 3.0.1 - ${serv_id}= Create Anomaly Detection ${0} ${1} ${1} metric - ${predict_data} = Evaluate [[0,50,52],[2648812678,50,63]] - Create Anomaly Threshold File /tmp/anomaly_threshold.json ${1} ${serv_id} metric ${predict_data} - Clear Retention - Clear Db services - Clear Db downtimes - Start Broker - ${start}= Get Current Date - Start Engine - # Let's wait for the check of external commands - ${content}= Create List check_for_external_commands - ${result}= Find In Log with Timeout ${engineLog0} ${start} ${content} 60 - Should Be True ${result} msg=No check for external commands executed for 1mn. - - #create dependent service downtime - Schedule Service Fixed Downtime host_1 service_1 3600 - Schedule Service Fixed Downtime host_1 anomaly_${serv_id} 3600 - - ${result}= Check Service Downtime With Timeout host_1 anomaly_${serv_id} 2 60 - Should Be True ${result} msg=anomaly service must be in double downtime - - DELETE SERVICE DOWNTIME host_1 service_1 - ${result}= Check Service Downtime With Timeout host_1 service_1 0 60 - Should Be True ${result} msg=dependent service mustn t be in downtime - ${result}= Check Service Downtime With Timeout host_1 anomaly_${serv_id} 1 60 - Should Be True ${result} msg=anomaly service must be in simple downtime - - - Stop Engine - Kindly Stop Broker - - - - - + [Documentation] set dt on anomaly and on dependent service, delete last one don t delete first one + [Tags] Broker Engine Anomaly + Config Engine ${1} ${50} ${20} + Config Broker central + Config Broker rrd + Config Broker module ${1} + Broker Config Log central sql debug + Config Broker Sql Output central unified_sql + Broker Config Add Item module0 bbdo_version 3.0.1 + Broker Config Add Item rrd bbdo_version 3.0.1 + Broker Config Add Item central bbdo_version 3.0.1 + ${serv_id} Create Anomaly Detection ${0} ${1} ${1} metric + ${predict_data} Evaluate [[0,50,52],[2648812678,50,63]] + Create Anomaly Threshold File /tmp/anomaly_threshold.json ${1} ${serv_id} metric ${predict_data} + Clear Retention + Clear Db services + Clear Db downtimes + Start Broker + ${start} Get Current Date + Start Engine + # Let's wait for the check of external commands + ${content} Create List check_for_external_commands + ${result} Find In Log with Timeout ${engineLog0} ${start} ${content} 60 + Should Be True ${result} msg=No check for external commands executed for 1mn. + + #create dependent service downtime + Schedule Service Fixed Downtime host_1 service_1 3600 + Schedule Service Fixed Downtime host_1 anomaly_${serv_id} 3600 + + ${result} Check Service Downtime With Timeout host_1 anomaly_${serv_id} 2 60 + Should Be True ${result} msg=anomaly service must be in double downtime + + DELETE SERVICE DOWNTIME host_1 service_1 + ${result} Check Service Downtime With Timeout host_1 service_1 0 60 + Should Be True ${result} msg=dependent service mustn t be in downtime + ${result} Check Service Downtime With Timeout host_1 anomaly_${serv_id} 1 60 + Should Be True ${result} msg=anomaly service must be in simple downtime + + + Stop Engine + Kindly Stop Broker + + +ANO_NOFILE_VERIF_CONFIG_NO_ERROR + [Documentation] an anomaly detection without threshold file doesn't display error on config check + [Tags] broker engine anomaly MON-35579 + Config Engine ${1} ${50} ${20} + Create Anomaly Detection ${0} ${1} ${1} metric + Remove File /tmp/anomaly_threshold.json + Clear Retention + Create Directory ${ENGINE_LOG}/config0 + Start Process + ... /usr/sbin/centengine + ... -v + ... ${EtcRoot}/centreon-engine/config0/centengine.cfg + ... alias=e0 + ... stderr=${engineLog0} + ... stdout=${engineLog0} + ${result} Wait For Process e0 30 + Should Be Equal As Integers ${result.rc} 0 engine not gracefully stopped + ${content} Grep File ${engineLog0} Fail to read thresholds file + Should Be True len("""${content}""") < 2 anomalydetection error message must not be found diff --git a/tests/broker-engine/downtimes.robot b/tests/broker-engine/downtimes.robot index 641149ca17f..c5c554acfae 100644 --- a/tests/broker-engine/downtimes.robot +++ b/tests/broker-engine/downtimes.robot @@ -1,252 +1,298 @@ *** Settings *** -Resource ../resources/resources.robot -Suite Setup Clean Downtimes Before Suite -Suite Teardown Clean After Suite -Test Setup Stop Processes -Test Teardown Save logs If Failed - -Documentation Centreon Broker and Engine progressively add services -Library Process -Library DatabaseLibrary -Library OperatingSystem -Library DateTime -Library Collections -Library ../resources/Engine.py -Library ../resources/Broker.py -Library ../resources/Common.py +Resource ../resources/resources.robot +Suite Setup Clean Downtimes Before Suite +Suite Teardown Clean After Suite +Test Setup Stop Processes +Test Teardown Save logs If Failed + +Documentation Centreon Broker and Engine progressively add services +Library Process +Library DatabaseLibrary +Library OperatingSystem +Library DateTime +Library Collections +Library ../resources/Engine.py +Library ../resources/Broker.py +Library ../resources/Common.py *** Test Cases *** BEDTMASS1 - [Documentation] 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 - [Tags] Broker Engine services protobuf - Config Engine ${3} ${50} ${20} - Engine Config Set Value ${0} log_level_functions trace - Engine Config Set Value ${1} log_level_functions trace - Engine Config Set Value ${2} log_level_functions trace - Config Broker rrd - Config Broker central - Config Broker module ${3} - Broker Config Log central sql debug - Broker Config Log module0 neb debug - Broker Config Log module1 neb debug - Broker Config Log module2 neb debug - - Broker Config Add Item module0 bbdo_version 3.0.0 - Broker Config Add Item module1 bbdo_version 3.0.0 - Broker Config Add Item module2 bbdo_version 3.0.0 - Broker Config Add Item central bbdo_version 3.0.0 - Broker Config Add Item rrd bbdo_version 3.0.0 - Broker Config Log central sql debug - Config Broker Sql Output central unified_sql - Clear Retention - ${start}= Get Current Date - Start Broker - Start Engine - # Let's wait for the initial service states. - ${content}= Create List INITIAL SERVICE STATE: host_50;service_1000; - ${result}= Find In Log with Timeout ${engineLog2} ${start} ${content} 60 - Should Be True ${result} msg=An Initial service state on service (50, 1000) should be raised before we can start external commands. - - # It's time to schedule downtimes - FOR ${i} IN RANGE ${17} - ${host0}= Catenate SEPARATOR= host_ ${i + 1} - ${host1}= Catenate SEPARATOR= host_ ${i + 18} - ${host2}= Catenate SEPARATOR= host_ ${i + 35} - Schedule host downtime ${0} ${host0} ${3600} - Schedule host downtime ${1} ${host1} ${3600} - Schedule host downtime ${2} ${host2} ${3600} - END - - ${result}= check number of downtimes ${1050} ${start} ${60} - Should be true ${result} msg=We should have 1050 downtimes enabled. - - # It's time to delete downtimes - FOR ${i} IN RANGE ${17} - ${host0}= Catenate SEPARATOR= host_ ${i + 1} - ${host1}= Catenate SEPARATOR= host_ ${i + 18} - ${host2}= Catenate SEPARATOR= host_ ${i + 35} - Delete host downtimes ${0} ${host0} - Delete host downtimes ${1} ${host1} - Delete host downtimes ${2} ${host2} - END - - ${result}= check number of downtimes ${0} ${start} ${60} - Should be true ${result} msg=We should have no downtime enabled. - - Stop Engine - Kindly Stop Broker + [Documentation] 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 + [Tags] Broker Engine services protobuf + Config Engine ${3} ${50} ${20} + Engine Config Set Value ${0} log_level_functions trace + Engine Config Set Value ${1} log_level_functions trace + Engine Config Set Value ${2} log_level_functions trace + Config Broker rrd + Config Broker central + Config Broker module ${3} + Broker Config Log central sql debug + Broker Config Log module0 neb debug + Broker Config Log module1 neb debug + Broker Config Log module2 neb debug + + Broker Config Add Item module0 bbdo_version 3.0.0 + Broker Config Add Item module1 bbdo_version 3.0.0 + Broker Config Add Item module2 bbdo_version 3.0.0 + Broker Config Add Item central bbdo_version 3.0.0 + Broker Config Add Item rrd bbdo_version 3.0.0 + Broker Config Log central sql debug + Config Broker Sql Output central unified_sql + Clear Retention + ${start} Get Current Date + Start Broker + Start Engine + # Let's wait for the external command check start + ${content} Create List check_for_external_commands() + ${result} Find In Log With Timeout ${engineLog2} ${start} ${content} 60 + Should Be True ${result} A message telling check_for_external_commands() should be available. + + # It's time to schedule downtimes + FOR ${i} IN RANGE ${17} + Schedule Host Downtime ${0} host_${i + 1} ${3600} + Schedule Host Downtime ${1} host_${i + 18} ${3600} + Schedule Host Downtime ${2} host_${i + 35} ${3600} + END + + ${result} check number of downtimes ${1050} ${start} ${60} + Should be true ${result} We should have 1050 downtimes enabled. + + # It's time to delete downtimes + FOR ${i} IN RANGE ${17} + Delete Host Downtimes ${0} host_${i + 1} + Delete Host Downtimes ${1} host_${i + 18} + Delete Host Downtimes ${2} host_${i + 35} + END + + ${result} check number of downtimes ${0} ${start} ${60} + Should be true ${result} We should have no downtime enabled. + + Stop Engine + Kindly Stop Broker BEDTMASS2 - [Documentation] 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 - [Tags] Broker Engine services protobuf - Config Engine ${3} ${50} ${20} - Engine Config Set Value ${0} log_level_functions trace - Engine Config Set Value ${1} log_level_functions trace - Engine Config Set Value ${2} log_level_functions trace - Config Broker rrd - Config Broker central - Config Broker module ${3} - Broker Config Log central sql debug - Broker Config Log module0 neb debug - Broker Config Log module1 neb debug - Broker Config Log module2 neb debug - - Broker Config Log central sql debug - Clear Retention - ${start}= Get Current Date - Start Broker - Start Engine - # Let's wait for the initial service states. - ${content}= Create List INITIAL SERVICE STATE: host_50;service_1000; - ${result}= Find In Log with Timeout ${engineLog2} ${start} ${content} 60 - Should Be True ${result} msg=An Initial service state on service (50, 1000) should be raised before we can start external commands. - - # It's time to schedule downtimes - FOR ${i} IN RANGE ${17} - ${host0}= Catenate SEPARATOR= host_ ${i + 1} - ${host1}= Catenate SEPARATOR= host_ ${i + 18} - ${host2}= Catenate SEPARATOR= host_ ${i + 35} - Schedule host downtime ${0} ${host0} ${3600} - Schedule host downtime ${1} ${host1} ${3600} - Schedule host downtime ${2} ${host2} ${3600} - END - - ${result}= check number of downtimes ${1050} ${start} ${60} - Should be true ${result} msg=We should have 1050 downtimes enabled. - - # It's time to delete downtimes - FOR ${i} IN RANGE ${17} - ${host0}= Catenate SEPARATOR= host_ ${i + 1} - ${host1}= Catenate SEPARATOR= host_ ${i + 18} - ${host2}= Catenate SEPARATOR= host_ ${i + 35} - Delete host downtimes ${0} ${host0} - Delete host downtimes ${1} ${host1} - Delete host downtimes ${2} ${host2} - END - - ${result}= check number of downtimes ${0} ${start} ${60} - Should be true ${result} msg=We should have no downtime enabled. - - Stop Engine - Kindly Stop Broker + [Documentation] 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 + [Tags] Broker Engine services protobuf + Config Engine ${3} ${50} ${20} + Engine Config Set Value ${0} log_level_functions trace + Engine Config Set Value ${1} log_level_functions trace + Engine Config Set Value ${2} log_level_functions trace + Config Broker rrd + Config Broker central + Config Broker module ${3} + Broker Config Log central sql debug + Broker Config Log module0 neb debug + Broker Config Log module1 neb debug + Broker Config Log module2 neb debug + + Broker Config Log central sql debug + Clear Retention + ${start} Get Current Date + Start Broker + Start Engine + # Let's wait for the external command check start + ${content} Create List check_for_external_commands() + ${result} Find In Log With Timeout ${engineLog2} ${start} ${content} 60 + Should Be True ${result} A message telling check_for_external_commands() should be available. + + # It's time to schedule downtimes + FOR ${i} IN RANGE ${17} + Schedule Host Downtime ${0} host_${i + 1} ${3600} + Schedule Host Downtime ${1} host_${i + 18} ${3600} + Schedule Host Downtime ${2} host_${i + 35} ${3600} + END + + ${result} check number of downtimes ${1050} ${start} ${60} + Should be true ${result} We should have 1050 downtimes enabled. + + # It's time to delete downtimes + FOR ${i} IN RANGE ${17} + Delete Host Downtimes ${0} host_${i + 1} + Delete Host Downtimes ${1} host_${i + 18} + Delete Host Downtimes ${2} host_${i + 35} + END + + ${result} check number of downtimes ${0} ${start} ${60} + Should be true ${result} We should have no downtime enabled. + + Stop Engine + Kindly Stop Broker BEDTSVCREN1 - [Documentation] 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. - [Tags] Broker Engine services downtime - Config Engine ${1} - Engine Config Set Value ${0} log_level_functions trace - Config Broker rrd - Config Broker central - Config Broker module ${1} - Broker Config Log central sql debug - Broker Config Log module0 neb debug + [Documentation] 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. + [Tags] Broker Engine services downtime + Config Engine ${1} + Engine Config Set Value ${0} log_level_functions trace + Config Broker rrd + Config Broker central + Config Broker module ${1} + Broker Config Log central sql debug + Broker Config Log module0 neb debug - Clear Retention - ${start}= Get Current Date - Start Broker - Start Engine - # Let's wait for the check of external commands - ${content}= Create List check_for_external_commands - ${result}= Find In Log with Timeout ${engineLog0} ${start} ${content} 60 - Should Be True ${result} msg=No check for external commands executed for 1mn. + Clear Retention + ${start} Get Current Date + Start Broker + Start Engine + # Let's wait for the check of external commands + ${content} Create List check_for_external_commands + ${result} Find In Log with Timeout ${engineLog0} ${start} ${content} 60 + Should Be True ${result} No check for external commands executed for 1mn. - # It's time to schedule a downtime - Schedule service downtime host_1 service_1 ${3600} + # It's time to schedule a downtime + Schedule service downtime host_1 service_1 ${3600} - ${result}= check number of downtimes ${1} ${start} ${60} - Should be true ${result} msg=We should have 1 downtime enabled. + ${result} check number of downtimes ${1} ${start} ${60} + Should be true ${result} We should have 1 downtime enabled. - # Let's rename the service service_1 - Rename Service ${0} host_1 service_1 toto_1 + # Let's rename the service service_1 + Rename Service ${0} host_1 service_1 toto_1 - Reload Engine - # Let's wait for the check of external commands - ${content}= Create List check_for_external_commands - ${result}= Find In Log with Timeout ${engineLog0} ${start} ${content} 60 - Should Be True ${result} msg=No check for external commands executed for 1mn. + Reload Engine + # Let's wait for the check of external commands + ${content} Create List check_for_external_commands + ${result} Find In Log with Timeout ${engineLog0} ${start} ${content} 60 + Should Be True ${result} No check for external commands executed for 1mn. - Delete service downtime full ${0} host_1 toto_1 + Delete service downtime full ${0} host_1 toto_1 - ${result}= check number of downtimes ${0} ${start} ${60} - Should be true ${result} msg=We should have no downtime enabled. + ${result} check number of downtimes ${0} ${start} ${60} + Should be true ${result} We should have no downtime enabled. - Stop Engine - Kindly Stop Broker + Stop Engine + Kindly Stop Broker BEDTSVCFIXED - [Documentation] 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. - [Tags] Broker Engine downtime - Config Engine ${1} - Engine Config Set Value ${0} log_level_functions trace - Config Broker rrd - Config Broker central - Config Broker module ${1} - Broker Config Log central sql debug - Broker Config Log module0 neb debug - - Clear Retention - ${start}= Get Current Date - Start Broker - Start Engine - # Let's wait for the check of external commands - ${content}= Create List check_for_external_commands - ${result}= Find In Log with Timeout ${engineLog0} ${start} ${content} 60 - Should Be True ${result} msg=No check for external commands executed for 1mn. - - # It's time to schedule a downtime - Schedule service downtime host_1 service_1 ${3600} - - ${result}= check number of downtimes ${1} ${start} ${60} - Should be true ${result} msg=We should have 1 downtime enabled. - - Delete service downtime full ${0} host_1 service_1 - - ${result}= check number of downtimes ${0} ${start} ${60} - Should be true ${result} msg=We should have no downtime enabled. - - Stop Engine - Kindly Stop Broker + [Documentation] 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. + [Tags] Broker Engine downtime + Config Engine ${1} + Engine Config Set Value ${0} log_level_functions trace + Config Broker rrd + Config Broker central + Config Broker module ${1} + Broker Config Log central sql debug + Broker Config Log module0 neb debug + + Clear Retention + ${start} Get Current Date + Start Broker + Start Engine + # Let's wait for the check of external commands + ${content} Create List check_for_external_commands + ${result} Find In Log with Timeout ${engineLog0} ${start} ${content} 60 + Should Be True ${result} No check for external commands executed for 1mn. + + # It's time to schedule a downtime + Schedule service downtime host_1 service_1 ${3600} + + ${result} check number of downtimes ${1} ${start} ${60} + Should be true ${result} We should have 1 downtime enabled. + + Delete service downtime full ${0} host_1 service_1 + + ${result} check number of downtimes ${0} ${start} ${60} + Should be true ${result} We should have no downtime enabled. + + Stop Engine + Kindly Stop Broker BEDTHOSTFIXED - [Documentation] 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. - [Tags] Broker Engine downtime - Config Engine ${1} - Engine Config Set Value ${0} log_level_functions trace - Config Broker rrd - Config Broker central - Config Broker module ${1} - Broker Config Log central sql debug - Broker Config Log module0 neb debug - Config Broker Sql Output central unified_sql - - Clear Retention - ${start}= Get Current Date - Start Broker - Start Engine - # Let's wait for the check of external commands - ${content}= Create List check_for_external_commands - ${result}= Find In Log with Timeout ${engineLog0} ${start} ${content} 60 - Should Be True ${result} msg=No check for external commands executed for 1mn. - - # It's time to schedule downtimes - Schedule host fixed downtime ${0} host_1 ${3600} - - ${result}= check number of downtimes ${21} ${start} ${60} - Should be true ${result} msg=We should have 21 downtimes (1 host + 20 services) enabled. - - # It's time to delete downtimes - Delete host downtimes ${0} host_1 - - ${result}= check number of downtimes ${0} ${start} ${60} - Should be true ${result} msg=We should have no downtime enabled. - - Stop Engine - Kindly Stop Broker + [Documentation] 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. + [Tags] Broker Engine downtime + Config Engine ${1} + Engine Config Set Value ${0} log_level_functions trace + Config Broker rrd + Config Broker central + Config Broker module ${1} + Broker Config Log central sql debug + Broker Config Log module0 neb debug + Config Broker Sql Output central unified_sql + + Clear Retention + ${start} Get Current Date + Start Broker + Start Engine + # Let's wait for the check of external commands + ${content} Create List check_for_external_commands + ${result} Find In Log with Timeout ${engineLog0} ${start} ${content} 60 + Should Be True ${result} No check for external commands executed for 1mn. + + # It's time to schedule downtimes + Schedule host fixed downtime ${0} host_1 ${3600} + + ${result} check number of downtimes ${21} ${start} ${60} + Should be true ${result} We should have 21 downtimes (1 host + 20 services) enabled. + + # It's time to delete downtimes + Delete host downtimes ${0} host_1 + + ${result} check number of downtimes ${0} ${start} ${60} + Should be true ${result} We should have no downtime enabled. + + Stop Engine + Kindly Stop Broker + +DTIM + [Documentation] 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 + [Tags] broker engine services host downtimes MON-36711 + Config Engine ${5} ${250} ${20} + Engine Config Set Value ${0} log_level_functions trace + Engine Config Set Value ${1} log_level_functions trace + Engine Config Set Value ${2} log_level_functions trace + Engine Config Set Value ${3} log_level_functions trace + Engine Config Set Value ${4} log_level_functions trace + Config Broker rrd + Config Broker central + Config Broker module ${5} + Broker Config Add Item module0 bbdo_version 3.0.1 + Broker Config Add Item module1 bbdo_version 3.0.1 + Broker Config Add Item module2 bbdo_version 3.0.1 + Broker Config Add Item module3 bbdo_version 3.0.1 + Broker Config Add Item module4 bbdo_version 3.0.1 + Broker Config Add Item central bbdo_version 3.0.1 + Broker Config Add Item rrd bbdo_version 3.0.1 + Config Broker Sql Output central unified_sql + Clear Retention + + ${start} Get Current Date + Start Broker + Start Engine + + # Let's wait for the external command check start + ${content} Create List check_for_external_commands() + ${result} Find In Log With Timeout ${engineLog4} ${start} ${content} 60 + Should Be True ${result} A message telling check_for_external_commands() should be available. + + # It's time to schedule downtimes + FOR ${i} IN RANGE ${50} + Schedule Host Fixed Downtime ${0} host_${i + 1} ${3600} + Schedule Host Fixed Downtime ${1} host_${i + 51} ${3600} + Schedule Host Fixed Downtime ${2} host_${i + 101} ${3600} + Schedule Host Fixed Downtime ${3} host_${i + 151} ${3600} + Schedule Host Fixed Downtime ${4} host_${i + 201} ${3600} + END + + ${result} Check Number Of Downtimes ${5250} ${start} ${60} + Should be true ${result} We should have 5250 downtimes enabled. + + # It's time to delete downtimes + FOR ${i} IN RANGE ${50} + Delete Host Downtimes ${0} host_${i + 1} + Delete Host Downtimes ${1} host_${i + 51} + Delete Host Downtimes ${2} host_${i + 101} + Delete Host Downtimes ${3} host_${i + 151} + Delete Host Downtimes ${4} host_${i + 201} + END + + ${result} Check Number Of Downtimes ${0} ${start} ${60} + Should Be True ${result} There are still some downtimes enabled. + + Stop Engine + Kindly Stop Broker *** Keywords *** Clean Downtimes Before Suite - Clean Before Suite - - Connect To Database pymysql ${DBName} ${DBUser} ${DBPass} ${DBHost} ${DBPort} - ${output}= Execute SQL String DELETE FROM downtimes WHERE deletion_time IS NULL + Clean Before Suite + + Connect To Database pymysql ${DBName} ${DBUser} ${DBPass} ${DBHost} ${DBPort} + ${output} Execute SQL String DELETE FROM downtimes WHERE deletion_time IS NULL diff --git a/tests/resources/Broker.py b/tests/resources/Broker.py index 460dd601473..abac5b0f370 100755 --- a/tests/resources/Broker.py +++ b/tests/resources/Broker.py @@ -420,6 +420,13 @@ def _apply_conf(name, callback): def config_broker(name, poller_inst: int = 1): + """ + Configure a broker instance for test. Write the configuration files. + + Args: + name (str): name of the conf broker wanted + poller_inst (int, optional): Defaults to 1. + """ makedirs(ETC_ROOT, mode=0o777, exist_ok=True) makedirs(VAR_ROOT, mode=0o777, exist_ok=True) makedirs(ETC_ROOT + "/centreon-broker", mode=0o777, exist_ok=True) @@ -470,6 +477,12 @@ def config_broker(name, poller_inst: int = 1): def change_broker_tcp_output_to_grpc(name: str): + """ + Update broker configuration to use a gRPC output instead of a TCP one. + + Args: + name (str): name of the conf broker wanted to be changed + """ def output_to_grpc(conf): output_dict = conf["centreonBroker"]["output"] for i, v in enumerate(output_dict): @@ -479,6 +492,14 @@ def output_to_grpc(conf): def add_path_to_rrd_output(name: str, path: str): + """ + Set the path for the rrd output. If no rrd output is defined, this function + does nothing. + + Args: + name (str): The broker instance name among central, rrd and module%d. + path (str): path to the rrd output. + """ def rrd_output(conf): output_dict = conf["centreonBroker"]["output"] for i, v in enumerate(output_dict): @@ -488,6 +509,13 @@ def rrd_output(conf): def change_broker_tcp_input_to_grpc(name: str): + """ + Update the broker configuration to use gRPC input instead of a TCP one. + If no tcp input is found, no replacement is done. + + Args: + name: The broker instance name among central, rrd and module%d. + """ def input_to_grpc(conf): input_dict = conf["centreonBroker"]["input"] for i, v in enumerate(input_dict): @@ -506,6 +534,18 @@ def add_broker_crypto(json_dict, add_cert: bool, only_ca_cert: bool): def add_broker_tcp_input_grpc_crypto(name: str, add_cert: bool, reversed: bool): + """ + Add some crypto to broker gRPC input. + + Args: + name: The broker instance name among central, rrd and module%d. + add_cert (bool): True to add a certificate, False otherwise. + reversed (bool): True if only a CA certificate is provided. + + *Example:* + + | Add Broker Tcp Input Grpc Crypto | central | ${True} | ${False} | + """ def crypto_modifier(conf): input_dict = conf["centreonBroker"]["input"] for i, v in enumerate(input_dict): @@ -515,6 +555,18 @@ def crypto_modifier(conf): def add_broker_tcp_output_grpc_crypto(name: str, add_cert: bool, reversed: bool): + """ + Add grpc crypto to broker tcp output + + Args: + name: The broker instance name among central, rrd and module%d. + add_cert (bool): True to add a certificate, False otherwise. + reversed (bool): False if only a we just want a CA certificate. + + *Example:* + + | Add Broker Tcp Output Grpc Crypto | module0 | ${True} | ${False} | + """ def crypto_modifier(conf): input_dict = conf["centreonBroker"]["output"] for i, v in enumerate(input_dict): @@ -524,6 +576,19 @@ def crypto_modifier(conf): def add_host_to_broker_output(name: str, output_name: str, host_ip: str): + """ + Add a host to some broker output. This is useful for a grpc or tcp client + where we want where to connect to. + + Args: + name (str): The broker instance name among central, rrd and module%d. + output_name (str): The name of the output to modify. + host_ip (str): the host address to set. + + *Example:* + + | Add Host To Broker Output | module0 | central-module-master-output | localhost | + """ def modifier(conf): input_dict = conf["centreonBroker"]["output"] for i, v in enumerate(input_dict): @@ -533,6 +598,19 @@ def modifier(conf): def add_host_to_broker_input(name: str, input_name: str, host_ip: str): + """ + Add host to some broker input. This is useful for a grpc or tcp client + where we want to set where to connect to. + + Args: + name: The broker instance name among central, rrd and module%d. + input_name (str): the name of the input to modify. + host_ip (str): the host address to set. + + *Example:* + + | Add Host To Broker Input | central | central-broker-master-input | localhost | + """ def modifier(conf): input_dict = conf["centreonBroker"]["input"] for i, v in enumerate(input_dict): @@ -542,6 +620,17 @@ def modifier(conf): def remove_host_from_broker_output(name: str, output_name: str): + """ + Remove the host entry from a broker output given by its name. + + Args: + name: The broker instance name among central, rrd and module%d. + output_name (str): The name of the output containing a host entry. + + *Example:* + + | Remove Host From Broker Output | module0 | central-module-master-output | + """ def modifier(conf): input_dict = conf["centreonBroker"]["output"] for i, v in enumerate(input_dict): @@ -551,6 +640,17 @@ def modifier(conf): def remove_host_from_broker_input(name: str, input_name: str): + """ + Remove the host entry from a broker input given by its name. + + Args: + name: The broker instance name among central, rrd and module%d. + input_name (str): The name of the input containing a host entry. + + *Example:* + + | Remove Host From Broker Input | central | central-broker-master-input | + """ def modifier(conf): input_dict = conf["centreonBroker"]["input"] for i, v in enumerate(input_dict): @@ -560,6 +660,18 @@ def modifier(conf): def change_broker_compression_output(config_name: str, output_name: str, compression_value: str): + """ + Change the compression option of a broker output. + + Args: + config_name (str): The broker instance name among central, rrd and module%d. + output_name (str): The output name to modify. + compression_value (str): The compression value. "yes/no", "1/0" or "true/false". + + *Example:* + + | Change Broker Compression Output | module0 | central-module-master-output | yes | + """ def compression_modifier(conf): output_dict = conf["centreonBroker"]["output"] for i, v in enumerate(output_dict): @@ -569,6 +681,18 @@ def compression_modifier(conf): def change_broker_compression_input(config_name: str, input_name: str, compression_value: str): + """ + Change the compression option of a broker input. + + Args: + config_name (str): The broker instance name among central, rrd and module%d. + input_name (str): The input name to modify. + compression_value (str): The compression value: "yes/no", "1/0" or "true/false". + + *Example:* + + | Change Broker Compression Input | central | central-broker-master-input | yes | + """ def compression_modifier(conf): input_dict = conf["centreonBroker"]["input"] for i, v in enumerate(input_dict): @@ -578,6 +702,23 @@ def compression_modifier(conf): def config_broker_bbdo_input(name, stream, port, proto, host=None): + """ + Configure Broker BBDO input. It can be a client or a server. We provide a + port number and a protocol that is grpc or tcp. + + Args: + name: The broker instance name among central, rrd and module%d. + stream: The type of stream among [bbdo_server, bbdo_client]. + port: A port number. + proto: grpc or tcp. + host (str, optional): Defaults to None. Used to provide a host, needed + in the case of bbdo_client. + + *Example:* + + | Config Broker Bbdo Input | central | bbdo_server | 5669 | grpc | | + | Config Broker Bbdo Input | rrd | bbdo_client | 5670 | tcp | localhost | + """ if stream != "bbdo_server" and stream != "bbdo_client": raise Exception( "config_broker_bbdo_input_output() function only accepts stream in ('bbdo_server', 'bbdo_client')") @@ -614,6 +755,22 @@ def config_broker_bbdo_input(name, stream, port, proto, host=None): def config_broker_bbdo_output(name, stream, port, proto, host=None): + """ + Configure Broker BBDO output. It can be a client or a server. We provide a + port number and a protocol that is grpc or tcp. + + Args: + name: The broker instance name among central, rrd and module%d. + stream (str): The type of stream among [bbdo_server, bbdo_client]. + port (int): A port number. + proto (str): grpc or tcp. + host (str, optional): Defaults to None. Used to provide a host to connect, + needed in the case of bbdo_client. + + *Example:* + + | Config Broker Bbdo Output | central | bbdo_client | 5670 | tcp | localhost | + """ if stream != "bbdo_server" and stream != "bbdo_client": raise Exception( "config_broker_bbdo_output() function only accepts stream in ('bbdo_server', 'bbdo_client')") @@ -650,6 +807,14 @@ def config_broker_bbdo_output(name, stream, port, proto, host=None): def config_broker_sql_output(name, output, queries_per_transaction: int = 20000): + """ + Configure the broker sql output. + + Args: + name (str): The broker instance name among central, rrd and module%d. + output (str): One string among "unified_sql" and "sql/perfdata". + queries_per_transaction (int, optional): Defaults to 20000. + """ if name == 'central': filename = "central-broker.json" elif name.startswith('module'): @@ -729,6 +894,18 @@ def config_broker_sql_output(name, output, queries_per_transaction: int = 20000) def broker_config_clear_outputs_except(name, ex: list): + """ + Remove all the outputs of the broker configuration except those of types given + in the ex list. + + Args: + name: The broker instance name among central, rrd and module%d. + ex (list): A list of type. + + *Example:* + + | Broker Config Clear Outputs Except | central | ["sql", "storage"] | + """ if name == 'central': filename = "central-broker.json" elif name.startswith('module'): @@ -751,6 +928,18 @@ def broker_config_clear_outputs_except(name, ex: list): def broker_config_add_item(name, key, value): + """ + Add an item to the broker configuration + + Args: + name (str): Which broker instance: central, rrd or module%d. + key (str): The key to add directly in the configuration first level. + value: The value. + + *Example:* + + | Broker Config Add Item | module0 | bbdo_version | 3.0.1 | + """ if name == 'central': filename = "central-broker.json" elif name == 'rrd': @@ -769,6 +958,17 @@ def broker_config_add_item(name, key, value): def broker_config_remove_item(name, key): + """ + Remove an item from the broker configuration + + Args: + name: The broker instance name among central, rrd and module%d + key: The key to remove. It must be defined at the first level of the configuration. + + *Example:* + + | Broker Config Remove Item | module0 | bbdo_version | + """ if name == 'central': filename = "central-broker.json" elif name == 'rrd': @@ -787,6 +987,18 @@ def broker_config_remove_item(name, key): def broker_config_add_lua_output(name, output, luafile): + """ + Add a lua output to the broker configuration. + + Args: + name (str): The broker instance name among central, rrd, module%d + output (str): The name of the Lua output. + luafile (str): The full name of the Lua script. + + *Example:* + + | Broker Config Add Lua Output | central | test-protobuf | /tmp/lua.lua | + """ if name == 'central': filename = "central-broker.json" elif name.startswith('module'): @@ -810,6 +1022,19 @@ def broker_config_add_lua_output(name, output, luafile): def broker_config_output_set(name, output, key, value): + """ + Set an attribute value in a broker output. + + Args: + name (str): The broker instance among central, rrd, module%d. + output (str): The output to work with. + key (str): The key whose value is to modify. + value (str): The new value to set. + + *Example:* + + | Broker Config Output Set | central | central-broker-master-sql | host | localhost | + """ if name == 'central': filename = "central-broker.json" elif name.startswith('module'): @@ -829,6 +1054,19 @@ def broker_config_output_set(name, output, key, value): def broker_config_output_set_json(name, output, key, value): + """ + Set an attribute value in a broker output. The value is given as a json string. + + Args: + name (str): The broker instance among central, rrd, module%d. + output (str): The output to work with. + key (str): The key whose value is to modify. + value (str): The new value to set. + + *Example:* + + | Broker Config Output Set Json | central | central-broker-master-sql | filters | {"category": ["neb", "foo", "bar"]} | + """ if name == 'central': filename = "central-broker.json" elif name.startswith('module'): @@ -849,6 +1087,18 @@ def broker_config_output_set_json(name, output, key, value): def broker_config_output_remove(name, output, key): + """ + Remove a key from an output of the broker configuration. + + Args: + name: The broker instance among central, rrd, module%d. + output: The output to work with. + key: The key to remove. + + *Example:* + + | Broker Config Output Remove | central | centreon-broker-master-rrd | host | + """ if name == 'central': filename = "central-broker.json" elif name.startswith('module'): @@ -869,6 +1119,19 @@ def broker_config_output_remove(name, output, key): def broker_config_input_set(name, inp, key, value): + """ + Set an attribute in an input of a broker configuration. + + Args: + name (str): The broker instance among central, rrd, module%d. + inp (str): The input to work with. + key (str): The key whose value is to modify. + value (str): The new value to set. + + *Example:* + + | Broker Config Input Set | rrd | rrd-broker-master-input | encryption | yes | + """ if name == 'central': filename = "central-broker.json" elif name.startswith('module'): @@ -888,6 +1151,14 @@ def broker_config_input_set(name, inp, key, value): def broker_config_input_remove(name, inp, key): + """ + Remove a key from an input of the broker configuration. + + Args: + name: The broker instance among central, rrd, module%d. + inp: The input to work with. + key: The key to remove. + """ if name == 'central': filename = "central-broker.json" elif name.startswith('module'): @@ -908,6 +1179,18 @@ def broker_config_input_remove(name, inp, key): def broker_config_log(name, key, value): + """ + Configure broker log level. + + Args: + name (str): The broker instance among central, rrd, module%d. + key (str): The logger name to modify. + value (str): The level among error, trace, info, debug, etc... + + *Example:* + + | Broker Config Log | central | bam | trace | + """ if name == 'central': filename = "central-broker.json" elif name.startswith('module'): @@ -926,6 +1209,17 @@ def broker_config_log(name, key, value): def broker_config_flush_log(name, value): + """ + Configure the flush interval of the broker loggers. This value is in seconds, with 0, every logs are flushed. + + Args: + name (str): the broker instance among central, rrd, module%d. + value (int): The value in seconds. + + *Example:* + + | Broker Config Flush Log | central | 1 | + """ if name == 'central': filename = "central-broker.json" elif name.startswith('module'): @@ -944,6 +1238,17 @@ def broker_config_flush_log(name, value): def broker_config_source_log(name, value): + """ + Configure if logs should contain the source file and its line number. + + Args: + name: The broker instance name among central, rrd and module%d. + value: A boolean that can be "true/false", "1/0" or "yes/no". + + *Example:* + + | Broker Config Source Log | central | 1 | + """ if name == 'central': filename = "central-broker.json" elif name.startswith('module'): @@ -962,6 +1267,23 @@ def broker_config_source_log(name, value): def check_broker_stats_exist(name, key1, key2, timeout=TIMEOUT): + """ + Return True if the Broker stats file contain keys pair (key1,key2). key2 must + be a daughter key of key1. + + Should be true if the poller is connected to the central broker. + + Args: + name: The broker instance name among central, rrd and module%d. + key1 (str): A key at first level. + key2 (str): A key under the key1 key. + timeout (int, optional): . Defaults to TIMEOUT. + + *Example:* + + | ${exist} | Check Broker Stats Exist | mysql manager | poller | waiting tasks in connection 0 | + | Should Be True | ${exist} | + """ limit = time.time() + timeout while time.time() < limit: if name == 'central': @@ -989,6 +1311,18 @@ def check_broker_stats_exist(name, key1, key2, timeout=TIMEOUT): def get_broker_stats_size(name, key, timeout=TIMEOUT): + """ + Return the number of items under the given key in the stats file. + + Args: + name: The broker instance name among central, rrd and module%d. + key: The key to work with. + timeout (int, optional): Defaults to TIMEOUT = 30s. + + *Example:* + + | ${size} | Get Broker Stats Size | central | poller | # 2 | + """ limit = time.time() + timeout retval = 0 while time.time() < limit: @@ -1022,13 +1356,16 @@ def get_broker_stats_size(name, key, timeout=TIMEOUT): def get_broker_stats(name: str, expected: str, timeout: int, *keys): - """! - read a value from broker stats - @param name central, module or rrd - @param expected: value expected (regexp) - @timeout delay to find key in stats - @param keys keys in json stats output - @return True if value found and matches expected + """ + Read a value from the broker stats file following the given keys. If the value is the expected one, return True. + + Args: + name The broker instance to work with among central, module%d or rrd + expected: value expected (regexp) + timeout: duration in seconds after what the check fails. + keys: keys in json stats output + + Returns: True if the expected value was found, otherwise it returns False. """ def json_get(json_dict, keys: tuple, index: int): @@ -1069,14 +1406,21 @@ def json_get(json_dict, keys: tuple, index: int): return False -## -# @brief Gets count indexes that does not exist in index_data. -# -# @param count:int The number of indexes to get. -# -# @return a list of index ids. -# def get_not_existing_indexes(count: int): + """ + Gets count indexes that does not exist in the centreon_storage.index_data table. + + Args: + count (int): The number of indexes to get. + + *Example:* + + | @{indexes} | Get Not Existing Indexes | 10 | + | Log To Console | @{indexes} | + + Returns: + a list of index IDs. + """ # Connect to the database connection = pymysql.connect(host=DB_HOST, user=DB_USER, @@ -1107,14 +1451,20 @@ def get_not_existing_indexes(count: int): return ids_db -## -# @brief Gets count indexes from available ones. -# -# @param count:int The number of indexes to get. -# -# @return a list of index ids. -# def get_indexes_to_delete(count: int): + """ + Gets count indexes from centreon_storage.index_data that really exist. + + Args: + count (int): The number of indexes to get. + + *Example:* + + | @{indexes} | Get Not Existing Indexes | 10 | + + Returns: + A list of index IDs. + """ files = [os.path.basename(x) for x in glob.glob( VAR_ROOT + "/lib/centreon/metrics/[0-9]*.rrd")] ids = [int(f.split(".")[0]) for f in files] @@ -1148,7 +1498,8 @@ def get_indexes_to_delete(count: int): def delete_all_rrd_metrics(): - """! remove all rrd metrics files + """ + Remove all rrd metrics files. """ with os.scandir(VAR_ROOT + "/lib/centreon/metrics/") as it: for entry in it: @@ -1157,12 +1508,19 @@ def delete_all_rrd_metrics(): def check_rrd_info(metric_id: int, key: str, value, timeout: int = 60): - """! execute rrdtool info and check one value of the returned informations - @param metric_id - @param key key to search in the rrdtool info result - @param value value to search in the rrdtool info result fot key - @param timeout timeout for metric file creation - @return True if key = value found + """ + Execute rrdtool info and check one value of the returned informations + + Args: + metric_id (int): A metric ID. + key (str): The key whose value is to check. + value: The expected value. + timeout (int, optional): Defaults to 60. + + *Example:* + + | ${result} | Check Rrd Info | 1 | step | 60 | + | Should Be True | ${result} | """ limit = time.time() + timeout @@ -1180,11 +1538,23 @@ def check_rrd_info(metric_id: int, key: str, value, timeout: int = 60): def get_metrics_for_service(service_id: int, metric_name: str = "%", timeout: int = 60): - """! scan data base every 5s to extract metric ids for a service + """ + Try to get the metric IDs of a service. + + Warning: + A service is identified by a host ID and a service ID. This function should be used with caution. + + Args: + service_id (int): The ID of the service. + metric_name (str, optional): Defaults to "%". + timeout (int, optional): Defaults to 60. + + Returns: + A list of metric IDs or None if no metric found. + + *Example:* - @param service_id id of the service - @param timeout timeout in second - @return array of metric ids + | ${metrics} | Get Metrics For Service | 1 | % | """ limit = time.time() + timeout @@ -1211,14 +1581,20 @@ def get_metrics_for_service(service_id: int, metric_name: str = "%", timeout: in return None -## -# @brief Gets count metrics that does not exist. -# -# @param count:int The number of metrics to get. -# -# @return a list of metric ids. -# def get_not_existing_metrics(count: int): + """ + Return a list of metrics that does not exist. + + Args: + count (int): How many metric IDs do we want. + + Returns: + A list of IDs. + + *Example:* + + | @{metrics} | Get Not Existing Metrics | 10 | + """ files = [os.path.basename(x) for x in glob.glob( VAR_ROOT + "/lib/centreon/metrics/[0-9]*.rrd")] ids = [int(f.split(".")[0]) for f in files] @@ -1249,14 +1625,16 @@ def get_not_existing_metrics(count: int): return retval -## -# @brief Gets count metrics from available ones. -# -# @param count:int The number of metrics to get. -# -# @return a list of metric ids. -# def get_metrics_to_delete(count: int): + """ + Get count metrics from availables ones. + + Args: + count (int): The number of metrics to get. + + Returns: + A list of metric IDs. + """ files = [os.path.basename(x) for x in glob.glob( VAR_ROOT + "/lib/centreon/metrics/[0-9]*.rrd")] ids = [int(f.split(".")[0]) for f in files] @@ -1281,12 +1659,13 @@ def get_metrics_to_delete(count: int): return inter[:count] -## -# @brief creat metrics from available ones. -# -# @param count:int The number of metrics to create. -# def create_metrics(count: int): + """ + Create count metrics from available ones. + + Args: + count (int): How many metrics to create. + """ files = [os.path.basename(x) for x in glob.glob( VAR_ROOT + "/lib/centreon/metrics/[0-9]*.rrd")] ids = [int(f.split(".")[0]) for f in files] @@ -1330,6 +1709,14 @@ def create_metrics(count: int): def run_reverse_bam(duration, interval): + """ + Launch the map_client.py script that simulates map. + + Args: + duration: The duration in seconds before to stop map_client.py + interval: Interval given to the map_client.py that tells the duration + between to recv calls. + """ subp.Popen("broker/map_client.py {:f}".format(interval), shell=True, stdout=subp.PIPE, stdin=subp.PIPE) time.sleep(duration) @@ -1337,17 +1724,36 @@ def run_reverse_bam(duration, interval): def start_map(): + """ + Launch the map_client_types.py script that simulates map. + """ global map_process map_process = subp.Popen("broker/map_client_types.py", shell=True, stdout=subp.DEVNULL, stdin=subp.DEVNULL) def clear_map_logs(): + """ + Reset the content of the /tmp/map-output.log file. + """ with open('/tmp/map-output.log', 'w') as f: f.write("") def check_map_output(categories_str, expected_events, timeout: int = TIMEOUT): + """ + Check the content of the /tmp/map-output.log file. This file contains informations on categories/elements of each + received event. A list of categories and event types are given to this function, so it can check if the file + contain these types of events. If it contains them, True is returned. + + Args: + categories_str: A list of categories, for example ["1", "2"]. + expected_events: A list of event types. + timeout (int, optional): A number of seconds, the default value is TIMEOUT. + + Returns: + True on success, otherwise False. + """ retval = False limit = time.time() + timeout while time.time() < limit: @@ -1394,11 +1800,20 @@ def check_map_output(categories_str, expected_events, timeout: int = TIMEOUT): def get_map_output(): + """ + The map_client_types.py script writes on STDOUT. This function allows to get this output. + + Returns: + A string containing the output. + """ global map_process return map_process.communicate()[0] def stop_map(): + """ + Stop the script simulating map. Works with map_client_type. + """ for proc in psutil.process_iter(): if 'map_client_type' in proc.name(): logger.console( @@ -1420,13 +1835,17 @@ def stop_map(): logger.console("map_client_type stopped") -## -# @brief Get count indexes that are available to rebuild them. -# -# @param count is the number of indexes to get. -# -# @return a list of indexes def get_indexes_to_rebuild(count: int, nb_day=180): + """ + Get count indexes that are available to rebuild. + + Args: + count (int): The number of indexes to get. + nb_day (int, optional): Defaults to 180. + + Returns: + A list of indexes. + """ files = [os.path.basename(x) for x in glob.glob( VAR_ROOT + "/lib/centreon/metrics/[0-9]*.rrd")] ids = [int(f.split(".")[0]) for f in files] @@ -1470,12 +1889,13 @@ def get_indexes_to_rebuild(count: int, nb_day=180): return retval -## -# @brief add a value at the mid of the first day of each metric -# -# -# @return a list of indexes of pair